id
stringlengths
25
30
content
stringlengths
14
942k
max_stars_repo_path
stringlengths
49
55
crossvul-cpp_data_bad_3831_0
/* * L2TPv3 IP encapsulation support for IPv6 * * Copyright (c) 2012 Katalix Systems Ltd * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/icmp.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/random.h> #include <linux/socket.h> #include <linux/l2tp.h> #include <linux/in.h> #include <linux/in6.h> #include <net/sock.h> #include <net/ip.h> #include <net/icmp.h> #include <net/udp.h> #include <net/inet_common.h> #include <net/inet_hashtables.h> #include <net/tcp_states.h> #include <net/protocol.h> #include <net/xfrm.h> #include <net/transp_v6.h> #include <net/addrconf.h> #include <net/ip6_route.h> #include "l2tp_core.h" struct l2tp_ip6_sock { /* inet_sock has to be the first member of l2tp_ip6_sock */ struct inet_sock inet; u32 conn_id; u32 peer_conn_id; /* ipv6_pinfo has to be the last member of l2tp_ip6_sock, see inet6_sk_generic */ struct ipv6_pinfo inet6; }; static DEFINE_RWLOCK(l2tp_ip6_lock); static struct hlist_head l2tp_ip6_table; static struct hlist_head l2tp_ip6_bind_table; static inline struct l2tp_ip6_sock *l2tp_ip6_sk(const struct sock *sk) { return (struct l2tp_ip6_sock *)sk; } static struct sock *__l2tp_ip6_bind_lookup(struct net *net, struct in6_addr *laddr, int dif, u32 tunnel_id) { struct hlist_node *node; struct sock *sk; sk_for_each_bound(sk, node, &l2tp_ip6_bind_table) { struct in6_addr *addr = inet6_rcv_saddr(sk); struct l2tp_ip6_sock *l2tp = l2tp_ip6_sk(sk); if (l2tp == NULL) continue; if ((l2tp->conn_id == tunnel_id) && net_eq(sock_net(sk), net) && !(addr && ipv6_addr_equal(addr, laddr)) && !(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)) goto found; } sk = NULL; found: return sk; } static inline struct sock *l2tp_ip6_bind_lookup(struct net *net, struct in6_addr *laddr, int dif, u32 tunnel_id) { struct sock *sk = __l2tp_ip6_bind_lookup(net, laddr, dif, tunnel_id); if (sk) sock_hold(sk); return sk; } /* When processing receive frames, there are two cases to * consider. Data frames consist of a non-zero session-id and an * optional cookie. Control frames consist of a regular L2TP header * preceded by 32-bits of zeros. * * L2TPv3 Session Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Session ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Cookie (optional, maximum 64 bits)... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * L2TPv3 Control Message Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | (32 bits of zeros) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Control Connection ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Ns | Nr | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * All control frames are passed to userspace. */ static int l2tp_ip6_recv(struct sk_buff *skb) { struct sock *sk; u32 session_id; u32 tunnel_id; unsigned char *ptr, *optr; struct l2tp_session *session; struct l2tp_tunnel *tunnel = NULL; int length; /* Point to L2TP header */ optr = ptr = skb->data; if (!pskb_may_pull(skb, 4)) goto discard; session_id = ntohl(*((__be32 *) ptr)); ptr += 4; /* RFC3931: L2TP/IP packets have the first 4 bytes containing * the session_id. If it is 0, the packet is a L2TP control * frame and the session_id value can be discarded. */ if (session_id == 0) { __skb_pull(skb, 4); goto pass_up; } /* Ok, this is a data packet. Lookup the session. */ session = l2tp_session_find(&init_net, NULL, session_id); if (session == NULL) goto discard; tunnel = session->tunnel; if (tunnel == NULL) goto discard; /* Trace packet contents, if enabled */ if (tunnel->debug & L2TP_MSG_DATA) { length = min(32u, skb->len); if (!pskb_may_pull(skb, length)) goto discard; pr_debug("%s: ip recv\n", tunnel->name); print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length); } l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook); return 0; pass_up: /* Get the tunnel_id from the L2TP header */ if (!pskb_may_pull(skb, 12)) goto discard; if ((skb->data[0] & 0xc0) != 0xc0) goto discard; tunnel_id = ntohl(*(__be32 *) &skb->data[4]); tunnel = l2tp_tunnel_find(&init_net, tunnel_id); if (tunnel != NULL) sk = tunnel->sock; else { struct ipv6hdr *iph = ipv6_hdr(skb); read_lock_bh(&l2tp_ip6_lock); sk = __l2tp_ip6_bind_lookup(&init_net, &iph->daddr, 0, tunnel_id); read_unlock_bh(&l2tp_ip6_lock); } if (sk == NULL) goto discard; sock_hold(sk); if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_put; nf_reset(skb); return sk_receive_skb(sk, skb, 1); discard_put: sock_put(sk); discard: kfree_skb(skb); return 0; } static int l2tp_ip6_open(struct sock *sk) { /* Prevent autobind. We don't have ports. */ inet_sk(sk)->inet_num = IPPROTO_L2TP; write_lock_bh(&l2tp_ip6_lock); sk_add_node(sk, &l2tp_ip6_table); write_unlock_bh(&l2tp_ip6_lock); return 0; } static void l2tp_ip6_close(struct sock *sk, long timeout) { write_lock_bh(&l2tp_ip6_lock); hlist_del_init(&sk->sk_bind_node); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip6_lock); sk_common_release(sk); } static void l2tp_ip6_destroy_sock(struct sock *sk) { lock_sock(sk); ip6_flush_pending_frames(sk); release_sock(sk); inet6_destroy_sock(sk); } static int l2tp_ip6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *addr = (struct sockaddr_l2tpip6 *) uaddr; __be32 v4addr = 0; int addr_type; int err; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr->l2tp_family != AF_INET6) return -EINVAL; if (addr_len < sizeof(*addr)) return -EINVAL; addr_type = ipv6_addr_type(&addr->l2tp_addr); /* l2tp_ip6 sockets are IPv6 only */ if (addr_type == IPV6_ADDR_MAPPED) return -EADDRNOTAVAIL; /* L2TP is point-point, not multicast */ if (addr_type & IPV6_ADDR_MULTICAST) return -EADDRNOTAVAIL; err = -EADDRINUSE; read_lock_bh(&l2tp_ip6_lock); if (__l2tp_ip6_bind_lookup(&init_net, &addr->l2tp_addr, sk->sk_bound_dev_if, addr->l2tp_conn_id)) goto out_in_use; read_unlock_bh(&l2tp_ip6_lock); lock_sock(sk); err = -EINVAL; if (sk->sk_state != TCP_CLOSE) goto out_unlock; /* Check if the address belongs to the host. */ rcu_read_lock(); if (addr_type != IPV6_ADDR_ANY) { struct net_device *dev = NULL; if (addr_type & IPV6_ADDR_LINKLOCAL) { if (addr_len >= sizeof(struct sockaddr_in6) && addr->l2tp_scope_id) { /* Override any existing binding, if another * one is supplied by user. */ sk->sk_bound_dev_if = addr->l2tp_scope_id; } /* Binding to link-local address requires an interface */ if (!sk->sk_bound_dev_if) goto out_unlock_rcu; err = -ENODEV; dev = dev_get_by_index_rcu(sock_net(sk), sk->sk_bound_dev_if); if (!dev) goto out_unlock_rcu; } /* ipv4 addr of the socket is invalid. Only the * unspecified and mapped address have a v4 equivalent. */ v4addr = LOOPBACK4_IPV6; err = -EADDRNOTAVAIL; if (!ipv6_chk_addr(sock_net(sk), &addr->l2tp_addr, dev, 0)) goto out_unlock_rcu; } rcu_read_unlock(); inet->inet_rcv_saddr = inet->inet_saddr = v4addr; np->rcv_saddr = addr->l2tp_addr; np->saddr = addr->l2tp_addr; l2tp_ip6_sk(sk)->conn_id = addr->l2tp_conn_id; write_lock_bh(&l2tp_ip6_lock); sk_add_bind_node(sk, &l2tp_ip6_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip6_lock); sock_reset_flag(sk, SOCK_ZAPPED); release_sock(sk); return 0; out_unlock_rcu: rcu_read_unlock(); out_unlock: release_sock(sk); return err; out_in_use: read_unlock_bh(&l2tp_ip6_lock); return err; } static int l2tp_ip6_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *) uaddr; struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr; struct in6_addr *daddr; int addr_type; int rc; if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */ return -EINVAL; if (addr_len < sizeof(*lsa)) return -EINVAL; addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type & IPV6_ADDR_MULTICAST) return -EINVAL; if (addr_type & IPV6_ADDR_MAPPED) { daddr = &usin->sin6_addr; if (ipv4_is_multicast(daddr->s6_addr32[3])) return -EINVAL; } rc = ip6_datagram_connect(sk, uaddr, addr_len); lock_sock(sk); l2tp_ip6_sk(sk)->peer_conn_id = lsa->l2tp_conn_id; write_lock_bh(&l2tp_ip6_lock); hlist_del_init(&sk->sk_bind_node); sk_add_bind_node(sk, &l2tp_ip6_bind_table); write_unlock_bh(&l2tp_ip6_lock); release_sock(sk); return rc; } static int l2tp_ip6_disconnect(struct sock *sk, int flags) { if (sock_flag(sk, SOCK_ZAPPED)) return 0; return udp_disconnect(sk, flags); } static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr; struct sock *sk = sock->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk); lsa->l2tp_family = AF_INET6; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (peer) { if (!lsk->peer_conn_id) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr = np->daddr; if (np->sndflow) lsa->l2tp_flowinfo = np->flow_label; } else { if (ipv6_addr_any(&np->rcv_saddr)) lsa->l2tp_addr = np->saddr; else lsa->l2tp_addr = np->rcv_saddr; lsa->l2tp_conn_id = lsk->conn_id; } if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = sk->sk_bound_dev_if; *uaddr_len = sizeof(*lsa); return 0; } static int l2tp_ip6_backlog_recv(struct sock *sk, struct sk_buff *skb) { int rc; /* Charge it to the socket, dropping if the queue is full. */ rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) goto drop; return 0; drop: IP_INC_STATS(&init_net, IPSTATS_MIB_INDISCARDS); kfree_skb(skb); return -1; } static int l2tp_ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; __be32 *transhdr = NULL; int err = 0; skb = skb_peek(&sk->sk_write_queue); if (skb == NULL) goto out; transhdr = (__be32 *)skb_transport_header(skb); *transhdr = 0; err = ip6_push_pending_frames(sk); out: return err; } /* Userspace will call sendmsg() on the tunnel socket to send L2TP * control frames. */ static int l2tp_ip6_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *) msg->msg_name; struct in6_addr *daddr, *final_p, final; struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt = NULL; struct ip6_flowlabel *flowlabel = NULL; struct dst_entry *dst = NULL; struct flowi6 fl6; int addr_len = msg->msg_namelen; int hlimit = -1; int tclass = -1; int dontfrag = -1; int transhdrlen = 4; /* zero session-id */ int ulen = len + transhdrlen; int err; /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX) return -EMSGSIZE; /* Mirror BSD error message compatibility */ if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* * Get and verify the address. */ memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_mark = sk->sk_mark; if (lsa) { if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6) return -EAFNOSUPPORT; daddr = &lsa->l2tp_addr; if (np->sndflow) { fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; daddr = &flowlabel->dst; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &np->daddr)) daddr = &np->daddr; if (addr_len >= sizeof(struct sockaddr_in6) && lsa->l2tp_scope_id && ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL) fl6.flowi6_oif = lsa->l2tp_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = &np->daddr; fl6.flowlabel = np->flow_label; } if (fl6.flowi6_oif == 0) fl6.flowi6_oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(struct ipv6_txoptions); err = datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; } if (opt == NULL) opt = np->opt; if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = sk->sk_protocol; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; final_p = fl6_update_dst(&fl6, opt, &final); if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) fl6.flowi6_oif = np->mcast_oif; else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p, true); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } if (hlimit < 0) { if (ipv6_addr_is_multicast(&fl6.daddr)) hlimit = np->mcast_hops; else hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); } if (tclass < 0) tclass = np->tclass; if (dontfrag < 0) dontfrag = np->dontfrag; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: lock_sock(sk); err = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen, transhdrlen, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, msg->msg_flags, dontfrag); if (err) ip6_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) err = l2tp_ip6_push_pending_frames(sk); release_sock(sk); done: dst_release(dst); out: fl6_sock_release(flowlabel); return err < 0 ? err : len; do_confirm: dst_confirm(dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct inet_sock *inet = inet_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (inet->cmsg_flags) ip_cmsg_recv(msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } static struct proto l2tp_ip6_prot = { .name = "L2TP/IPv6", .owner = THIS_MODULE, .init = l2tp_ip6_open, .close = l2tp_ip6_close, .bind = l2tp_ip6_bind, .connect = l2tp_ip6_connect, .disconnect = l2tp_ip6_disconnect, .ioctl = udp_ioctl, .destroy = l2tp_ip6_destroy_sock, .setsockopt = ipv6_setsockopt, .getsockopt = ipv6_getsockopt, .sendmsg = l2tp_ip6_sendmsg, .recvmsg = l2tp_ip6_recvmsg, .backlog_rcv = l2tp_ip6_backlog_recv, .hash = inet_hash, .unhash = inet_unhash, .obj_size = sizeof(struct l2tp_ip6_sock), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ipv6_setsockopt, .compat_getsockopt = compat_ipv6_getsockopt, #endif }; static const struct proto_ops l2tp_ip6_ops = { .family = PF_INET6, .owner = THIS_MODULE, .release = inet6_release, .bind = inet6_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = l2tp_ip6_getname, .poll = datagram_poll, .ioctl = inet6_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw l2tp_ip6_protosw = { .type = SOCK_DGRAM, .protocol = IPPROTO_L2TP, .prot = &l2tp_ip6_prot, .ops = &l2tp_ip6_ops, .no_check = 0, }; static struct inet6_protocol l2tp_ip6_protocol __read_mostly = { .handler = l2tp_ip6_recv, }; static int __init l2tp_ip6_init(void) { int err; pr_info("L2TP IP encapsulation support for IPv6 (L2TPv3)\n"); err = proto_register(&l2tp_ip6_prot, 1); if (err != 0) goto out; err = inet6_add_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP); if (err) goto out1; inet6_register_protosw(&l2tp_ip6_protosw); return 0; out1: proto_unregister(&l2tp_ip6_prot); out: return err; } static void __exit l2tp_ip6_exit(void) { inet6_unregister_protosw(&l2tp_ip6_protosw); inet6_del_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP); proto_unregister(&l2tp_ip6_prot); } module_init(l2tp_ip6_init); module_exit(l2tp_ip6_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Chris Elston <celston@katalix.com>"); MODULE_DESCRIPTION("L2TP IP encapsulation for IPv6"); MODULE_VERSION("1.0"); /* Use the value of SOCK_DGRAM (2) directory, because __stringify doesn't like * enums */ MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 2, IPPROTO_L2TP);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3831_0
crossvul-cpp_data_bad_5681_0
/* net/atm/common.c - ATM sockets (common part for PVC and SVC) */ /* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */ #define pr_fmt(fmt) KBUILD_MODNAME ":%s: " fmt, __func__ #include <linux/module.h> #include <linux/kmod.h> #include <linux/net.h> /* struct socket, struct proto_ops */ #include <linux/atm.h> /* ATM stuff */ #include <linux/atmdev.h> #include <linux/socket.h> /* SOL_SOCKET */ #include <linux/errno.h> /* error codes */ #include <linux/capability.h> #include <linux/mm.h> #include <linux/sched.h> #include <linux/time.h> /* struct timeval */ #include <linux/skbuff.h> #include <linux/bitops.h> #include <linux/init.h> #include <linux/slab.h> #include <net/sock.h> /* struct sock */ #include <linux/uaccess.h> #include <linux/poll.h> #include <linux/atomic.h> #include "resources.h" /* atm_find_dev */ #include "common.h" /* prototypes */ #include "protocols.h" /* atm_init_<transport> */ #include "addr.h" /* address registry */ #include "signaling.h" /* for WAITING and sigd_attach */ struct hlist_head vcc_hash[VCC_HTABLE_SIZE]; EXPORT_SYMBOL(vcc_hash); DEFINE_RWLOCK(vcc_sklist_lock); EXPORT_SYMBOL(vcc_sklist_lock); static ATOMIC_NOTIFIER_HEAD(atm_dev_notify_chain); static void __vcc_insert_socket(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); struct hlist_head *head = &vcc_hash[vcc->vci & (VCC_HTABLE_SIZE - 1)]; sk->sk_hash = vcc->vci & (VCC_HTABLE_SIZE - 1); sk_add_node(sk, head); } void vcc_insert_socket(struct sock *sk) { write_lock_irq(&vcc_sklist_lock); __vcc_insert_socket(sk); write_unlock_irq(&vcc_sklist_lock); } EXPORT_SYMBOL(vcc_insert_socket); static void vcc_remove_socket(struct sock *sk) { write_lock_irq(&vcc_sklist_lock); sk_del_node_init(sk); write_unlock_irq(&vcc_sklist_lock); } static struct sk_buff *alloc_tx(struct atm_vcc *vcc, unsigned int size) { struct sk_buff *skb; struct sock *sk = sk_atm(vcc); if (sk_wmem_alloc_get(sk) && !atm_may_send(vcc, size)) { pr_debug("Sorry: wmem_alloc = %d, size = %d, sndbuf = %d\n", sk_wmem_alloc_get(sk), size, sk->sk_sndbuf); return NULL; } while (!(skb = alloc_skb(size, GFP_KERNEL))) schedule(); pr_debug("%d += %d\n", sk_wmem_alloc_get(sk), skb->truesize); atomic_add(skb->truesize, &sk->sk_wmem_alloc); return skb; } static void vcc_sock_destruct(struct sock *sk) { if (atomic_read(&sk->sk_rmem_alloc)) printk(KERN_DEBUG "%s: rmem leakage (%d bytes) detected.\n", __func__, atomic_read(&sk->sk_rmem_alloc)); if (atomic_read(&sk->sk_wmem_alloc)) printk(KERN_DEBUG "%s: wmem leakage (%d bytes) detected.\n", __func__, atomic_read(&sk->sk_wmem_alloc)); } static void vcc_def_wakeup(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up(&wq->wait); rcu_read_unlock(); } static inline int vcc_writable(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); return (vcc->qos.txtp.max_sdu + atomic_read(&sk->sk_wmem_alloc)) <= sk->sk_sndbuf; } static void vcc_write_space(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); if (vcc_writable(sk)) { wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible(&wq->wait); sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); } rcu_read_unlock(); } static void vcc_release_cb(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); if (vcc->release_cb) vcc->release_cb(vcc); } static struct proto vcc_proto = { .name = "VCC", .owner = THIS_MODULE, .obj_size = sizeof(struct atm_vcc), .release_cb = vcc_release_cb, }; int vcc_create(struct net *net, struct socket *sock, int protocol, int family) { struct sock *sk; struct atm_vcc *vcc; sock->sk = NULL; if (sock->type == SOCK_STREAM) return -EINVAL; sk = sk_alloc(net, family, GFP_KERNEL, &vcc_proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sk->sk_state_change = vcc_def_wakeup; sk->sk_write_space = vcc_write_space; vcc = atm_sk(sk); vcc->dev = NULL; memset(&vcc->local, 0, sizeof(struct sockaddr_atmsvc)); memset(&vcc->remote, 0, sizeof(struct sockaddr_atmsvc)); vcc->qos.txtp.max_sdu = 1 << 16; /* for meta VCs */ atomic_set(&sk->sk_wmem_alloc, 1); atomic_set(&sk->sk_rmem_alloc, 0); vcc->push = NULL; vcc->pop = NULL; vcc->owner = NULL; vcc->push_oam = NULL; vcc->release_cb = NULL; vcc->vpi = vcc->vci = 0; /* no VCI/VPI yet */ vcc->atm_options = vcc->aal_options = 0; sk->sk_destruct = vcc_sock_destruct; return 0; } static void vcc_destroy_socket(struct sock *sk) { struct atm_vcc *vcc = atm_sk(sk); struct sk_buff *skb; set_bit(ATM_VF_CLOSE, &vcc->flags); clear_bit(ATM_VF_READY, &vcc->flags); if (vcc->dev) { if (vcc->dev->ops->close) vcc->dev->ops->close(vcc); if (vcc->push) vcc->push(vcc, NULL); /* atmarpd has no push */ module_put(vcc->owner); while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { atm_return(vcc, skb->truesize); kfree_skb(skb); } module_put(vcc->dev->ops->owner); atm_dev_put(vcc->dev); } vcc_remove_socket(sk); } int vcc_release(struct socket *sock) { struct sock *sk = sock->sk; if (sk) { lock_sock(sk); vcc_destroy_socket(sock->sk); release_sock(sk); sock_put(sk); } return 0; } void vcc_release_async(struct atm_vcc *vcc, int reply) { struct sock *sk = sk_atm(vcc); set_bit(ATM_VF_CLOSE, &vcc->flags); sk->sk_shutdown |= RCV_SHUTDOWN; sk->sk_err = -reply; clear_bit(ATM_VF_WAITING, &vcc->flags); sk->sk_state_change(sk); } EXPORT_SYMBOL(vcc_release_async); void vcc_process_recv_queue(struct atm_vcc *vcc) { struct sk_buff_head queue, *rq; struct sk_buff *skb, *tmp; unsigned long flags; __skb_queue_head_init(&queue); rq = &sk_atm(vcc)->sk_receive_queue; spin_lock_irqsave(&rq->lock, flags); skb_queue_splice_init(rq, &queue); spin_unlock_irqrestore(&rq->lock, flags); skb_queue_walk_safe(&queue, skb, tmp) { __skb_unlink(skb, &queue); vcc->push(vcc, skb); } } EXPORT_SYMBOL(vcc_process_recv_queue); void atm_dev_signal_change(struct atm_dev *dev, char signal) { pr_debug("%s signal=%d dev=%p number=%d dev->signal=%d\n", __func__, signal, dev, dev->number, dev->signal); /* atm driver sending invalid signal */ WARN_ON(signal < ATM_PHY_SIG_LOST || signal > ATM_PHY_SIG_FOUND); if (dev->signal == signal) return; /* no change */ dev->signal = signal; atomic_notifier_call_chain(&atm_dev_notify_chain, signal, dev); } EXPORT_SYMBOL(atm_dev_signal_change); void atm_dev_release_vccs(struct atm_dev *dev) { int i; write_lock_irq(&vcc_sklist_lock); for (i = 0; i < VCC_HTABLE_SIZE; i++) { struct hlist_head *head = &vcc_hash[i]; struct hlist_node *tmp; struct sock *s; struct atm_vcc *vcc; sk_for_each_safe(s, tmp, head) { vcc = atm_sk(s); if (vcc->dev == dev) { vcc_release_async(vcc, -EPIPE); sk_del_node_init(s); } } } write_unlock_irq(&vcc_sklist_lock); } EXPORT_SYMBOL(atm_dev_release_vccs); static int adjust_tp(struct atm_trafprm *tp, unsigned char aal) { int max_sdu; if (!tp->traffic_class) return 0; switch (aal) { case ATM_AAL0: max_sdu = ATM_CELL_SIZE-1; break; case ATM_AAL34: max_sdu = ATM_MAX_AAL34_PDU; break; default: pr_warning("AAL problems ... (%d)\n", aal); /* fall through */ case ATM_AAL5: max_sdu = ATM_MAX_AAL5_PDU; } if (!tp->max_sdu) tp->max_sdu = max_sdu; else if (tp->max_sdu > max_sdu) return -EINVAL; if (!tp->max_cdv) tp->max_cdv = ATM_MAX_CDV; return 0; } static int check_ci(const struct atm_vcc *vcc, short vpi, int vci) { struct hlist_head *head = &vcc_hash[vci & (VCC_HTABLE_SIZE - 1)]; struct sock *s; struct atm_vcc *walk; sk_for_each(s, head) { walk = atm_sk(s); if (walk->dev != vcc->dev) continue; if (test_bit(ATM_VF_ADDR, &walk->flags) && walk->vpi == vpi && walk->vci == vci && ((walk->qos.txtp.traffic_class != ATM_NONE && vcc->qos.txtp.traffic_class != ATM_NONE) || (walk->qos.rxtp.traffic_class != ATM_NONE && vcc->qos.rxtp.traffic_class != ATM_NONE))) return -EADDRINUSE; } /* allow VCCs with same VPI/VCI iff they don't collide on TX/RX (but we may refuse such sharing for other reasons, e.g. if protocol requires to have both channels) */ return 0; } static int find_ci(const struct atm_vcc *vcc, short *vpi, int *vci) { static short p; /* poor man's per-device cache */ static int c; short old_p; int old_c; int err; if (*vpi != ATM_VPI_ANY && *vci != ATM_VCI_ANY) { err = check_ci(vcc, *vpi, *vci); return err; } /* last scan may have left values out of bounds for current device */ if (*vpi != ATM_VPI_ANY) p = *vpi; else if (p >= 1 << vcc->dev->ci_range.vpi_bits) p = 0; if (*vci != ATM_VCI_ANY) c = *vci; else if (c < ATM_NOT_RSV_VCI || c >= 1 << vcc->dev->ci_range.vci_bits) c = ATM_NOT_RSV_VCI; old_p = p; old_c = c; do { if (!check_ci(vcc, p, c)) { *vpi = p; *vci = c; return 0; } if (*vci == ATM_VCI_ANY) { c++; if (c >= 1 << vcc->dev->ci_range.vci_bits) c = ATM_NOT_RSV_VCI; } if ((c == ATM_NOT_RSV_VCI || *vci != ATM_VCI_ANY) && *vpi == ATM_VPI_ANY) { p++; if (p >= 1 << vcc->dev->ci_range.vpi_bits) p = 0; } } while (old_p != p || old_c != c); return -EADDRINUSE; } static int __vcc_connect(struct atm_vcc *vcc, struct atm_dev *dev, short vpi, int vci) { struct sock *sk = sk_atm(vcc); int error; if ((vpi != ATM_VPI_UNSPEC && vpi != ATM_VPI_ANY && vpi >> dev->ci_range.vpi_bits) || (vci != ATM_VCI_UNSPEC && vci != ATM_VCI_ANY && vci >> dev->ci_range.vci_bits)) return -EINVAL; if (vci > 0 && vci < ATM_NOT_RSV_VCI && !capable(CAP_NET_BIND_SERVICE)) return -EPERM; error = -ENODEV; if (!try_module_get(dev->ops->owner)) return error; vcc->dev = dev; write_lock_irq(&vcc_sklist_lock); if (test_bit(ATM_DF_REMOVED, &dev->flags) || (error = find_ci(vcc, &vpi, &vci))) { write_unlock_irq(&vcc_sklist_lock); goto fail_module_put; } vcc->vpi = vpi; vcc->vci = vci; __vcc_insert_socket(sk); write_unlock_irq(&vcc_sklist_lock); switch (vcc->qos.aal) { case ATM_AAL0: error = atm_init_aal0(vcc); vcc->stats = &dev->stats.aal0; break; case ATM_AAL34: error = atm_init_aal34(vcc); vcc->stats = &dev->stats.aal34; break; case ATM_NO_AAL: /* ATM_AAL5 is also used in the "0 for default" case */ vcc->qos.aal = ATM_AAL5; /* fall through */ case ATM_AAL5: error = atm_init_aal5(vcc); vcc->stats = &dev->stats.aal5; break; default: error = -EPROTOTYPE; } if (!error) error = adjust_tp(&vcc->qos.txtp, vcc->qos.aal); if (!error) error = adjust_tp(&vcc->qos.rxtp, vcc->qos.aal); if (error) goto fail; pr_debug("VCC %d.%d, AAL %d\n", vpi, vci, vcc->qos.aal); pr_debug(" TX: %d, PCR %d..%d, SDU %d\n", vcc->qos.txtp.traffic_class, vcc->qos.txtp.min_pcr, vcc->qos.txtp.max_pcr, vcc->qos.txtp.max_sdu); pr_debug(" RX: %d, PCR %d..%d, SDU %d\n", vcc->qos.rxtp.traffic_class, vcc->qos.rxtp.min_pcr, vcc->qos.rxtp.max_pcr, vcc->qos.rxtp.max_sdu); if (dev->ops->open) { error = dev->ops->open(vcc); if (error) goto fail; } return 0; fail: vcc_remove_socket(sk); fail_module_put: module_put(dev->ops->owner); /* ensure we get dev module ref count correct */ vcc->dev = NULL; return error; } int vcc_connect(struct socket *sock, int itf, short vpi, int vci) { struct atm_dev *dev; struct atm_vcc *vcc = ATM_SD(sock); int error; pr_debug("(vpi %d, vci %d)\n", vpi, vci); if (sock->state == SS_CONNECTED) return -EISCONN; if (sock->state != SS_UNCONNECTED) return -EINVAL; if (!(vpi || vci)) return -EINVAL; if (vpi != ATM_VPI_UNSPEC && vci != ATM_VCI_UNSPEC) clear_bit(ATM_VF_PARTIAL, &vcc->flags); else if (test_bit(ATM_VF_PARTIAL, &vcc->flags)) return -EINVAL; pr_debug("(TX: cl %d,bw %d-%d,sdu %d; " "RX: cl %d,bw %d-%d,sdu %d,AAL %s%d)\n", vcc->qos.txtp.traffic_class, vcc->qos.txtp.min_pcr, vcc->qos.txtp.max_pcr, vcc->qos.txtp.max_sdu, vcc->qos.rxtp.traffic_class, vcc->qos.rxtp.min_pcr, vcc->qos.rxtp.max_pcr, vcc->qos.rxtp.max_sdu, vcc->qos.aal == ATM_AAL5 ? "" : vcc->qos.aal == ATM_AAL0 ? "" : " ??? code ", vcc->qos.aal == ATM_AAL0 ? 0 : vcc->qos.aal); if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EBADFD; if (vcc->qos.txtp.traffic_class == ATM_ANYCLASS || vcc->qos.rxtp.traffic_class == ATM_ANYCLASS) return -EINVAL; if (likely(itf != ATM_ITF_ANY)) { dev = try_then_request_module(atm_dev_lookup(itf), "atm-device-%d", itf); } else { dev = NULL; mutex_lock(&atm_dev_mutex); if (!list_empty(&atm_devs)) { dev = list_entry(atm_devs.next, struct atm_dev, dev_list); atm_dev_hold(dev); } mutex_unlock(&atm_dev_mutex); } if (!dev) return -ENODEV; error = __vcc_connect(vcc, dev, vpi, vci); if (error) { atm_dev_put(dev); return error; } if (vpi == ATM_VPI_UNSPEC || vci == ATM_VCI_UNSPEC) set_bit(ATM_VF_PARTIAL, &vcc->flags); if (test_bit(ATM_VF_READY, &ATM_SD(sock)->flags)) sock->state = SS_CONNECTED; return 0; } int vcc_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct atm_vcc *vcc; struct sk_buff *skb; int copied, error = -EINVAL; if (sock->state != SS_CONNECTED) return -ENOTCONN; /* only handle MSG_DONTWAIT and MSG_PEEK */ if (flags & ~(MSG_DONTWAIT | MSG_PEEK)) return -EOPNOTSUPP; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) return 0; skb = skb_recv_datagram(sk, flags, flags & MSG_DONTWAIT, &error); if (!skb) return error; copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } error = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (error) return error; sock_recv_ts_and_drops(msg, sk, skb); if (!(flags & MSG_PEEK)) { pr_debug("%d -= %d\n", atomic_read(&sk->sk_rmem_alloc), skb->truesize); atm_return(vcc, skb->truesize); } skb_free_datagram(sk, skb); return copied; } int vcc_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len) { struct sock *sk = sock->sk; DEFINE_WAIT(wait); struct atm_vcc *vcc; struct sk_buff *skb; int eff, error; const void __user *buff; int size; lock_sock(sk); if (sock->state != SS_CONNECTED) { error = -ENOTCONN; goto out; } if (m->msg_name) { error = -EISCONN; goto out; } if (m->msg_iovlen != 1) { error = -ENOSYS; /* fix this later @@@ */ goto out; } buff = m->msg_iov->iov_base; size = m->msg_iov->iov_len; vcc = ATM_SD(sock); if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) { error = -EPIPE; send_sig(SIGPIPE, current, 0); goto out; } if (!size) { error = 0; goto out; } if (size < 0 || size > vcc->qos.txtp.max_sdu) { error = -EMSGSIZE; goto out; } eff = (size+3) & ~3; /* align to word boundary */ prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); error = 0; while (!(skb = alloc_tx(vcc, eff))) { if (m->msg_flags & MSG_DONTWAIT) { error = -EAGAIN; break; } schedule(); if (signal_pending(current)) { error = -ERESTARTSYS; break; } if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags) || !test_bit(ATM_VF_READY, &vcc->flags)) { error = -EPIPE; send_sig(SIGPIPE, current, 0); break; } prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); } finish_wait(sk_sleep(sk), &wait); if (error) goto out; skb->dev = NULL; /* for paths shared with net_device interfaces */ ATM_SKB(skb)->atm_options = vcc->atm_options; if (copy_from_user(skb_put(skb, size), buff, size)) { kfree_skb(skb); error = -EFAULT; goto out; } if (eff != size) memset(skb->data + size, 0, eff-size); error = vcc->dev->ops->send(vcc, skb); error = error ? error : size; out: release_sock(sk); return error; } unsigned int vcc_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; struct atm_vcc *vcc; unsigned int mask; sock_poll_wait(file, sk_sleep(sk), wait); mask = 0; vcc = ATM_SD(sock); /* exceptional events */ if (sk->sk_err) mask = POLLERR; if (test_bit(ATM_VF_RELEASED, &vcc->flags) || test_bit(ATM_VF_CLOSE, &vcc->flags)) mask |= POLLHUP; /* readable? */ if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; /* writable? */ if (sock->state == SS_CONNECTING && test_bit(ATM_VF_WAITING, &vcc->flags)) return mask; if (vcc->qos.txtp.traffic_class != ATM_NONE && vcc_writable(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; return mask; } static int atm_change_qos(struct atm_vcc *vcc, struct atm_qos *qos) { int error; /* * Don't let the QoS change the already connected AAL type nor the * traffic class. */ if (qos->aal != vcc->qos.aal || qos->rxtp.traffic_class != vcc->qos.rxtp.traffic_class || qos->txtp.traffic_class != vcc->qos.txtp.traffic_class) return -EINVAL; error = adjust_tp(&qos->txtp, qos->aal); if (!error) error = adjust_tp(&qos->rxtp, qos->aal); if (error) return error; if (!vcc->dev->ops->change_qos) return -EOPNOTSUPP; if (sk_atm(vcc)->sk_family == AF_ATMPVC) return vcc->dev->ops->change_qos(vcc, qos, ATM_MF_SET); return svc_change_qos(vcc, qos); } static int check_tp(const struct atm_trafprm *tp) { /* @@@ Should be merged with adjust_tp */ if (!tp->traffic_class || tp->traffic_class == ATM_ANYCLASS) return 0; if (tp->traffic_class != ATM_UBR && !tp->min_pcr && !tp->pcr && !tp->max_pcr) return -EINVAL; if (tp->min_pcr == ATM_MAX_PCR) return -EINVAL; if (tp->min_pcr && tp->max_pcr && tp->max_pcr != ATM_MAX_PCR && tp->min_pcr > tp->max_pcr) return -EINVAL; /* * We allow pcr to be outside [min_pcr,max_pcr], because later * adjustment may still push it in the valid range. */ return 0; } static int check_qos(const struct atm_qos *qos) { int error; if (!qos->txtp.traffic_class && !qos->rxtp.traffic_class) return -EINVAL; if (qos->txtp.traffic_class != qos->rxtp.traffic_class && qos->txtp.traffic_class && qos->rxtp.traffic_class && qos->txtp.traffic_class != ATM_ANYCLASS && qos->rxtp.traffic_class != ATM_ANYCLASS) return -EINVAL; error = check_tp(&qos->txtp); if (error) return error; return check_tp(&qos->rxtp); } int vcc_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct atm_vcc *vcc; unsigned long value; int error; if (__SO_LEVEL_MATCH(optname, level) && optlen != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: { struct atm_qos qos; if (copy_from_user(&qos, optval, sizeof(qos))) return -EFAULT; error = check_qos(&qos); if (error) return error; if (sock->state == SS_CONNECTED) return atm_change_qos(vcc, &qos); if (sock->state != SS_UNCONNECTED) return -EBADFD; vcc->qos = qos; set_bit(ATM_VF_HASQOS, &vcc->flags); return 0; } case SO_SETCLP: if (get_user(value, (unsigned long __user *)optval)) return -EFAULT; if (value) vcc->atm_options |= ATM_ATMOPT_CLP; else vcc->atm_options &= ~ATM_ATMOPT_CLP; return 0; default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->setsockopt) return -EINVAL; return vcc->dev->ops->setsockopt(vcc, level, optname, optval, optlen); } int vcc_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct atm_vcc *vcc; int len; if (get_user(len, optlen)) return -EFAULT; if (__SO_LEVEL_MATCH(optname, level) && len != __SO_SIZE(optname)) return -EINVAL; vcc = ATM_SD(sock); switch (optname) { case SO_ATMQOS: if (!test_bit(ATM_VF_HASQOS, &vcc->flags)) return -EINVAL; return copy_to_user(optval, &vcc->qos, sizeof(vcc->qos)) ? -EFAULT : 0; case SO_SETCLP: return put_user(vcc->atm_options & ATM_ATMOPT_CLP ? 1 : 0, (unsigned long __user *)optval) ? -EFAULT : 0; case SO_ATMPVC: { struct sockaddr_atmpvc pvc; if (!vcc->dev || !test_bit(ATM_VF_ADDR, &vcc->flags)) return -ENOTCONN; memset(&pvc, 0, sizeof(pvc)); pvc.sap_family = AF_ATMPVC; pvc.sap_addr.itf = vcc->dev->number; pvc.sap_addr.vpi = vcc->vpi; pvc.sap_addr.vci = vcc->vci; return copy_to_user(optval, &pvc, sizeof(pvc)) ? -EFAULT : 0; } default: if (level == SOL_SOCKET) return -EINVAL; break; } if (!vcc->dev || !vcc->dev->ops->getsockopt) return -EINVAL; return vcc->dev->ops->getsockopt(vcc, level, optname, optval, len); } int register_atmdevice_notifier(struct notifier_block *nb) { return atomic_notifier_chain_register(&atm_dev_notify_chain, nb); } EXPORT_SYMBOL_GPL(register_atmdevice_notifier); void unregister_atmdevice_notifier(struct notifier_block *nb) { atomic_notifier_chain_unregister(&atm_dev_notify_chain, nb); } EXPORT_SYMBOL_GPL(unregister_atmdevice_notifier); static int __init atm_init(void) { int error; error = proto_register(&vcc_proto, 0); if (error < 0) goto out; error = atmpvc_init(); if (error < 0) { pr_err("atmpvc_init() failed with %d\n", error); goto out_unregister_vcc_proto; } error = atmsvc_init(); if (error < 0) { pr_err("atmsvc_init() failed with %d\n", error); goto out_atmpvc_exit; } error = atm_proc_init(); if (error < 0) { pr_err("atm_proc_init() failed with %d\n", error); goto out_atmsvc_exit; } error = atm_sysfs_init(); if (error < 0) { pr_err("atm_sysfs_init() failed with %d\n", error); goto out_atmproc_exit; } out: return error; out_atmproc_exit: atm_proc_exit(); out_atmsvc_exit: atmsvc_exit(); out_atmpvc_exit: atmsvc_exit(); out_unregister_vcc_proto: proto_unregister(&vcc_proto); goto out; } static void __exit atm_exit(void) { atm_proc_exit(); atm_sysfs_exit(); atmsvc_exit(); atmpvc_exit(); proto_unregister(&vcc_proto); } subsys_initcall(atm_init); module_exit(atm_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_ATMPVC); MODULE_ALIAS_NETPROTO(PF_ATMSVC);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5681_0
crossvul-cpp_data_bad_5614_0
/*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2013, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at http://curl.haxx.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ***************************************************************************/ /*** RECEIVING COOKIE INFORMATION ============================ struct CookieInfo *cookie_init(char *file); Inits a cookie struct to store data in a local file. This is always called before any cookies are set. int cookies_set(struct CookieInfo *cookie, char *cookie_line); The 'cookie_line' parameter is a full "Set-cookie:" line as received from a server. The function need to replace previously stored lines that this new line superceeds. It may remove lines that are expired. It should return an indication of success/error. SENDING COOKIE INFORMATION ========================== struct Cookies *cookie_getlist(struct CookieInfo *cookie, char *host, char *path, bool secure); For a given host and path, return a linked list of cookies that the client should send to the server if used now. The secure boolean informs the cookie if a secure connection is achieved or not. It shall only return cookies that haven't expired. Example set of cookies: Set-cookie: PRODUCTINFO=webxpress; domain=.fidelity.com; path=/; secure Set-cookie: PERSONALIZE=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/ftgw; secure Set-cookie: FidHist=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure Set-cookie: FidOrder=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure Set-cookie: DisPend=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure Set-cookie: FidDis=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure Set-cookie: Session_Key@6791a9e0-901a-11d0-a1c8-9b012c88aa77=none;expires=Monday, 13-Jun-1988 03:04:55 GMT; domain=.fidelity.com; path=/; secure ****/ #include "curl_setup.h" #if !defined(CURL_DISABLE_HTTP) && !defined(CURL_DISABLE_COOKIES) #define _MPRINTF_REPLACE #include <curl/mprintf.h> #include "urldata.h" #include "cookie.h" #include "strequal.h" #include "strtok.h" #include "sendf.h" #include "curl_memory.h" #include "share.h" #include "strtoofft.h" #include "rawstr.h" #include "curl_memrchr.h" /* The last #include file should be: */ #include "memdebug.h" static void freecookie(struct Cookie *co) { if(co->expirestr) free(co->expirestr); if(co->domain) free(co->domain); if(co->path) free(co->path); if(co->name) free(co->name); if(co->value) free(co->value); if(co->maxage) free(co->maxage); if(co->version) free(co->version); free(co); } static bool tailmatch(const char *little, const char *bigone) { size_t littlelen = strlen(little); size_t biglen = strlen(bigone); if(littlelen > biglen) return FALSE; return Curl_raw_equal(little, bigone+biglen-littlelen) ? TRUE : FALSE; } /* * Load cookies from all given cookie files (CURLOPT_COOKIEFILE). */ void Curl_cookie_loadfiles(struct SessionHandle *data) { struct curl_slist *list = data->change.cookielist; if(list) { Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); while(list) { data->cookies = Curl_cookie_init(data, list->data, data->cookies, data->set.cookiesession); list = list->next; } curl_slist_free_all(data->change.cookielist); /* clean up list */ data->change.cookielist = NULL; /* don't do this again! */ Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } } /* * strstore() makes a strdup() on the 'newstr' and if '*str' is non-NULL * that will be freed before the allocated string is stored there. * * It is meant to easily replace strdup() */ static void strstore(char **str, const char *newstr) { if(*str) free(*str); *str = strdup(newstr); } /**************************************************************************** * * Curl_cookie_add() * * Add a single cookie line to the cookie keeping object. * ***************************************************************************/ struct Cookie * Curl_cookie_add(struct SessionHandle *data, /* The 'data' pointer here may be NULL at times, and thus must only be used very carefully for things that can deal with data being NULL. Such as infof() and similar */ struct CookieInfo *c, bool httpheader, /* TRUE if HTTP header-style line */ char *lineptr, /* first character of the line */ const char *domain, /* default domain */ const char *path) /* full path used when this cookie is set, used to get default path for the cookie unless set */ { struct Cookie *clist; char name[MAX_NAME]; struct Cookie *co; struct Cookie *lastc=NULL; time_t now = time(NULL); bool replace_old = FALSE; bool badcookie = FALSE; /* cookies are good by default. mmmmm yummy */ #ifdef CURL_DISABLE_VERBOSE_STRINGS (void)data; #endif /* First, alloc and init a new struct for it */ co = calloc(1, sizeof(struct Cookie)); if(!co) return NULL; /* bail out if we're this low on memory */ if(httpheader) { /* This line was read off a HTTP-header */ const char *ptr; const char *semiptr; char *what; what = malloc(MAX_COOKIE_LINE); if(!what) { free(co); return NULL; } semiptr=strchr(lineptr, ';'); /* first, find a semicolon */ while(*lineptr && ISBLANK(*lineptr)) lineptr++; ptr = lineptr; do { /* we have a <what>=<this> pair or a stand-alone word here */ name[0]=what[0]=0; /* init the buffers */ if(1 <= sscanf(ptr, "%" MAX_NAME_TXT "[^;\r\n =]=%" MAX_COOKIE_LINE_TXT "[^;\r\n]", name, what)) { /* Use strstore() below to properly deal with received cookie headers that have the same string property set more than once, and then we use the last one. */ const char *whatptr; bool done = FALSE; bool sep; size_t len=strlen(what); const char *endofn = &ptr[ strlen(name) ]; /* skip trailing spaces in name */ while(*endofn && ISBLANK(*endofn)) endofn++; /* name ends with a '=' ? */ sep = (*endofn == '=')?TRUE:FALSE; /* Strip off trailing whitespace from the 'what' */ while(len && ISBLANK(what[len-1])) { what[len-1]=0; len--; } /* Skip leading whitespace from the 'what' */ whatptr=what; while(*whatptr && ISBLANK(*whatptr)) whatptr++; if(!len) { /* this was a "<name>=" with no content, and we must allow 'secure' and 'httponly' specified this weirdly */ done = TRUE; if(Curl_raw_equal("secure", name)) co->secure = TRUE; else if(Curl_raw_equal("httponly", name)) co->httponly = TRUE; else if(sep) /* there was a '=' so we're not done parsing this field */ done = FALSE; } if(done) ; else if(Curl_raw_equal("path", name)) { strstore(&co->path, whatptr); if(!co->path) { badcookie = TRUE; /* out of memory bad */ break; } } else if(Curl_raw_equal("domain", name)) { /* note that this name may or may not have a preceding dot, but we don't care about that, we treat the names the same anyway */ const char *domptr=whatptr; const char *nextptr; int dotcount=1; /* Count the dots, we need to make sure that there are enough of them. */ if('.' == whatptr[0]) /* don't count the initial dot, assume it */ domptr++; do { nextptr = strchr(domptr, '.'); if(nextptr) { if(domptr != nextptr) dotcount++; domptr = nextptr+1; } } while(nextptr); /* The original Netscape cookie spec defined that this domain name MUST have three dots (or two if one of the seven holy TLDs), but it seems that these kinds of cookies are in use "out there" so we cannot be that strict. I've therefore lowered the check to not allow less than two dots. */ if(dotcount < 2) { /* Received and skipped a cookie with a domain using too few dots. */ badcookie=TRUE; /* mark this as a bad cookie */ infof(data, "skipped cookie with illegal dotcount domain: %s\n", whatptr); } else { /* Now, we make sure that our host is within the given domain, or the given domain is not valid and thus cannot be set. */ if('.' == whatptr[0]) whatptr++; /* ignore preceding dot */ if(!domain || tailmatch(whatptr, domain)) { const char *tailptr=whatptr; if(tailptr[0] == '.') tailptr++; strstore(&co->domain, tailptr); /* don't prefix w/dots internally */ if(!co->domain) { badcookie = TRUE; break; } co->tailmatch=TRUE; /* we always do that if the domain name was given */ } else { /* we did not get a tailmatch and then the attempted set domain is not a domain to which the current host belongs. Mark as bad. */ badcookie=TRUE; infof(data, "skipped cookie with bad tailmatch domain: %s\n", whatptr); } } } else if(Curl_raw_equal("version", name)) { strstore(&co->version, whatptr); if(!co->version) { badcookie = TRUE; break; } } else if(Curl_raw_equal("max-age", name)) { /* Defined in RFC2109: Optional. The Max-Age attribute defines the lifetime of the cookie, in seconds. The delta-seconds value is a decimal non- negative integer. After delta-seconds seconds elapse, the client should discard the cookie. A value of zero means the cookie should be discarded immediately. */ strstore(&co->maxage, whatptr); if(!co->maxage) { badcookie = TRUE; break; } co->expires = strtol((*co->maxage=='\"')?&co->maxage[1]:&co->maxage[0],NULL,10) + (long)now; } else if(Curl_raw_equal("expires", name)) { strstore(&co->expirestr, whatptr); if(!co->expirestr) { badcookie = TRUE; break; } /* Note that if the date couldn't get parsed for whatever reason, the cookie will be treated as a session cookie */ co->expires = curl_getdate(what, &now); /* Session cookies have expires set to 0 so if we get that back from the date parser let's add a second to make it a non-session cookie */ if(co->expires == 0) co->expires = 1; else if(co->expires < 0) co->expires = 0; } else if(!co->name) { co->name = strdup(name); co->value = strdup(whatptr); if(!co->name || !co->value) { badcookie = TRUE; break; } } /* else this is the second (or more) name we don't know about! */ } else { /* this is an "illegal" <what>=<this> pair */ } if(!semiptr || !*semiptr) { /* we already know there are no more cookies */ semiptr = NULL; continue; } ptr=semiptr+1; while(*ptr && ISBLANK(*ptr)) ptr++; semiptr=strchr(ptr, ';'); /* now, find the next semicolon */ if(!semiptr && *ptr) /* There are no more semicolons, but there's a final name=value pair coming up */ semiptr=strchr(ptr, '\0'); } while(semiptr); if(!badcookie && !co->domain) { if(domain) { /* no domain was given in the header line, set the default */ co->domain=strdup(domain); if(!co->domain) badcookie = TRUE; } } if(!badcookie && !co->path && path) { /* No path was given in the header line, set the default. Note that the passed-in path to this function MAY have a '?' and following part that MUST not be stored as part of the path. */ char *queryp = strchr(path, '?'); /* queryp is where the interesting part of the path ends, so now we want to the find the last */ char *endslash; if(!queryp) endslash = strrchr(path, '/'); else endslash = memrchr(path, '/', (size_t)(queryp - path)); if(endslash) { size_t pathlen = (size_t)(endslash-path+1); /* include ending slash */ co->path=malloc(pathlen+1); /* one extra for the zero byte */ if(co->path) { memcpy(co->path, path, pathlen); co->path[pathlen]=0; /* zero terminate */ } else badcookie = TRUE; } } free(what); if(badcookie || !co->name) { /* we didn't get a cookie name or a bad one, this is an illegal line, bail out */ freecookie(co); return NULL; } } else { /* This line is NOT a HTTP header style line, we do offer support for reading the odd netscape cookies-file format here */ char *ptr; char *firstptr; char *tok_buf=NULL; int fields; /* IE introduced HTTP-only cookies to prevent XSS attacks. Cookies marked with httpOnly after the domain name are not accessible from javascripts, but since curl does not operate at javascript level, we include them anyway. In Firefox's cookie files, these lines are preceded with #HttpOnly_ and then everything is as usual, so we skip 10 characters of the line.. */ if(strncmp(lineptr, "#HttpOnly_", 10) == 0) { lineptr += 10; co->httponly = TRUE; } if(lineptr[0]=='#') { /* don't even try the comments */ free(co); return NULL; } /* strip off the possible end-of-line characters */ ptr=strchr(lineptr, '\r'); if(ptr) *ptr=0; /* clear it */ ptr=strchr(lineptr, '\n'); if(ptr) *ptr=0; /* clear it */ firstptr=strtok_r(lineptr, "\t", &tok_buf); /* tokenize it on the TAB */ /* Here's a quick check to eliminate normal HTTP-headers from this */ if(!firstptr || strchr(firstptr, ':')) { free(co); return NULL; } /* Now loop through the fields and init the struct we already have allocated */ for(ptr=firstptr, fields=0; ptr && !badcookie; ptr=strtok_r(NULL, "\t", &tok_buf), fields++) { switch(fields) { case 0: if(ptr[0]=='.') /* skip preceding dots */ ptr++; co->domain = strdup(ptr); if(!co->domain) badcookie = TRUE; break; case 1: /* This field got its explanation on the 23rd of May 2001 by Andr�s Garc�a: flag: A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for the domain. As far as I can see, it is set to true when the cookie says .domain.com and to false when the domain is complete www.domain.com */ co->tailmatch = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE; break; case 2: /* It turns out, that sometimes the file format allows the path field to remain not filled in, we try to detect this and work around it! Andr�s Garc�a made us aware of this... */ if(strcmp("TRUE", ptr) && strcmp("FALSE", ptr)) { /* only if the path doesn't look like a boolean option! */ co->path = strdup(ptr); if(!co->path) badcookie = TRUE; break; } /* this doesn't look like a path, make one up! */ co->path = strdup("/"); if(!co->path) badcookie = TRUE; fields++; /* add a field and fall down to secure */ /* FALLTHROUGH */ case 3: co->secure = Curl_raw_equal(ptr, "TRUE")?TRUE:FALSE; break; case 4: co->expires = curlx_strtoofft(ptr, NULL, 10); break; case 5: co->name = strdup(ptr); if(!co->name) badcookie = TRUE; break; case 6: co->value = strdup(ptr); if(!co->value) badcookie = TRUE; break; } } if(6 == fields) { /* we got a cookie with blank contents, fix it */ co->value = strdup(""); if(!co->value) badcookie = TRUE; else fields++; } if(!badcookie && (7 != fields)) /* we did not find the sufficient number of fields */ badcookie = TRUE; if(badcookie) { freecookie(co); return NULL; } } if(!c->running && /* read from a file */ c->newsession && /* clean session cookies */ !co->expires) { /* this is a session cookie since it doesn't expire! */ freecookie(co); return NULL; } co->livecookie = c->running; /* now, we have parsed the incoming line, we must now check if this superceeds an already existing cookie, which it may if the previous have the same domain and path as this */ clist = c->cookies; replace_old = FALSE; while(clist) { if(Curl_raw_equal(clist->name, co->name)) { /* the names are identical */ if(clist->domain && co->domain) { if(Curl_raw_equal(clist->domain, co->domain)) /* The domains are identical */ replace_old=TRUE; } else if(!clist->domain && !co->domain) replace_old = TRUE; if(replace_old) { /* the domains were identical */ if(clist->path && co->path) { if(Curl_raw_equal(clist->path, co->path)) { replace_old = TRUE; } else replace_old = FALSE; } else if(!clist->path && !co->path) replace_old = TRUE; else replace_old = FALSE; } if(replace_old && !co->livecookie && clist->livecookie) { /* Both cookies matched fine, except that the already present cookie is "live", which means it was set from a header, while the new one isn't "live" and thus only read from a file. We let live cookies stay alive */ /* Free the newcomer and get out of here! */ freecookie(co); return NULL; } if(replace_old) { co->next = clist->next; /* get the next-pointer first */ /* then free all the old pointers */ free(clist->name); if(clist->value) free(clist->value); if(clist->domain) free(clist->domain); if(clist->path) free(clist->path); if(clist->expirestr) free(clist->expirestr); if(clist->version) free(clist->version); if(clist->maxage) free(clist->maxage); *clist = *co; /* then store all the new data */ free(co); /* free the newly alloced memory */ co = clist; /* point to the previous struct instead */ /* We have replaced a cookie, now skip the rest of the list but make sure the 'lastc' pointer is properly set */ do { lastc = clist; clist = clist->next; } while(clist); break; } } lastc = clist; clist = clist->next; } if(c->running) /* Only show this when NOT reading the cookies from a file */ infof(data, "%s cookie %s=\"%s\" for domain %s, path %s, " "expire %" FORMAT_OFF_T "\n", replace_old?"Replaced":"Added", co->name, co->value, co->domain, co->path, co->expires); if(!replace_old) { /* then make the last item point on this new one */ if(lastc) lastc->next = co; else c->cookies = co; c->numcookies++; /* one more cookie in the jar */ } return co; } /***************************************************************************** * * Curl_cookie_init() * * Inits a cookie struct to read data from a local file. This is always * called before any cookies are set. File may be NULL. * * If 'newsession' is TRUE, discard all "session cookies" on read from file. * ****************************************************************************/ struct CookieInfo *Curl_cookie_init(struct SessionHandle *data, const char *file, struct CookieInfo *inc, bool newsession) { struct CookieInfo *c; FILE *fp; bool fromfile=TRUE; if(NULL == inc) { /* we didn't get a struct, create one */ c = calloc(1, sizeof(struct CookieInfo)); if(!c) return NULL; /* failed to get memory */ c->filename = strdup(file?file:"none"); /* copy the name just in case */ } else { /* we got an already existing one, use that */ c = inc; } c->running = FALSE; /* this is not running, this is init */ if(file && strequal(file, "-")) { fp = stdin; fromfile=FALSE; } else if(file && !*file) { /* points to a "" string */ fp = NULL; } else fp = file?fopen(file, "r"):NULL; c->newsession = newsession; /* new session? */ if(fp) { char *lineptr; bool headerline; char *line = malloc(MAX_COOKIE_LINE); if(line) { while(fgets(line, MAX_COOKIE_LINE, fp)) { if(checkprefix("Set-Cookie:", line)) { /* This is a cookie line, get it! */ lineptr=&line[11]; headerline=TRUE; } else { lineptr=line; headerline=FALSE; } while(*lineptr && ISBLANK(*lineptr)) lineptr++; Curl_cookie_add(data, c, headerline, lineptr, NULL, NULL); } free(line); /* free the line buffer */ } if(fromfile) fclose(fp); } c->running = TRUE; /* now, we're running */ return c; } /* sort this so that the longest path gets before the shorter path */ static int cookie_sort(const void *p1, const void *p2) { struct Cookie *c1 = *(struct Cookie **)p1; struct Cookie *c2 = *(struct Cookie **)p2; size_t l1, l2; /* 1 - compare cookie path lengths */ l1 = c1->path ? strlen(c1->path) : 0; l2 = c2->path ? strlen(c2->path) : 0; if(l1 != l2) return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */ /* 2 - compare cookie domain lengths */ l1 = c1->domain ? strlen(c1->domain) : 0; l2 = c2->domain ? strlen(c2->domain) : 0; if(l1 != l2) return (l2 > l1) ? 1 : -1 ; /* avoid size_t <=> int conversions */ /* 3 - compare cookie names */ if(c1->name && c2->name) return strcmp(c1->name, c2->name); /* sorry, can't be more deterministic */ return 0; } /***************************************************************************** * * Curl_cookie_getlist() * * For a given host and path, return a linked list of cookies that the * client should send to the server if used now. The secure boolean informs * the cookie if a secure connection is achieved or not. * * It shall only return cookies that haven't expired. * ****************************************************************************/ struct Cookie *Curl_cookie_getlist(struct CookieInfo *c, const char *host, const char *path, bool secure) { struct Cookie *newco; struct Cookie *co; time_t now = time(NULL); struct Cookie *mainco=NULL; size_t matches = 0; if(!c || !c->cookies) return NULL; /* no cookie struct or no cookies in the struct */ co = c->cookies; while(co) { /* only process this cookie if it is not expired or had no expire date AND that if the cookie requires we're secure we must only continue if we are! */ if((!co->expires || (co->expires > now)) && (co->secure?secure:TRUE)) { /* now check if the domain is correct */ if(!co->domain || (co->tailmatch && tailmatch(co->domain, host)) || (!co->tailmatch && Curl_raw_equal(host, co->domain)) ) { /* the right part of the host matches the domain stuff in the cookie data */ /* now check the left part of the path with the cookies path requirement */ if(!co->path || /* not using checkprefix() because matching should be case-sensitive */ !strncmp(co->path, path, strlen(co->path)) ) { /* and now, we know this is a match and we should create an entry for the return-linked-list */ newco = malloc(sizeof(struct Cookie)); if(newco) { /* first, copy the whole source cookie: */ memcpy(newco, co, sizeof(struct Cookie)); /* then modify our next */ newco->next = mainco; /* point the main to us */ mainco = newco; matches++; } else { fail: /* failure, clear up the allocated chain and return NULL */ while(mainco) { co = mainco->next; free(mainco); mainco = co; } return NULL; } } } } co = co->next; } if(matches) { /* Now we need to make sure that if there is a name appearing more than once, the longest specified path version comes first. To make this the swiftest way, we just sort them all based on path length. */ struct Cookie **array; size_t i; /* alloc an array and store all cookie pointers */ array = malloc(sizeof(struct Cookie *) * matches); if(!array) goto fail; co = mainco; for(i=0; co; co = co->next) array[i++] = co; /* now sort the cookie pointers in path length order */ qsort(array, matches, sizeof(struct Cookie *), cookie_sort); /* remake the linked list order according to the new order */ mainco = array[0]; /* start here */ for(i=0; i<matches-1; i++) array[i]->next = array[i+1]; array[matches-1]->next = NULL; /* terminate the list */ free(array); /* remove the temporary data again */ } return mainco; /* return the new list */ } /***************************************************************************** * * Curl_cookie_clearall() * * Clear all existing cookies and reset the counter. * ****************************************************************************/ void Curl_cookie_clearall(struct CookieInfo *cookies) { if(cookies) { Curl_cookie_freelist(cookies->cookies, TRUE); cookies->cookies = NULL; cookies->numcookies = 0; } } /***************************************************************************** * * Curl_cookie_freelist() * * Free a list of cookies previously returned by Curl_cookie_getlist(); * * The 'cookiestoo' argument tells this function whether to just free the * list or actually also free all cookies within the list as well. * ****************************************************************************/ void Curl_cookie_freelist(struct Cookie *co, bool cookiestoo) { struct Cookie *next; if(co) { while(co) { next = co->next; if(cookiestoo) freecookie(co); else free(co); /* we only free the struct since the "members" are all just pointed out in the main cookie list! */ co = next; } } } /***************************************************************************** * * Curl_cookie_clearsess() * * Free all session cookies in the cookies list. * ****************************************************************************/ void Curl_cookie_clearsess(struct CookieInfo *cookies) { struct Cookie *first, *curr, *next, *prev = NULL; if(!cookies || !cookies->cookies) return; first = curr = prev = cookies->cookies; for(; curr; curr = next) { next = curr->next; if(!curr->expires) { if(first == curr) first = next; if(prev == curr) prev = next; else prev->next = next; freecookie(curr); cookies->numcookies--; } else prev = curr; } cookies->cookies = first; } /***************************************************************************** * * Curl_cookie_cleanup() * * Free a "cookie object" previous created with cookie_init(). * ****************************************************************************/ void Curl_cookie_cleanup(struct CookieInfo *c) { struct Cookie *co; struct Cookie *next; if(c) { if(c->filename) free(c->filename); co = c->cookies; while(co) { next = co->next; freecookie(co); co = next; } free(c); /* free the base struct as well */ } } /* get_netscape_format() * * Formats a string for Netscape output file, w/o a newline at the end. * * Function returns a char * to a formatted line. Has to be free()d */ static char *get_netscape_format(const struct Cookie *co) { return aprintf( "%s" /* httponly preamble */ "%s%s\t" /* domain */ "%s\t" /* tailmatch */ "%s\t" /* path */ "%s\t" /* secure */ "%" FORMAT_OFF_T "\t" /* expires */ "%s\t" /* name */ "%s", /* value */ co->httponly?"#HttpOnly_":"", /* Make sure all domains are prefixed with a dot if they allow tailmatching. This is Mozilla-style. */ (co->tailmatch && co->domain && co->domain[0] != '.')? ".":"", co->domain?co->domain:"unknown", co->tailmatch?"TRUE":"FALSE", co->path?co->path:"/", co->secure?"TRUE":"FALSE", co->expires, co->name, co->value?co->value:""); } /* * cookie_output() * * Writes all internally known cookies to the specified file. Specify * "-" as file name to write to stdout. * * The function returns non-zero on write failure. */ static int cookie_output(struct CookieInfo *c, const char *dumphere) { struct Cookie *co; FILE *out; bool use_stdout=FALSE; if((NULL == c) || (0 == c->numcookies)) /* If there are no known cookies, we don't write or even create any destination file */ return 0; if(strequal("-", dumphere)) { /* use stdout */ out = stdout; use_stdout=TRUE; } else { out = fopen(dumphere, "w"); if(!out) return 1; /* failure */ } if(c) { char *format_ptr; fputs("# Netscape HTTP Cookie File\n" "# http://curl.haxx.se/docs/http-cookies.html\n" "# This file was generated by libcurl! Edit at your own risk.\n\n", out); co = c->cookies; while(co) { format_ptr = get_netscape_format(co); if(format_ptr == NULL) { fprintf(out, "#\n# Fatal libcurl error\n"); if(!use_stdout) fclose(out); return 1; } fprintf(out, "%s\n", format_ptr); free(format_ptr); co=co->next; } } if(!use_stdout) fclose(out); return 0; } struct curl_slist *Curl_cookie_list(struct SessionHandle *data) { struct curl_slist *list = NULL; struct curl_slist *beg; struct Cookie *c; char *line; if((data->cookies == NULL) || (data->cookies->numcookies == 0)) return NULL; c = data->cookies->cookies; while(c) { /* fill the list with _all_ the cookies we know */ line = get_netscape_format(c); if(!line) { curl_slist_free_all(list); return NULL; } beg = curl_slist_append(list, line); free(line); if(!beg) { curl_slist_free_all(list); return NULL; } list = beg; c = c->next; } return list; } void Curl_flush_cookies(struct SessionHandle *data, int cleanup) { if(data->set.str[STRING_COOKIEJAR]) { if(data->change.cookielist) { /* If there is a list of cookie files to read, do it first so that we have all the told files read before we write the new jar. Curl_cookie_loadfiles() LOCKS and UNLOCKS the share itself! */ Curl_cookie_loadfiles(data); } Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); /* if we have a destination file for all the cookies to get dumped to */ if(cookie_output(data->cookies, data->set.str[STRING_COOKIEJAR])) infof(data, "WARNING: failed to save cookies in %s\n", data->set.str[STRING_COOKIEJAR]); } else { if(cleanup && data->change.cookielist) { /* since nothing is written, we can just free the list of cookie file names */ curl_slist_free_all(data->change.cookielist); /* clean up list */ data->change.cookielist = NULL; } Curl_share_lock(data, CURL_LOCK_DATA_COOKIE, CURL_LOCK_ACCESS_SINGLE); } if(cleanup && (!data->share || (data->cookies != data->share->cookies))) { Curl_cookie_cleanup(data->cookies); } Curl_share_unlock(data, CURL_LOCK_DATA_COOKIE); } #endif /* CURL_DISABLE_HTTP || CURL_DISABLE_COOKIES */
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5614_0
crossvul-cpp_data_bad_1793_0
/* -*- mode: c; c-file-style: "bsd"; indent-tabs-mode: t -*- */ /* * Copyright 1993 OpenVision Technologies, Inc., All Rights Reserved */ #include <gssrpc/rpc.h> #include <krb5.h> #include <errno.h> #include <kadm5/admin.h> #include <kadm5/kadm_rpc.h> #include <kadm5/admin_xdr.h> #include <stdlib.h> #include <string.h> static bool_t _xdr_kadm5_principal_ent_rec(XDR *xdrs, kadm5_principal_ent_rec *objp, int v); static bool_t _xdr_kadm5_policy_ent_rec(XDR *xdrs, kadm5_policy_ent_rec *objp, int vers); /* * Function: xdr_ui_4 * * Purpose: XDR function which serves as a wrapper for xdr_u_int32, * to prevent compiler warnings about type clashes between u_int32 * and krb5_ui_4. */ bool_t xdr_ui_4(XDR *xdrs, krb5_ui_4 *objp) { /* Assumes that krb5_ui_4 and u_int32 are both four bytes long. This should not be a harmful assumption. */ return xdr_u_int32(xdrs, (uint32_t *) objp); } /* * Function: xdr_nullstring * * Purpose: XDR function for "strings" that are either NULL-terminated * or NULL. */ bool_t xdr_nullstring(XDR *xdrs, char **objp) { u_int size; if (xdrs->x_op == XDR_ENCODE) { if (*objp == NULL) size = 0; else size = strlen(*objp) + 1; } if (! xdr_u_int(xdrs, &size)) { return FALSE; } switch (xdrs->x_op) { case XDR_DECODE: if (size == 0) { *objp = NULL; return TRUE; } else if (*objp == NULL) { *objp = (char *) mem_alloc(size); if (*objp == NULL) { errno = ENOMEM; return FALSE; } } return (xdr_opaque(xdrs, *objp, size)); case XDR_ENCODE: if (size != 0) return (xdr_opaque(xdrs, *objp, size)); return TRUE; case XDR_FREE: if (*objp != NULL) mem_free(*objp, size); *objp = NULL; return TRUE; } return FALSE; } /* * Function: xdr_nulltype * * Purpose: XDR function for arbitrary pointer types that are either * NULL or contain data. */ bool_t xdr_nulltype(XDR *xdrs, void **objp, xdrproc_t proc) { bool_t null; switch (xdrs->x_op) { case XDR_DECODE: if (!xdr_bool(xdrs, &null)) return FALSE; if (null) { *objp = NULL; return TRUE; } return (*proc)(xdrs, objp); case XDR_ENCODE: if (*objp == NULL) null = TRUE; else null = FALSE; if (!xdr_bool(xdrs, &null)) return FALSE; if (null == FALSE) return (*proc)(xdrs, objp); return TRUE; case XDR_FREE: if (*objp) return (*proc)(xdrs, objp); return TRUE; } return FALSE; } bool_t xdr_krb5_timestamp(XDR *xdrs, krb5_timestamp *objp) { /* This assumes that int32 and krb5_timestamp are the same size. This shouldn't be a problem, since we've got a unit test which checks for this. */ if (!xdr_int32(xdrs, (int32_t *) objp)) { return (FALSE); } return (TRUE); } bool_t xdr_krb5_kvno(XDR *xdrs, krb5_kvno *objp) { return xdr_u_int(xdrs, objp); } bool_t xdr_krb5_deltat(XDR *xdrs, krb5_deltat *objp) { /* This assumes that int32 and krb5_deltat are the same size. This shouldn't be a problem, since we've got a unit test which checks for this. */ if (!xdr_int32(xdrs, (int32_t *) objp)) { return (FALSE); } return (TRUE); } bool_t xdr_krb5_flags(XDR *xdrs, krb5_flags *objp) { /* This assumes that int32 and krb5_flags are the same size. This shouldn't be a problem, since we've got a unit test which checks for this. */ if (!xdr_int32(xdrs, (int32_t *) objp)) { return (FALSE); } return (TRUE); } bool_t xdr_krb5_ui_4(XDR *xdrs, krb5_ui_4 *objp) { if (!xdr_u_int32(xdrs, (uint32_t *) objp)) { return (FALSE); } return (TRUE); } bool_t xdr_krb5_int16(XDR *xdrs, krb5_int16 *objp) { int tmp; tmp = (int) *objp; if (!xdr_int(xdrs, &tmp)) return(FALSE); *objp = (krb5_int16) tmp; return(TRUE); } /* * Function: xdr_krb5_ui_2 * * Purpose: XDR function which serves as a wrapper for xdr_u_int, * to prevent compiler warnings about type clashes between u_int * and krb5_ui_2. */ bool_t xdr_krb5_ui_2(XDR *xdrs, krb5_ui_2 *objp) { unsigned int tmp; tmp = (unsigned int) *objp; if (!xdr_u_int(xdrs, &tmp)) return(FALSE); *objp = (krb5_ui_2) tmp; return(TRUE); } static bool_t xdr_krb5_boolean(XDR *xdrs, krb5_boolean *kbool) { bool_t val; switch (xdrs->x_op) { case XDR_DECODE: if (!xdr_bool(xdrs, &val)) return FALSE; *kbool = (val == FALSE) ? FALSE : TRUE; return TRUE; case XDR_ENCODE: val = *kbool ? TRUE : FALSE; return xdr_bool(xdrs, &val); case XDR_FREE: return TRUE; } return FALSE; } bool_t xdr_krb5_key_data_nocontents(XDR *xdrs, krb5_key_data *objp) { /* * Note that this function intentionally DOES NOT tranfer key * length or contents! xdr_krb5_key_data in adb_xdr.c does, but * that is only for use within the server-side library. */ unsigned int tmp; if (xdrs->x_op == XDR_DECODE) memset(objp, 0, sizeof(krb5_key_data)); if (!xdr_krb5_int16(xdrs, &objp->key_data_ver)) { return (FALSE); } if (!xdr_krb5_ui_2(xdrs, &objp->key_data_kvno)) { return (FALSE); } if (!xdr_krb5_int16(xdrs, &objp->key_data_type[0])) { return (FALSE); } if (objp->key_data_ver > 1) { if (!xdr_krb5_int16(xdrs, &objp->key_data_type[1])) { return (FALSE); } } /* * kadm5_get_principal on the server side allocates and returns * key contents when asked. Even though this function refuses to * transmit that data, it still has to *free* the data at the * appropriate time to avoid a memory leak. */ if (xdrs->x_op == XDR_FREE) { tmp = (unsigned int) objp->key_data_length[0]; if (!xdr_bytes(xdrs, (char **) &objp->key_data_contents[0], &tmp, ~0)) return FALSE; tmp = (unsigned int) objp->key_data_length[1]; if (!xdr_bytes(xdrs, (char **) &objp->key_data_contents[1], &tmp, ~0)) return FALSE; } return (TRUE); } bool_t xdr_krb5_key_salt_tuple(XDR *xdrs, krb5_key_salt_tuple *objp) { if (!xdr_krb5_enctype(xdrs, &objp->ks_enctype)) return FALSE; if (!xdr_krb5_salttype(xdrs, &objp->ks_salttype)) return FALSE; return TRUE; } bool_t xdr_krb5_tl_data(XDR *xdrs, krb5_tl_data **tl_data_head) { krb5_tl_data *tl, *tl2; bool_t more; unsigned int len; switch (xdrs->x_op) { case XDR_FREE: tl = tl2 = *tl_data_head; while (tl) { tl2 = tl->tl_data_next; free(tl->tl_data_contents); free(tl); tl = tl2; } *tl_data_head = NULL; break; case XDR_ENCODE: tl = *tl_data_head; while (1) { more = (tl != NULL); if (!xdr_bool(xdrs, &more)) return FALSE; if (tl == NULL) break; if (!xdr_krb5_int16(xdrs, &tl->tl_data_type)) return FALSE; len = tl->tl_data_length; if (!xdr_bytes(xdrs, (char **) &tl->tl_data_contents, &len, ~0)) return FALSE; tl = tl->tl_data_next; } break; case XDR_DECODE: tl = NULL; while (1) { if (!xdr_bool(xdrs, &more)) return FALSE; if (more == FALSE) break; tl2 = (krb5_tl_data *) malloc(sizeof(krb5_tl_data)); if (tl2 == NULL) return FALSE; memset(tl2, 0, sizeof(krb5_tl_data)); if (!xdr_krb5_int16(xdrs, &tl2->tl_data_type)) return FALSE; if (!xdr_bytes(xdrs, (char **)&tl2->tl_data_contents, &len, ~0)) return FALSE; tl2->tl_data_length = len; tl2->tl_data_next = tl; tl = tl2; } *tl_data_head = tl; break; } return TRUE; } bool_t xdr_kadm5_ret_t(XDR *xdrs, kadm5_ret_t *objp) { uint32_t tmp; if (xdrs->x_op == XDR_ENCODE) tmp = (uint32_t) *objp; if (!xdr_u_int32(xdrs, &tmp)) return (FALSE); if (xdrs->x_op == XDR_DECODE) *objp = (kadm5_ret_t) tmp; return (TRUE); } bool_t xdr_kadm5_principal_ent_rec(XDR *xdrs, kadm5_principal_ent_rec *objp) { return _xdr_kadm5_principal_ent_rec(xdrs, objp, KADM5_API_VERSION_3); } static bool_t _xdr_kadm5_principal_ent_rec(XDR *xdrs, kadm5_principal_ent_rec *objp, int v) { unsigned int n; if (!xdr_krb5_principal(xdrs, &objp->principal)) { return (FALSE); } if (!xdr_krb5_timestamp(xdrs, &objp->princ_expire_time)) { return (FALSE); } if (!xdr_krb5_timestamp(xdrs, &objp->last_pwd_change)) { return (FALSE); } if (!xdr_krb5_timestamp(xdrs, &objp->pw_expiration)) { return (FALSE); } if (!xdr_krb5_deltat(xdrs, &objp->max_life)) { return (FALSE); } if (!xdr_nulltype(xdrs, (void **) &objp->mod_name, xdr_krb5_principal)) { return (FALSE); } if (!xdr_krb5_timestamp(xdrs, &objp->mod_date)) { return (FALSE); } if (!xdr_krb5_flags(xdrs, &objp->attributes)) { return (FALSE); } if (!xdr_krb5_kvno(xdrs, &objp->kvno)) { return (FALSE); } if (!xdr_krb5_kvno(xdrs, &objp->mkvno)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->policy)) { return (FALSE); } if (!xdr_long(xdrs, &objp->aux_attributes)) { return (FALSE); } if (!xdr_krb5_deltat(xdrs, &objp->max_renewable_life)) { return (FALSE); } if (!xdr_krb5_timestamp(xdrs, &objp->last_success)) { return (FALSE); } if (!xdr_krb5_timestamp(xdrs, &objp->last_failed)) { return (FALSE); } if (!xdr_krb5_kvno(xdrs, &objp->fail_auth_count)) { return (FALSE); } if (!xdr_krb5_int16(xdrs, &objp->n_key_data)) { return (FALSE); } if (!xdr_krb5_int16(xdrs, &objp->n_tl_data)) { return (FALSE); } if (!xdr_nulltype(xdrs, (void **) &objp->tl_data, xdr_krb5_tl_data)) { return FALSE; } n = objp->n_key_data; if (!xdr_array(xdrs, (caddr_t *) &objp->key_data, &n, ~0, sizeof(krb5_key_data), xdr_krb5_key_data_nocontents)) { return (FALSE); } return (TRUE); } static bool_t _xdr_kadm5_policy_ent_rec(XDR *xdrs, kadm5_policy_ent_rec *objp, int vers) { if (!xdr_nullstring(xdrs, &objp->policy)) { return (FALSE); } /* these all used to be u_int32, but it's stupid for sized types to be exposed at the api, and they're the same as longs on the wire. */ if (!xdr_long(xdrs, &objp->pw_min_life)) { return (FALSE); } if (!xdr_long(xdrs, &objp->pw_max_life)) { return (FALSE); } if (!xdr_long(xdrs, &objp->pw_min_length)) { return (FALSE); } if (!xdr_long(xdrs, &objp->pw_min_classes)) { return (FALSE); } if (!xdr_long(xdrs, &objp->pw_history_num)) { return (FALSE); } if (!xdr_long(xdrs, &objp->policy_refcnt)) { return (FALSE); } if (xdrs->x_op == XDR_DECODE) { objp->pw_max_fail = 0; objp->pw_failcnt_interval = 0; objp->pw_lockout_duration = 0; objp->attributes = 0; objp->max_life = 0; objp->max_renewable_life = 0; objp->allowed_keysalts = NULL; objp->n_tl_data = 0; objp->tl_data = NULL; } if (vers >= KADM5_API_VERSION_3) { if (!xdr_krb5_kvno(xdrs, &objp->pw_max_fail)) return (FALSE); if (!xdr_krb5_deltat(xdrs, &objp->pw_failcnt_interval)) return (FALSE); if (!xdr_krb5_deltat(xdrs, &objp->pw_lockout_duration)) return (FALSE); } if (vers >= KADM5_API_VERSION_4) { if (!xdr_krb5_flags(xdrs, &objp->attributes)) { return (FALSE); } if (!xdr_krb5_deltat(xdrs, &objp->max_life)) { return (FALSE); } if (!xdr_krb5_deltat(xdrs, &objp->max_renewable_life)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->allowed_keysalts)) { return (FALSE); } if (!xdr_krb5_int16(xdrs, &objp->n_tl_data)) { return (FALSE); } if (!xdr_nulltype(xdrs, (void **) &objp->tl_data, xdr_krb5_tl_data)) { return FALSE; } } return (TRUE); } bool_t xdr_kadm5_policy_ent_rec(XDR *xdrs, kadm5_policy_ent_rec *objp) { return _xdr_kadm5_policy_ent_rec(xdrs, objp, KADM5_API_VERSION_4); } bool_t xdr_cprinc_arg(XDR *xdrs, cprinc_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!_xdr_kadm5_principal_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->passwd)) { return (FALSE); } return (TRUE); } bool_t xdr_cprinc3_arg(XDR *xdrs, cprinc3_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!_xdr_kadm5_principal_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *)&objp->ks_tuple, (unsigned int *)&objp->n_ks_tuple, ~0, sizeof(krb5_key_salt_tuple), xdr_krb5_key_salt_tuple)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->passwd)) { return (FALSE); } return (TRUE); } bool_t xdr_generic_ret(XDR *xdrs, generic_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } return(TRUE); } bool_t xdr_dprinc_arg(XDR *xdrs, dprinc_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } return (TRUE); } bool_t xdr_mprinc_arg(XDR *xdrs, mprinc_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!_xdr_kadm5_principal_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return (FALSE); } return (TRUE); } bool_t xdr_rprinc_arg(XDR *xdrs, rprinc_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->src)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->dest)) { return (FALSE); } return (TRUE); } bool_t xdr_gprincs_arg(XDR *xdrs, gprincs_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->exp)) { return (FALSE); } return (TRUE); } bool_t xdr_gprincs_ret(XDR *xdrs, gprincs_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } if (objp->code == KADM5_OK) { if (!xdr_int(xdrs, &objp->count)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->princs, (unsigned int *) &objp->count, ~0, sizeof(char *), xdr_nullstring)) { return (FALSE); } } return (TRUE); } bool_t xdr_chpass_arg(XDR *xdrs, chpass_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->pass)) { return (FALSE); } return (TRUE); } bool_t xdr_chpass3_arg(XDR *xdrs, chpass3_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_krb5_boolean(xdrs, &objp->keepold)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *)&objp->ks_tuple, (unsigned int*)&objp->n_ks_tuple, ~0, sizeof(krb5_key_salt_tuple), xdr_krb5_key_salt_tuple)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->pass)) { return (FALSE); } return (TRUE); } bool_t xdr_setv4key_arg(XDR *xdrs, setv4key_arg *objp) { unsigned int n_keys = 1; if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->keyblock, &n_keys, ~0, sizeof(krb5_keyblock), xdr_krb5_keyblock)) { return (FALSE); } return (TRUE); } bool_t xdr_setkey_arg(XDR *xdrs, setkey_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->keyblocks, (unsigned int *) &objp->n_keys, ~0, sizeof(krb5_keyblock), xdr_krb5_keyblock)) { return (FALSE); } return (TRUE); } bool_t xdr_setkey3_arg(XDR *xdrs, setkey3_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_krb5_boolean(xdrs, &objp->keepold)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->ks_tuple, (unsigned int *) &objp->n_ks_tuple, ~0, sizeof(krb5_key_salt_tuple), xdr_krb5_key_salt_tuple)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->keyblocks, (unsigned int *) &objp->n_keys, ~0, sizeof(krb5_keyblock), xdr_krb5_keyblock)) { return (FALSE); } return (TRUE); } bool_t xdr_chrand_arg(XDR *xdrs, chrand_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } return (TRUE); } bool_t xdr_chrand3_arg(XDR *xdrs, chrand3_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_krb5_boolean(xdrs, &objp->keepold)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *)&objp->ks_tuple, (unsigned int*)&objp->n_ks_tuple, ~0, sizeof(krb5_key_salt_tuple), xdr_krb5_key_salt_tuple)) { return (FALSE); } return (TRUE); } bool_t xdr_chrand_ret(XDR *xdrs, chrand_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } if (objp->code == KADM5_OK) { if (!xdr_array(xdrs, (char **)&objp->keys, (unsigned int *)&objp->n_keys, ~0, sizeof(krb5_keyblock), xdr_krb5_keyblock)) return FALSE; } return (TRUE); } bool_t xdr_gprinc_arg(XDR *xdrs, gprinc_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return FALSE; } return (TRUE); } bool_t xdr_gprinc_ret(XDR *xdrs, gprinc_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } if(objp->code == KADM5_OK) { if (!_xdr_kadm5_principal_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } } return (TRUE); } bool_t xdr_cpol_arg(XDR *xdrs, cpol_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!_xdr_kadm5_policy_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return (FALSE); } return (TRUE); } bool_t xdr_dpol_arg(XDR *xdrs, dpol_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->name)) { return (FALSE); } return (TRUE); } bool_t xdr_mpol_arg(XDR *xdrs, mpol_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!_xdr_kadm5_policy_ent_rec(xdrs, &objp->rec, objp->api_version)) { return (FALSE); } if (!xdr_long(xdrs, &objp->mask)) { return (FALSE); } return (TRUE); } bool_t xdr_gpol_arg(XDR *xdrs, gpol_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->name)) { return (FALSE); } return (TRUE); } bool_t xdr_gpol_ret(XDR *xdrs, gpol_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } if(objp->code == KADM5_OK) { if (!_xdr_kadm5_policy_ent_rec(xdrs, &objp->rec, objp->api_version)) return (FALSE); } return (TRUE); } bool_t xdr_gpols_arg(XDR *xdrs, gpols_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->exp)) { return (FALSE); } return (TRUE); } bool_t xdr_gpols_ret(XDR *xdrs, gpols_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } if (objp->code == KADM5_OK) { if (!xdr_int(xdrs, &objp->count)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->pols, (unsigned int *) &objp->count, ~0, sizeof(char *), xdr_nullstring)) { return (FALSE); } } return (TRUE); } bool_t xdr_getprivs_ret(XDR *xdrs, getprivs_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (! xdr_kadm5_ret_t(xdrs, &objp->code) || ! xdr_long(xdrs, &objp->privs)) return FALSE; return TRUE; } bool_t xdr_purgekeys_arg(XDR *xdrs, purgekeys_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_int(xdrs, &objp->keepkvno)) { return FALSE; } return (TRUE); } bool_t xdr_gstrings_arg(XDR *xdrs, gstrings_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } return (TRUE); } bool_t xdr_gstrings_ret(XDR *xdrs, gstrings_ret *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_kadm5_ret_t(xdrs, &objp->code)) { return (FALSE); } if (objp->code == KADM5_OK) { if (!xdr_int(xdrs, &objp->count)) { return (FALSE); } if (!xdr_array(xdrs, (caddr_t *) &objp->strings, (unsigned int *) &objp->count, ~0, sizeof(krb5_string_attr), xdr_krb5_string_attr)) { return (FALSE); } } return (TRUE); } bool_t xdr_sstring_arg(XDR *xdrs, sstring_arg *objp) { if (!xdr_ui_4(xdrs, &objp->api_version)) { return (FALSE); } if (!xdr_krb5_principal(xdrs, &objp->princ)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->key)) { return (FALSE); } if (!xdr_nullstring(xdrs, &objp->value)) { return (FALSE); } return (TRUE); } bool_t xdr_krb5_principal(XDR *xdrs, krb5_principal *objp) { int ret; char *p = NULL; krb5_principal pr = NULL; static krb5_context context = NULL; /* using a static context here is ugly, but should work ok, and the other solutions are even uglier */ if (!context && kadm5_init_krb5_context(&context)) return(FALSE); switch(xdrs->x_op) { case XDR_ENCODE: if (*objp) { if((ret = krb5_unparse_name(context, *objp, &p)) != 0) return FALSE; } if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) free(p); break; case XDR_DECODE: if(!xdr_nullstring(xdrs, &p)) return FALSE; if (p) { ret = krb5_parse_name(context, p, &pr); if(ret != 0) return FALSE; *objp = pr; free(p); } else *objp = NULL; break; case XDR_FREE: if(*objp != NULL) krb5_free_principal(context, *objp); *objp = NULL; break; } return TRUE; } bool_t xdr_krb5_octet(XDR *xdrs, krb5_octet *objp) { if (!xdr_u_char(xdrs, objp)) return (FALSE); return (TRUE); } bool_t xdr_krb5_enctype(XDR *xdrs, krb5_enctype *objp) { /* * This used to be xdr_krb5_keytype, but keytypes and enctypes have * been merged into only enctypes. However, randkey_principal * already ensures that only a key of ENCTYPE_DES_CBC_CRC will be * returned to v1 clients, and ENCTYPE_DES_CBC_CRC has the same * value as KEYTYPE_DES used too, which is what all v1 clients * expect. Therefore, IMHO, just encoding whatever enctype we get * is safe. */ if (!xdr_int32(xdrs, (int32_t *) objp)) return (FALSE); return (TRUE); } bool_t xdr_krb5_salttype(XDR *xdrs, krb5_int32 *objp) { if (!xdr_int32(xdrs, (int32_t *) objp)) return FALSE; return TRUE; } bool_t xdr_krb5_keyblock(XDR *xdrs, krb5_keyblock *objp) { /* XXX This only works because free_keyblock assumes ->contents is allocated by malloc() */ if(!xdr_krb5_enctype(xdrs, &objp->enctype)) return FALSE; if(!xdr_bytes(xdrs, (char **) &objp->contents, (unsigned int *) &objp->length, ~0)) return FALSE; return TRUE; } bool_t xdr_krb5_string_attr(XDR *xdrs, krb5_string_attr *objp) { if (!xdr_nullstring(xdrs, &objp->key)) return FALSE; if (!xdr_nullstring(xdrs, &objp->value)) return FALSE; if (xdrs->x_op == XDR_DECODE && (objp->key == NULL || objp->value == NULL)) return FALSE; return TRUE; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1793_0
crossvul-cpp_data_bad_3826_0
/* xfrm_user.c: User interface to configure xfrm engine. * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * * Changes: * Mitsuru KANDA @USAGI * Kazunori MIYAZAWA @USAGI * Kunihiro Ishiguro <kunihiro@ipinfusion.com> * IPv6 support * */ #include <linux/crypto.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/string.h> #include <linux/net.h> #include <linux/skbuff.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/init.h> #include <linux/security.h> #include <net/sock.h> #include <net/xfrm.h> #include <net/netlink.h> #include <net/ah.h> #include <asm/uaccess.h> #if IS_ENABLED(CONFIG_IPV6) #include <linux/in6.h> #endif static inline int aead_len(struct xfrm_algo_aead *alg) { return sizeof(*alg) + ((alg->alg_key_len + 7) / 8); } static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type) { struct nlattr *rt = attrs[type]; struct xfrm_algo *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < xfrm_alg_len(algp)) return -EINVAL; switch (type) { case XFRMA_ALG_AUTH: case XFRMA_ALG_CRYPT: case XFRMA_ALG_COMP: break; default: return -EINVAL; } algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static int verify_auth_trunc(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC]; struct xfrm_algo_auth *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < xfrm_alg_auth_len(algp)) return -EINVAL; algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static int verify_aead(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_ALG_AEAD]; struct xfrm_algo_aead *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < aead_len(algp)) return -EINVAL; algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type, xfrm_address_t **addrp) { struct nlattr *rt = attrs[type]; if (rt && addrp) *addrp = nla_data(rt); } static inline int verify_sec_ctx_len(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = nla_data(rt); if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len)) return -EINVAL; return 0; } static inline int verify_replay(struct xfrm_usersa_info *p, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL]; if ((p->flags & XFRM_STATE_ESN) && !rt) return -EINVAL; if (!rt) return 0; if (p->id.proto != IPPROTO_ESP) return -EINVAL; if (p->replay_window != 0) return -EINVAL; return 0; } static int verify_newsa_info(struct xfrm_usersa_info *p, struct nlattr **attrs) { int err; err = -EINVAL; switch (p->family) { case AF_INET: break; case AF_INET6: #if IS_ENABLED(CONFIG_IPV6) break; #else err = -EAFNOSUPPORT; goto out; #endif default: goto out; } err = -EINVAL; switch (p->id.proto) { case IPPROTO_AH: if ((!attrs[XFRMA_ALG_AUTH] && !attrs[XFRMA_ALG_AUTH_TRUNC]) || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_ALG_COMP] || attrs[XFRMA_TFCPAD]) goto out; break; case IPPROTO_ESP: if (attrs[XFRMA_ALG_COMP]) goto out; if (!attrs[XFRMA_ALG_AUTH] && !attrs[XFRMA_ALG_AUTH_TRUNC] && !attrs[XFRMA_ALG_CRYPT] && !attrs[XFRMA_ALG_AEAD]) goto out; if ((attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_CRYPT]) && attrs[XFRMA_ALG_AEAD]) goto out; if (attrs[XFRMA_TFCPAD] && p->mode != XFRM_MODE_TUNNEL) goto out; break; case IPPROTO_COMP: if (!attrs[XFRMA_ALG_COMP] || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_TFCPAD]) goto out; break; #if IS_ENABLED(CONFIG_IPV6) case IPPROTO_DSTOPTS: case IPPROTO_ROUTING: if (attrs[XFRMA_ALG_COMP] || attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_ENCAP] || attrs[XFRMA_SEC_CTX] || attrs[XFRMA_TFCPAD] || !attrs[XFRMA_COADDR]) goto out; break; #endif default: goto out; } if ((err = verify_aead(attrs))) goto out; if ((err = verify_auth_trunc(attrs))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP))) goto out; if ((err = verify_sec_ctx_len(attrs))) goto out; if ((err = verify_replay(p, attrs))) goto out; err = -EINVAL; switch (p->mode) { case XFRM_MODE_TRANSPORT: case XFRM_MODE_TUNNEL: case XFRM_MODE_ROUTEOPTIMIZATION: case XFRM_MODE_BEET: break; default: goto out; } err = 0; out: return err; } static int attach_one_algo(struct xfrm_algo **algpp, u8 *props, struct xfrm_algo_desc *(*get_byname)(const char *, int), struct nlattr *rta) { struct xfrm_algo *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); *algpp = p; return 0; } static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo *ualg; struct xfrm_algo_auth *p; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aalg_get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); p->alg_key_len = ualg->alg_key_len; p->alg_trunc_len = algo->uinfo.auth.icv_truncbits; memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8); *algpp = p; return 0; } static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo_auth *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aalg_get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN || ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits) return -EINVAL; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); if (!p->alg_trunc_len) p->alg_trunc_len = algo->uinfo.auth.icv_truncbits; *algpp = p; return 0; } static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo_aead *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); *algpp = p; return 0; } static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; if (!replay_esn || !rp) return 0; up = nla_data(rp); if (xfrm_replay_state_esn_len(replay_esn) != xfrm_replay_state_esn_len(up)) return -EINVAL; return 0; } static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn, struct xfrm_replay_state_esn **preplay_esn, struct nlattr *rta) { struct xfrm_replay_state_esn *p, *pp, *up; if (!rta) return 0; up = nla_data(rta); p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!p) return -ENOMEM; pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!pp) { kfree(p); return -ENOMEM; } *replay_esn = p; *preplay_esn = pp; return 0; } static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx) { int len = 0; if (xfrm_ctx) { len += sizeof(struct xfrm_user_sec_ctx); len += xfrm_ctx->ctx_len; } return len; } static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&x->id, &p->id, sizeof(x->id)); memcpy(&x->sel, &p->sel, sizeof(x->sel)); memcpy(&x->lft, &p->lft, sizeof(x->lft)); x->props.mode = p->mode; x->props.replay_window = p->replay_window; x->props.reqid = p->reqid; x->props.family = p->family; memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr)); x->props.flags = p->flags; if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC)) x->sel.family = p->family; } /* * someday when pfkey also has support, we could have the code * somehow made shareable and move it to xfrm_state.c - JHS * */ static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs) { struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL]; struct nlattr *lt = attrs[XFRMA_LTIME_VAL]; struct nlattr *et = attrs[XFRMA_ETIMER_THRESH]; struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH]; if (re) { struct xfrm_replay_state_esn *replay_esn; replay_esn = nla_data(re); memcpy(x->replay_esn, replay_esn, xfrm_replay_state_esn_len(replay_esn)); memcpy(x->preplay_esn, replay_esn, xfrm_replay_state_esn_len(replay_esn)); } if (rp) { struct xfrm_replay_state *replay; replay = nla_data(rp); memcpy(&x->replay, replay, sizeof(*replay)); memcpy(&x->preplay, replay, sizeof(*replay)); } if (lt) { struct xfrm_lifetime_cur *ltime; ltime = nla_data(lt); x->curlft.bytes = ltime->bytes; x->curlft.packets = ltime->packets; x->curlft.add_time = ltime->add_time; x->curlft.use_time = ltime->use_time; } if (et) x->replay_maxage = nla_get_u32(et); if (rt) x->replay_maxdiff = nla_get_u32(rt); } static struct xfrm_state *xfrm_state_construct(struct net *net, struct xfrm_usersa_info *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = xfrm_state_alloc(net); int err = -ENOMEM; if (!x) goto error_no_put; copy_from_user_state(x, p); if ((err = attach_aead(&x->aead, &x->props.ealgo, attrs[XFRMA_ALG_AEAD]))) goto error; if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH_TRUNC]))) goto error; if (!x->props.aalgo) { if ((err = attach_auth(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH]))) goto error; } if ((err = attach_one_algo(&x->ealg, &x->props.ealgo, xfrm_ealg_get_byname, attrs[XFRMA_ALG_CRYPT]))) goto error; if ((err = attach_one_algo(&x->calg, &x->props.calgo, xfrm_calg_get_byname, attrs[XFRMA_ALG_COMP]))) goto error; if (attrs[XFRMA_ENCAP]) { x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]), sizeof(*x->encap), GFP_KERNEL); if (x->encap == NULL) goto error; } if (attrs[XFRMA_TFCPAD]) x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]); if (attrs[XFRMA_COADDR]) { x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]), sizeof(*x->coaddr), GFP_KERNEL); if (x->coaddr == NULL) goto error; } xfrm_mark_get(attrs, &x->mark); err = __xfrm_init_state(x, false); if (err) goto error; if (attrs[XFRMA_SEC_CTX] && security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX]))) goto error; if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn, attrs[XFRMA_REPLAY_ESN_VAL]))) goto error; x->km.seq = p->seq; x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth; /* sysctl_xfrm_aevent_etime is in 100ms units */ x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M; if ((err = xfrm_init_replay(x))) goto error; /* override default values from above */ xfrm_update_ae_params(x, attrs); return x; error: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); error_no_put: *errp = err; return NULL; } static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_usersa_info *p = nlmsg_data(nlh); struct xfrm_state *x; int err; struct km_event c; uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; err = verify_newsa_info(p, attrs); if (err) return err; x = xfrm_state_construct(net, p, attrs, &err); if (!x) return err; xfrm_state_hold(x); if (nlh->nlmsg_type == XFRM_MSG_NEWSA) err = xfrm_state_add(x); else err = xfrm_state_update(x); security_task_getsecid(current, &sid); xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static struct xfrm_state *xfrm_user_state_lookup(struct net *net, struct xfrm_usersa_id *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = NULL; struct xfrm_mark m; int err; u32 mark = xfrm_mark_get(attrs, &m); if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) { err = -ESRCH; x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family); } else { xfrm_address_t *saddr = NULL; verify_one_addr(attrs, XFRMA_SRCADDR, &saddr); if (!saddr) { err = -EINVAL; goto out; } err = -ESRCH; x = xfrm_state_lookup_byaddr(net, mark, &p->daddr, saddr, p->proto, p->family); } out: if (!x && errp) *errp = err; return x; } static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; int err = -ESRCH; struct km_event c; struct xfrm_usersa_id *p = nlmsg_data(nlh); uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; x = xfrm_user_state_lookup(net, p, attrs, &err); if (x == NULL) return err; if ((err = security_xfrm_state_delete(x)) != 0) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: security_task_getsecid(current, &sid); xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid); xfrm_state_put(x); return err; } static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } struct xfrm_dump_info { struct sk_buff *in_skb; struct sk_buff *out_skb; u32 nlmsg_seq; u16 nlmsg_flags; }; static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb) { struct xfrm_user_sec_ctx *uctx; struct nlattr *attr; int ctx_size = sizeof(*uctx) + s->ctx_len; attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size); if (attr == NULL) return -EMSGSIZE; uctx = nla_data(attr); uctx->exttype = XFRMA_SEC_CTX; uctx->len = ctx_size; uctx->ctx_doi = s->ctx_doi; uctx->ctx_alg = s->ctx_alg; uctx->ctx_len = s->ctx_len; memcpy(uctx + 1, s->ctx_str, s->ctx_len); return 0; } static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb) { struct xfrm_algo *algo; struct nlattr *nla; nla = nla_reserve(skb, XFRMA_ALG_AUTH, sizeof(*algo) + (auth->alg_key_len + 7) / 8); if (!nla) return -EMSGSIZE; algo = nla_data(nla); strcpy(algo->alg_name, auth->alg_name); memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8); algo->alg_key_len = auth->alg_key_len; return 0; } /* Don't change this without updating xfrm_sa_len! */ static int copy_to_user_state_extra(struct xfrm_state *x, struct xfrm_usersa_info *p, struct sk_buff *skb) { int ret = 0; copy_to_user_state(x, p); if (x->coaddr) { ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr); if (ret) goto out; } if (x->lastused) { ret = nla_put_u64(skb, XFRMA_LASTUSED, x->lastused); if (ret) goto out; } if (x->aead) { ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead); if (ret) goto out; } if (x->aalg) { ret = copy_to_user_auth(x->aalg, skb); if (!ret) ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC, xfrm_alg_auth_len(x->aalg), x->aalg); if (ret) goto out; } if (x->ealg) { ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg); if (ret) goto out; } if (x->calg) { ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg); if (ret) goto out; } if (x->encap) { ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap); if (ret) goto out; } if (x->tfcpad) { ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad); if (ret) goto out; } ret = xfrm_mark_put(skb, &x->mark); if (ret) goto out; if (x->replay_esn) { ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL, xfrm_replay_state_esn_len(x->replay_esn), x->replay_esn); if (ret) goto out; } if (x->security) ret = copy_sec_ctx(x->security, skb); out: return ret; } static int dump_one_state(struct xfrm_state *x, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct xfrm_usersa_info *p; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags); if (nlh == NULL) return -EMSGSIZE; p = nlmsg_data(nlh); err = copy_to_user_state_extra(x, p, skb); if (err) { nlmsg_cancel(skb, nlh); return err; } nlmsg_end(skb, nlh); return 0; } static int xfrm_dump_sa_done(struct netlink_callback *cb) { struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1]; xfrm_state_walk_done(walk); return 0; } static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_state_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_state_walk_init(walk, 0); } (void) xfrm_state_walk(net, walk, dump_one_state, &info); return skb->len; } static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb, struct xfrm_state *x, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; int err; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; err = dump_one_state(x, 0, &info); if (err) { kfree_skb(skb); return ERR_PTR(err); } return skb; } static inline size_t xfrm_spdinfo_msgsize(void) { return NLMSG_ALIGN(4) + nla_total_size(sizeof(struct xfrmu_spdinfo)) + nla_total_size(sizeof(struct xfrmu_spdhinfo)); } static int build_spdinfo(struct sk_buff *skb, struct net *net, u32 pid, u32 seq, u32 flags) { struct xfrmk_spdinfo si; struct xfrmu_spdinfo spc; struct xfrmu_spdhinfo sph; struct nlmsghdr *nlh; int err; u32 *f; nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0); if (nlh == NULL) /* shouldn't really happen ... */ return -EMSGSIZE; f = nlmsg_data(nlh); *f = flags; xfrm_spd_getinfo(net, &si); spc.incnt = si.incnt; spc.outcnt = si.outcnt; spc.fwdcnt = si.fwdcnt; spc.inscnt = si.inscnt; spc.outscnt = si.outscnt; spc.fwdscnt = si.fwdscnt; sph.spdhcnt = si.spdhcnt; sph.spdhmcnt = si.spdhmcnt; err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc); if (!err) err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct sk_buff *r_skb; u32 *flags = nlmsg_data(nlh); u32 spid = NETLINK_CB(skb).pid; u32 seq = nlh->nlmsg_seq; r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC); if (r_skb == NULL) return -ENOMEM; if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0) BUG(); return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid); } static inline size_t xfrm_sadinfo_msgsize(void) { return NLMSG_ALIGN(4) + nla_total_size(sizeof(struct xfrmu_sadhinfo)) + nla_total_size(4); /* XFRMA_SAD_CNT */ } static int build_sadinfo(struct sk_buff *skb, struct net *net, u32 pid, u32 seq, u32 flags) { struct xfrmk_sadinfo si; struct xfrmu_sadhinfo sh; struct nlmsghdr *nlh; int err; u32 *f; nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0); if (nlh == NULL) /* shouldn't really happen ... */ return -EMSGSIZE; f = nlmsg_data(nlh); *f = flags; xfrm_sad_getinfo(net, &si); sh.sadhmcnt = si.sadhmcnt; sh.sadhcnt = si.sadhcnt; err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt); if (!err) err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct sk_buff *r_skb; u32 *flags = nlmsg_data(nlh); u32 spid = NETLINK_CB(skb).pid; u32 seq = nlh->nlmsg_seq; r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC); if (r_skb == NULL) return -ENOMEM; if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0) BUG(); return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid); } static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_usersa_id *p = nlmsg_data(nlh); struct xfrm_state *x; struct sk_buff *resp_skb; int err = -ESRCH; x = xfrm_user_state_lookup(net, p, attrs, &err); if (x == NULL) goto out_noput; resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); } xfrm_state_put(x); out_noput: return err; } static int verify_userspi_info(struct xfrm_userspi_info *p) { switch (p->info.id.proto) { case IPPROTO_AH: case IPPROTO_ESP: break; case IPPROTO_COMP: /* IPCOMP spi is 16-bits. */ if (p->max >= 0x10000) return -EINVAL; break; default: return -EINVAL; } if (p->min > p->max) return -EINVAL; return 0; } static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct xfrm_userspi_info *p; struct sk_buff *resp_skb; xfrm_address_t *daddr; int family; int err; u32 mark; struct xfrm_mark m; p = nlmsg_data(nlh); err = verify_userspi_info(p); if (err) goto out_noput; family = p->info.family; daddr = &p->info.id.daddr; x = NULL; mark = xfrm_mark_get(attrs, &m); if (p->info.seq) { x = xfrm_find_acq_byseq(net, mark, p->info.seq); if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid, p->info.id.proto, daddr, &p->info.saddr, 1, family); err = -ENOENT; if (x == NULL) goto out_noput; err = xfrm_alloc_spi(x, p->min, p->max); if (err) goto out; resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); goto out; } err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); out: xfrm_state_put(x); out_noput: return err; } static int verify_policy_dir(u8 dir) { switch (dir) { case XFRM_POLICY_IN: case XFRM_POLICY_OUT: case XFRM_POLICY_FWD: break; default: return -EINVAL; } return 0; } static int verify_policy_type(u8 type) { switch (type) { case XFRM_POLICY_TYPE_MAIN: #ifdef CONFIG_XFRM_SUB_POLICY case XFRM_POLICY_TYPE_SUB: #endif break; default: return -EINVAL; } return 0; } static int verify_newpolicy_info(struct xfrm_userpolicy_info *p) { switch (p->share) { case XFRM_SHARE_ANY: case XFRM_SHARE_SESSION: case XFRM_SHARE_USER: case XFRM_SHARE_UNIQUE: break; default: return -EINVAL; } switch (p->action) { case XFRM_POLICY_ALLOW: case XFRM_POLICY_BLOCK: break; default: return -EINVAL; } switch (p->sel.family) { case AF_INET: break; case AF_INET6: #if IS_ENABLED(CONFIG_IPV6) break; #else return -EAFNOSUPPORT; #endif default: return -EINVAL; } return verify_policy_dir(p->dir); } static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = nla_data(rt); return security_xfrm_policy_alloc(&pol->security, uctx); } static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut, int nr) { int i; xp->xfrm_nr = nr; for (i = 0; i < nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&t->id, &ut->id, sizeof(struct xfrm_id)); memcpy(&t->saddr, &ut->saddr, sizeof(xfrm_address_t)); t->reqid = ut->reqid; t->mode = ut->mode; t->share = ut->share; t->optional = ut->optional; t->aalgos = ut->aalgos; t->ealgos = ut->ealgos; t->calgos = ut->calgos; /* If all masks are ~0, then we allow all algorithms. */ t->allalgs = !~(t->aalgos & t->ealgos & t->calgos); t->encap_family = ut->family; } } static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family) { int i; if (nr > XFRM_MAX_DEPTH) return -EINVAL; for (i = 0; i < nr; i++) { /* We never validated the ut->family value, so many * applications simply leave it at zero. The check was * never made and ut->family was ignored because all * templates could be assumed to have the same family as * the policy itself. Now that we will have ipv4-in-ipv6 * and ipv6-in-ipv4 tunnels, this is no longer true. */ if (!ut[i].family) ut[i].family = family; switch (ut[i].family) { case AF_INET: break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: break; #endif default: return -EINVAL; } } return 0; } static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_TMPL]; if (!rt) { pol->xfrm_nr = 0; } else { struct xfrm_user_tmpl *utmpl = nla_data(rt); int nr = nla_len(rt) / sizeof(*utmpl); int err; err = validate_tmpl(nr, utmpl, pol->family); if (err) return err; copy_templates(pol, utmpl, nr); } return 0; } static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_POLICY_TYPE]; struct xfrm_userpolicy_type *upt; u8 type = XFRM_POLICY_TYPE_MAIN; int err; if (rt) { upt = nla_data(rt); type = upt->type; } err = verify_policy_type(type); if (err) return err; *tp = type; return 0; } static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p) { xp->priority = p->priority; xp->index = p->index; memcpy(&xp->selector, &p->sel, sizeof(xp->selector)); memcpy(&xp->lft, &p->lft, sizeof(xp->lft)); xp->action = p->action; xp->flags = p->flags; xp->family = p->sel.family; /* XXX xp->share = p->share; */ } static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir) { memcpy(&p->sel, &xp->selector, sizeof(p->sel)); memcpy(&p->lft, &xp->lft, sizeof(p->lft)); memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft)); p->priority = xp->priority; p->index = xp->index; p->sel.family = xp->family; p->dir = dir; p->action = xp->action; p->flags = xp->flags; p->share = XFRM_SHARE_ANY; /* XXX xp->share */ } static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp) { struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL); int err; if (!xp) { *errp = -ENOMEM; return NULL; } copy_from_user_policy(xp, p); err = copy_from_user_policy_type(&xp->type, attrs); if (err) goto error; if (!(err = copy_from_user_tmpl(xp, attrs))) err = copy_from_user_sec_ctx(xp, attrs); if (err) goto error; xfrm_mark_get(attrs, &xp->mark); return xp; error: *errp = err; xp->walk.dead = 1; xfrm_policy_destroy(xp); return NULL; } static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_userpolicy_info *p = nlmsg_data(nlh); struct xfrm_policy *xp; struct km_event c; int err; int excl; uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; err = verify_newpolicy_info(p); if (err) return err; err = verify_sec_ctx_len(attrs); if (err) return err; xp = xfrm_policy_construct(net, p, attrs, &err); if (!xp) return err; /* shouldn't excl be based on nlh flags?? * Aha! this is anti-netlink really i.e more pfkey derived * in netlink excl is a flag and you wouldnt need * a type XFRM_MSG_UPDPOLICY - JHS */ excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY; err = xfrm_policy_insert(p->dir, xp, excl); security_task_getsecid(current, &sid); xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid); if (err) { security_xfrm_policy_free(xp->security); kfree(xp); return err; } c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); xfrm_pol_put(xp); return 0; } static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = kp->encap_family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } return nla_put(skb, XFRMA_TMPL, sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec); } static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb) { if (x->security) { return copy_sec_ctx(x->security, skb); } return 0; } static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb) { if (xp->security) return copy_sec_ctx(xp->security, skb); return 0; } static inline size_t userpolicy_type_attrsize(void) { #ifdef CONFIG_XFRM_SUB_POLICY return nla_total_size(sizeof(struct xfrm_userpolicy_type)); #else return 0; #endif } #ifdef CONFIG_XFRM_SUB_POLICY static int copy_to_user_policy_type(u8 type, struct sk_buff *skb) { struct xfrm_userpolicy_type upt = { .type = type, }; return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt); } #else static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb) { return 0; } #endif static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct xfrm_userpolicy_info *p; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags); if (nlh == NULL) return -EMSGSIZE; p = nlmsg_data(nlh); copy_to_user_policy(xp, p, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_sec_ctx(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } nlmsg_end(skb, nlh); return 0; } static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; xfrm_policy_walk_done(walk); return 0; } static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY); } (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; } static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb, struct xfrm_policy *xp, int dir, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; int err; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; err = dump_one_policy(xp, dir, 0, &info); if (err) { kfree_skb(skb); return ERR_PTR(err); } return skb; } static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_userpolicy_id *p; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct km_event c; int delete; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); p = nlmsg_data(nlh); delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY; err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = verify_policy_dir(p->dir); if (err) return err; if (p->index) xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err); else { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_sec_ctx *ctx; err = verify_sec_ctx_len(attrs); if (err) return err; ctx = NULL; if (rt) { struct xfrm_user_sec_ctx *uctx = nla_data(rt); err = security_xfrm_policy_alloc(&ctx, uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel, ctx, delete, &err); security_xfrm_policy_free(ctx); } if (xp == NULL) return -ENOENT; if (!delete) { struct sk_buff *resp_skb; resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); } } else { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid, sid); if (err != 0) goto out; c.data.byid = p->index; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); } out: xfrm_pol_put(xp); return err; } static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; struct xfrm_usersa_flush *p = nlmsg_data(nlh); struct xfrm_audit audit_info; int err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_state_flush(net, p->proto, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.proto = p->proto; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_state_notify(NULL, &c); return 0; } static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x) { size_t replay_size = x->replay_esn ? xfrm_replay_state_esn_len(x->replay_esn) : sizeof(struct xfrm_replay_state); return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id)) + nla_total_size(replay_size) + nla_total_size(sizeof(struct xfrm_lifetime_cur)) + nla_total_size(sizeof(struct xfrm_mark)) + nla_total_size(4) /* XFRM_AE_RTHR */ + nla_total_size(4); /* XFRM_AE_ETHR */ } static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c) { struct xfrm_aevent_id *id; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0); if (nlh == NULL) return -EMSGSIZE; id = nlmsg_data(nlh); memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr)); id->sa_id.spi = x->id.spi; id->sa_id.family = x->props.family; id->sa_id.proto = x->id.proto; memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr)); id->reqid = x->props.reqid; id->flags = c->data.aevent; if (x->replay_esn) { err = nla_put(skb, XFRMA_REPLAY_ESN_VAL, xfrm_replay_state_esn_len(x->replay_esn), x->replay_esn); } else { err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay), &x->replay); } if (err) goto out_cancel; err = nla_put(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft); if (err) goto out_cancel; if (id->flags & XFRM_AE_RTHR) { err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff); if (err) goto out_cancel; } if (id->flags & XFRM_AE_ETHR) { err = nla_put_u32(skb, XFRMA_ETIMER_THRESH, x->replay_maxage * 10 / HZ); if (err) goto out_cancel; } err = xfrm_mark_put(skb, &x->mark); if (err) goto out_cancel; return nlmsg_end(skb, nlh); out_cancel: nlmsg_cancel(skb, nlh); return err; } static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct sk_buff *r_skb; int err; struct km_event c; u32 mark; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct xfrm_usersa_id *id = &p->sa_id; mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family); if (x == NULL) return -ESRCH; r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC); if (r_skb == NULL) { xfrm_state_put(x); return -ENOMEM; } /* * XXX: is this lock really needed - none of the other * gets lock (the concern is things getting updated * while we are still reading) - jhs */ spin_lock_bh(&x->lock); c.data.aevent = p->flags; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; if (build_aevent(r_skb, x, &c) < 0) BUG(); err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid); spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct km_event c; int err = - EINVAL; u32 mark = 0; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL]; struct nlattr *lt = attrs[XFRMA_LTIME_VAL]; if (!lt && !rp && !re) return err; /* pedantic mode - thou shalt sayeth replaceth */ if (!(nlh->nlmsg_flags&NLM_F_REPLACE)) return err; mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family); if (x == NULL) return -ESRCH; if (x->km.state != XFRM_STATE_VALID) goto out; err = xfrm_replay_verify_len(x->replay_esn, rp); if (err) goto out; spin_lock_bh(&x->lock); xfrm_update_ae_params(x, attrs); spin_unlock_bh(&x->lock); c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.data.aevent = XFRM_AE_CU; km_state_notify(x, &c); err = 0; out: xfrm_state_put(x); return err; } static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct xfrm_audit audit_info; err = copy_from_user_policy_type(&type, attrs); if (err) return err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_policy_flush(net, type, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.type = type; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_user_polexpire *up = nlmsg_data(nlh); struct xfrm_userpolicy_info *p = &up->pol; u8 type = XFRM_POLICY_TYPE_MAIN; int err = -ENOENT; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = verify_policy_dir(p->dir); if (err) return err; if (p->index) xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err); else { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_sec_ctx *ctx; err = verify_sec_ctx_len(attrs); if (err) return err; ctx = NULL; if (rt) { struct xfrm_user_sec_ctx *uctx = nla_data(rt); err = security_xfrm_policy_alloc(&ctx, uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel, ctx, 0, &err); security_xfrm_policy_free(ctx); } if (xp == NULL) return -ENOENT; if (unlikely(xp->walk.dead)) goto out; err = 0; if (up->hard) { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); xfrm_policy_delete(xp, p->dir); xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid); } else { // reset the timers here? WARN(1, "Dont know what to do with soft policy expire\n"); } km_policy_expired(xp, p->dir, up->hard, current->pid); out: xfrm_pol_put(xp); return err; } static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; int err; struct xfrm_user_expire *ue = nlmsg_data(nlh); struct xfrm_usersa_info *p = &ue->state; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family); err = -ENOENT; if (x == NULL) return err; spin_lock_bh(&x->lock); err = -EINVAL; if (x->km.state != XFRM_STATE_VALID) goto out; km_state_expired(x, ue->hard, current->pid); if (ue->hard) { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); __xfrm_state_delete(x); xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid); } err = 0; out: spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_user_tmpl *ut; int i; struct nlattr *rt = attrs[XFRMA_TMPL]; struct xfrm_mark mark; struct xfrm_user_acquire *ua = nlmsg_data(nlh); struct xfrm_state *x = xfrm_state_alloc(net); int err = -ENOMEM; if (!x) goto nomem; xfrm_mark_get(attrs, &mark); err = verify_newpolicy_info(&ua->policy); if (err) goto bad_policy; /* build an XP */ xp = xfrm_policy_construct(net, &ua->policy, attrs, &err); if (!xp) goto free_state; memcpy(&x->id, &ua->id, sizeof(ua->id)); memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr)); memcpy(&x->sel, &ua->sel, sizeof(ua->sel)); xp->mark.m = x->mark.m = mark.m; xp->mark.v = x->mark.v = mark.v; ut = nla_data(rt); /* extract the templates and for each call km_key */ for (i = 0; i < xp->xfrm_nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&x->id, &t->id, sizeof(x->id)); x->props.mode = t->mode; x->props.reqid = t->reqid; x->props.family = ut->family; t->aalgos = ua->aalgos; t->ealgos = ua->ealgos; t->calgos = ua->calgos; err = km_query(x, t, xp); } kfree(x); kfree(xp); return 0; bad_policy: WARN(1, "BAD policy passed\n"); free_state: kfree(x); nomem: return err; } #ifdef CONFIG_XFRM_MIGRATE static int copy_from_user_migrate(struct xfrm_migrate *ma, struct xfrm_kmaddress *k, struct nlattr **attrs, int *num) { struct nlattr *rt = attrs[XFRMA_MIGRATE]; struct xfrm_user_migrate *um; int i, num_migrate; if (k != NULL) { struct xfrm_user_kmaddress *uk; uk = nla_data(attrs[XFRMA_KMADDRESS]); memcpy(&k->local, &uk->local, sizeof(k->local)); memcpy(&k->remote, &uk->remote, sizeof(k->remote)); k->family = uk->family; k->reserved = uk->reserved; } um = nla_data(rt); num_migrate = nla_len(rt) / sizeof(*um); if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH) return -EINVAL; for (i = 0; i < num_migrate; i++, um++, ma++) { memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr)); memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr)); memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr)); memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr)); ma->proto = um->proto; ma->mode = um->mode; ma->reqid = um->reqid; ma->old_family = um->old_family; ma->new_family = um->new_family; } *num = i; return 0; } static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct xfrm_userpolicy_id *pi = nlmsg_data(nlh); struct xfrm_migrate m[XFRM_MAX_DEPTH]; struct xfrm_kmaddress km, *kmp; u8 type; int err; int n = 0; if (attrs[XFRMA_MIGRATE] == NULL) return -EINVAL; kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL; err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n); if (err) return err; if (!n) return 0; xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp); return 0; } #else static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { return -ENOPROTOOPT; } #endif #ifdef CONFIG_XFRM_MIGRATE static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb) { struct xfrm_user_migrate um; memset(&um, 0, sizeof(um)); um.proto = m->proto; um.mode = m->mode; um.reqid = m->reqid; um.old_family = m->old_family; memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr)); memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr)); um.new_family = m->new_family; memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr)); memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr)); return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um); } static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb) { struct xfrm_user_kmaddress uk; memset(&uk, 0, sizeof(uk)); uk.family = k->family; uk.reserved = k->reserved; memcpy(&uk.local, &k->local, sizeof(uk.local)); memcpy(&uk.remote, &k->remote, sizeof(uk.remote)); return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk); } static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma) { return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id)) + (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0) + nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate) + userpolicy_type_attrsize(); } static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k, const struct xfrm_selector *sel, u8 dir, u8 type) { const struct xfrm_migrate *mp; struct xfrm_userpolicy_id *pol_id; struct nlmsghdr *nlh; int i, err; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0); if (nlh == NULL) return -EMSGSIZE; pol_id = nlmsg_data(nlh); /* copy data from selector, dir, and type to the pol_id */ memset(pol_id, 0, sizeof(*pol_id)); memcpy(&pol_id->sel, sel, sizeof(pol_id->sel)); pol_id->dir = dir; if (k != NULL) { err = copy_to_user_kmaddress(k, skb); if (err) goto out_cancel; } err = copy_to_user_policy_type(type, skb); if (err) goto out_cancel; for (i = 0, mp = m ; i < num_migrate; i++, mp++) { err = copy_to_user_migrate(mp, skb); if (err) goto out_cancel; } return nlmsg_end(skb, nlh); out_cancel: nlmsg_cancel(skb, nlh); return err; } static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k) { struct net *net = &init_net; struct sk_buff *skb; skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; /* build migrate */ if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC); } #else static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k) { return -ENOPROTOOPT; } #endif #define XMSGSIZE(type) sizeof(struct type) static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info), [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire), [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire), [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire), [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush), [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0, [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), [XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), [XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report), [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32), [XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32), }; #undef XMSGSIZE static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = { [XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)}, [XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)}, [XFRMA_LASTUSED] = { .type = NLA_U64}, [XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)}, [XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) }, [XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) }, [XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) }, [XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) }, [XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) }, [XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) }, [XFRMA_REPLAY_THRESH] = { .type = NLA_U32 }, [XFRMA_ETIMER_THRESH] = { .type = NLA_U32 }, [XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) }, [XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) }, [XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)}, [XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) }, [XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) }, [XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) }, [XFRMA_TFCPAD] = { .type = NLA_U32 }, [XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) }, }; static struct xfrm_link { int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **); int (*dump)(struct sk_buff *, struct netlink_callback *); int (*done)(struct netlink_callback *); } xfrm_dispatch[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa }, [XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa, .dump = xfrm_dump_sa, .done = xfrm_dump_sa_done }, [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy }, [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy, .dump = xfrm_dump_policy, .done = xfrm_dump_policy_done }, [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi }, [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire }, [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire }, [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire}, [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa }, [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy }, [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae }, [XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae }, [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate }, [XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo }, [XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo }, }; static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct nlattr *attrs[XFRMA_MAX+1]; struct xfrm_link *link; int type, err; type = nlh->nlmsg_type; if (type > XFRM_MSG_MAX) return -EINVAL; type -= XFRM_MSG_BASE; link = &xfrm_dispatch[type]; /* All operations require privileges, even GET */ if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) || type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) && (nlh->nlmsg_flags & NLM_F_DUMP)) { if (link->dump == NULL) return -EINVAL; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, }; return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c); } } err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX, xfrma_policy); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } static void xfrm_netlink_rcv(struct sk_buff *skb) { mutex_lock(&xfrm_cfg_mutex); netlink_rcv_skb(skb, &xfrm_user_rcv_msg); mutex_unlock(&xfrm_cfg_mutex); } static inline size_t xfrm_expire_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_expire)) + nla_total_size(sizeof(struct xfrm_mark)); } static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c) { struct xfrm_user_expire *ue; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0); if (nlh == NULL) return -EMSGSIZE; ue = nlmsg_data(nlh); copy_to_user_state(x, &ue->state); ue->hard = (c->data.hard != 0) ? 1 : 0; err = xfrm_mark_put(skb, &x->mark); if (err) return err; return nlmsg_end(skb, nlh); } static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_expire(skb, x, c) < 0) { kfree_skb(skb); return -EMSGSIZE; } return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_aevent(skb, x, c) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC); } static int xfrm_notify_sa_flush(const struct km_event *c) { struct net *net = c->net; struct xfrm_usersa_flush *p; struct nlmsghdr *nlh; struct sk_buff *skb; int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush)); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0); if (nlh == NULL) { kfree_skb(skb); return -EMSGSIZE; } p = nlmsg_data(nlh); p->proto = c->data.proto; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); } static inline size_t xfrm_sa_len(struct xfrm_state *x) { size_t l = 0; if (x->aead) l += nla_total_size(aead_len(x->aead)); if (x->aalg) { l += nla_total_size(sizeof(struct xfrm_algo) + (x->aalg->alg_key_len + 7) / 8); l += nla_total_size(xfrm_alg_auth_len(x->aalg)); } if (x->ealg) l += nla_total_size(xfrm_alg_len(x->ealg)); if (x->calg) l += nla_total_size(sizeof(*x->calg)); if (x->encap) l += nla_total_size(sizeof(*x->encap)); if (x->tfcpad) l += nla_total_size(sizeof(x->tfcpad)); if (x->replay_esn) l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn)); if (x->security) l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) + x->security->ctx_len); if (x->coaddr) l += nla_total_size(sizeof(*x->coaddr)); /* Must count x->lastused as it may become non-zero behind our back. */ l += nla_total_size(sizeof(u64)); return l; } static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct xfrm_usersa_info *p; struct xfrm_usersa_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; int len = xfrm_sa_len(x); int headlen, err; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELSA) { len += nla_total_size(headlen); headlen = sizeof(*id); len += nla_total_size(sizeof(struct xfrm_mark)); } len += NLMSG_ALIGN(headlen); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; p = nlmsg_data(nlh); if (c->event == XFRM_MSG_DELSA) { struct nlattr *attr; id = nlmsg_data(nlh); memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr)); id->spi = x->id.spi; id->family = x->props.family; id->proto = x->id.proto; attr = nla_reserve(skb, XFRMA_SA, sizeof(*p)); err = -EMSGSIZE; if (attr == NULL) goto out_free_skb; p = nla_data(attr); } err = copy_to_user_state_extra(x, p, skb); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c) { switch (c->event) { case XFRM_MSG_EXPIRE: return xfrm_exp_state_notify(x, c); case XFRM_MSG_NEWAE: return xfrm_aevent_state_notify(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_UPDSA: case XFRM_MSG_NEWSA: return xfrm_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return xfrm_notify_sa_flush(c); default: printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n", c->event); break; } return 0; } static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x, struct xfrm_policy *xp) { return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire)) + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr) + nla_total_size(sizeof(struct xfrm_mark)) + nla_total_size(xfrm_user_sec_ctx_size(x->security)) + userpolicy_type_attrsize(); } static int build_acquire(struct sk_buff *skb, struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { __u32 seq = xfrm_get_acqseq(); struct xfrm_user_acquire *ua; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0); if (nlh == NULL) return -EMSGSIZE; ua = nlmsg_data(nlh); memcpy(&ua->id, &x->id, sizeof(ua->id)); memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr)); memcpy(&ua->sel, &x->sel, sizeof(ua->sel)); copy_to_user_policy(xp, &ua->policy, dir); ua->aalgos = xt->aalgos; ua->ealgos = xt->ealgos; ua->calgos = xt->calgos; ua->seq = x->km.seq = seq; err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_state_sec_ctx(x, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_acquire(skb, x, xt, xp, dir) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC); } /* User gives us xfrm_user_policy_info followed by an array of 0 * or more templates. */ static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt, u8 *data, int len, int *dir) { struct net *net = sock_net(sk); struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data; struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1); struct xfrm_policy *xp; int nr; switch (sk->sk_family) { case AF_INET: if (opt != IP_XFRM_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: if (opt != IPV6_XFRM_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(*p) || verify_newpolicy_info(p)) return NULL; nr = ((len - sizeof(*p)) / sizeof(*ut)); if (validate_tmpl(nr, ut, p->sel.family)) return NULL; if (p->dir > XFRM_POLICY_OUT) return NULL; xp = xfrm_policy_alloc(net, GFP_ATOMIC); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } copy_from_user_policy(xp, p); xp->type = XFRM_POLICY_TYPE_MAIN; copy_templates(xp, ut, nr); *dir = p->dir; return xp; } static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp) { return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire)) + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr) + nla_total_size(xfrm_user_sec_ctx_size(xp->security)) + nla_total_size(sizeof(struct xfrm_mark)) + userpolicy_type_attrsize(); } static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp, int dir, const struct km_event *c) { struct xfrm_user_polexpire *upe; int hard = c->data.hard; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0); if (nlh == NULL) return -EMSGSIZE; upe = nlmsg_data(nlh); copy_to_user_policy(xp, &upe->pol, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_sec_ctx(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } upe->hard = !!hard; return nlmsg_end(skb, nlh); } static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { struct net *net = xp_net(xp); struct sk_buff *skb; skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_polexpire(skb, xp, dir, c) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c) { int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr); struct net *net = xp_net(xp); struct xfrm_userpolicy_info *p; struct xfrm_userpolicy_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; int headlen, err; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELPOLICY) { len += nla_total_size(headlen); headlen = sizeof(*id); } len += userpolicy_type_attrsize(); len += nla_total_size(sizeof(struct xfrm_mark)); len += NLMSG_ALIGN(headlen); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; p = nlmsg_data(nlh); if (c->event == XFRM_MSG_DELPOLICY) { struct nlattr *attr; id = nlmsg_data(nlh); memset(id, 0, sizeof(*id)); id->dir = dir; if (c->data.byid) id->index = xp->index; else memcpy(&id->sel, &xp->selector, sizeof(id->sel)); attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p)); err = -EMSGSIZE; if (attr == NULL) goto out_free_skb; p = nla_data(attr); } copy_to_user_policy(xp, p, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_notify_policy_flush(const struct km_event *c) { struct net *net = c->net; struct nlmsghdr *nlh; struct sk_buff *skb; int err; skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; err = copy_to_user_policy_type(c->data.type, skb); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { switch (c->event) { case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: case XFRM_MSG_DELPOLICY: return xfrm_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: return xfrm_notify_policy_flush(c); case XFRM_MSG_POLEXPIRE: return xfrm_exp_policy_notify(xp, dir, c); default: printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n", c->event); } return 0; } static inline size_t xfrm_report_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_report)); } static int build_report(struct sk_buff *skb, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct xfrm_user_report *ur; struct nlmsghdr *nlh; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0); if (nlh == NULL) return -EMSGSIZE; ur = nlmsg_data(nlh); ur->proto = proto; memcpy(&ur->sel, sel, sizeof(ur->sel)); if (addr) { int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr); if (err) { nlmsg_cancel(skb, nlh); return err; } } return nlmsg_end(skb, nlh); } static int xfrm_send_report(struct net *net, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct sk_buff *skb; skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_report(skb, proto, sel, addr) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC); } static inline size_t xfrm_mapping_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping)); } static int build_mapping(struct sk_buff *skb, struct xfrm_state *x, xfrm_address_t *new_saddr, __be16 new_sport) { struct xfrm_user_mapping *um; struct nlmsghdr *nlh; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0); if (nlh == NULL) return -EMSGSIZE; um = nlmsg_data(nlh); memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr)); um->id.spi = x->id.spi; um->id.family = x->props.family; um->id.proto = x->id.proto; memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr)); memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr)); um->new_sport = new_sport; um->old_sport = x->encap->encap_sport; um->reqid = x->props.reqid; return nlmsg_end(skb, nlh); } static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport) { struct net *net = xs_net(x); struct sk_buff *skb; if (x->id.proto != IPPROTO_ESP) return -EINVAL; if (!x->encap) return -EINVAL; skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_mapping(skb, x, ipaddr, sport) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC); } static struct xfrm_mgr netlink_mgr = { .id = "netlink", .notify = xfrm_send_state_notify, .acquire = xfrm_send_acquire, .compile_policy = xfrm_compile_policy, .notify_policy = xfrm_send_policy_notify, .report = xfrm_send_report, .migrate = xfrm_send_migrate, .new_mapping = xfrm_send_mapping, }; static int __net_init xfrm_user_net_init(struct net *net) { struct sock *nlsk; struct netlink_kernel_cfg cfg = { .groups = XFRMNLGRP_MAX, .input = xfrm_netlink_rcv, }; nlsk = netlink_kernel_create(net, NETLINK_XFRM, THIS_MODULE, &cfg); if (nlsk == NULL) return -ENOMEM; net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */ rcu_assign_pointer(net->xfrm.nlsk, nlsk); return 0; } static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list) { struct net *net; list_for_each_entry(net, net_exit_list, exit_list) RCU_INIT_POINTER(net->xfrm.nlsk, NULL); synchronize_net(); list_for_each_entry(net, net_exit_list, exit_list) netlink_kernel_release(net->xfrm.nlsk_stash); } static struct pernet_operations xfrm_user_net_ops = { .init = xfrm_user_net_init, .exit_batch = xfrm_user_net_exit, }; static int __init xfrm_user_init(void) { int rv; printk(KERN_INFO "Initializing XFRM netlink socket\n"); rv = register_pernet_subsys(&xfrm_user_net_ops); if (rv < 0) return rv; rv = xfrm_register_km(&netlink_mgr); if (rv < 0) unregister_pernet_subsys(&xfrm_user_net_ops); return rv; } static void __exit xfrm_user_exit(void) { xfrm_unregister_km(&netlink_mgr); unregister_pernet_subsys(&xfrm_user_net_ops); } module_init(xfrm_user_init); module_exit(xfrm_user_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3826_0
crossvul-cpp_data_bad_3473_0
/* * taskstats.c - Export per-task statistics to userland * * Copyright (C) Shailabh Nagar, IBM Corp. 2006 * (C) Balbir Singh, IBM Corp. 2006 * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/kernel.h> #include <linux/taskstats_kern.h> #include <linux/tsacct_kern.h> #include <linux/delayacct.h> #include <linux/cpumask.h> #include <linux/percpu.h> #include <linux/slab.h> #include <linux/cgroupstats.h> #include <linux/cgroup.h> #include <linux/fs.h> #include <linux/file.h> #include <net/genetlink.h> #include <linux/atomic.h> /* * Maximum length of a cpumask that can be specified in * the TASKSTATS_CMD_ATTR_REGISTER/DEREGISTER_CPUMASK attribute */ #define TASKSTATS_CPUMASK_MAXLEN (100+6*NR_CPUS) static DEFINE_PER_CPU(__u32, taskstats_seqnum); static int family_registered; struct kmem_cache *taskstats_cache; static struct genl_family family = { .id = GENL_ID_GENERATE, .name = TASKSTATS_GENL_NAME, .version = TASKSTATS_GENL_VERSION, .maxattr = TASKSTATS_CMD_ATTR_MAX, }; static const struct nla_policy taskstats_cmd_get_policy[TASKSTATS_CMD_ATTR_MAX+1] = { [TASKSTATS_CMD_ATTR_PID] = { .type = NLA_U32 }, [TASKSTATS_CMD_ATTR_TGID] = { .type = NLA_U32 }, [TASKSTATS_CMD_ATTR_REGISTER_CPUMASK] = { .type = NLA_STRING }, [TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK] = { .type = NLA_STRING },}; static const struct nla_policy cgroupstats_cmd_get_policy[CGROUPSTATS_CMD_ATTR_MAX+1] = { [CGROUPSTATS_CMD_ATTR_FD] = { .type = NLA_U32 }, }; struct listener { struct list_head list; pid_t pid; char valid; }; struct listener_list { struct rw_semaphore sem; struct list_head list; }; static DEFINE_PER_CPU(struct listener_list, listener_array); enum actions { REGISTER, DEREGISTER, CPU_DONT_CARE }; static int prepare_reply(struct genl_info *info, u8 cmd, struct sk_buff **skbp, size_t size) { struct sk_buff *skb; void *reply; /* * If new attributes are added, please revisit this allocation */ skb = genlmsg_new(size, GFP_KERNEL); if (!skb) return -ENOMEM; if (!info) { int seq = this_cpu_inc_return(taskstats_seqnum) - 1; reply = genlmsg_put(skb, 0, seq, &family, 0, cmd); } else reply = genlmsg_put_reply(skb, info, &family, 0, cmd); if (reply == NULL) { nlmsg_free(skb); return -EINVAL; } *skbp = skb; return 0; } /* * Send taskstats data in @skb to listener with nl_pid @pid */ static int send_reply(struct sk_buff *skb, struct genl_info *info) { struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb)); void *reply = genlmsg_data(genlhdr); int rc; rc = genlmsg_end(skb, reply); if (rc < 0) { nlmsg_free(skb); return rc; } return genlmsg_reply(skb, info); } /* * Send taskstats data in @skb to listeners registered for @cpu's exit data */ static void send_cpu_listeners(struct sk_buff *skb, struct listener_list *listeners) { struct genlmsghdr *genlhdr = nlmsg_data(nlmsg_hdr(skb)); struct listener *s, *tmp; struct sk_buff *skb_next, *skb_cur = skb; void *reply = genlmsg_data(genlhdr); int rc, delcount = 0; rc = genlmsg_end(skb, reply); if (rc < 0) { nlmsg_free(skb); return; } rc = 0; down_read(&listeners->sem); list_for_each_entry(s, &listeners->list, list) { skb_next = NULL; if (!list_is_last(&s->list, &listeners->list)) { skb_next = skb_clone(skb_cur, GFP_KERNEL); if (!skb_next) break; } rc = genlmsg_unicast(&init_net, skb_cur, s->pid); if (rc == -ECONNREFUSED) { s->valid = 0; delcount++; } skb_cur = skb_next; } up_read(&listeners->sem); if (skb_cur) nlmsg_free(skb_cur); if (!delcount) return; /* Delete invalidated entries */ down_write(&listeners->sem); list_for_each_entry_safe(s, tmp, &listeners->list, list) { if (!s->valid) { list_del(&s->list); kfree(s); } } up_write(&listeners->sem); } static void fill_stats(struct task_struct *tsk, struct taskstats *stats) { memset(stats, 0, sizeof(*stats)); /* * Each accounting subsystem adds calls to its functions to * fill in relevant parts of struct taskstsats as follows * * per-task-foo(stats, tsk); */ delayacct_add_tsk(stats, tsk); /* fill in basic acct fields */ stats->version = TASKSTATS_VERSION; stats->nvcsw = tsk->nvcsw; stats->nivcsw = tsk->nivcsw; bacct_add_tsk(stats, tsk); /* fill in extended acct fields */ xacct_add_tsk(stats, tsk); } static int fill_stats_for_pid(pid_t pid, struct taskstats *stats) { struct task_struct *tsk; rcu_read_lock(); tsk = find_task_by_vpid(pid); if (tsk) get_task_struct(tsk); rcu_read_unlock(); if (!tsk) return -ESRCH; fill_stats(tsk, stats); put_task_struct(tsk); return 0; } static int fill_stats_for_tgid(pid_t tgid, struct taskstats *stats) { struct task_struct *tsk, *first; unsigned long flags; int rc = -ESRCH; /* * Add additional stats from live tasks except zombie thread group * leaders who are already counted with the dead tasks */ rcu_read_lock(); first = find_task_by_vpid(tgid); if (!first || !lock_task_sighand(first, &flags)) goto out; if (first->signal->stats) memcpy(stats, first->signal->stats, sizeof(*stats)); else memset(stats, 0, sizeof(*stats)); tsk = first; do { if (tsk->exit_state) continue; /* * Accounting subsystem can call its functions here to * fill in relevant parts of struct taskstsats as follows * * per-task-foo(stats, tsk); */ delayacct_add_tsk(stats, tsk); stats->nvcsw += tsk->nvcsw; stats->nivcsw += tsk->nivcsw; } while_each_thread(first, tsk); unlock_task_sighand(first, &flags); rc = 0; out: rcu_read_unlock(); stats->version = TASKSTATS_VERSION; /* * Accounting subsystems can also add calls here to modify * fields of taskstats. */ return rc; } static void fill_tgid_exit(struct task_struct *tsk) { unsigned long flags; spin_lock_irqsave(&tsk->sighand->siglock, flags); if (!tsk->signal->stats) goto ret; /* * Each accounting subsystem calls its functions here to * accumalate its per-task stats for tsk, into the per-tgid structure * * per-task-foo(tsk->signal->stats, tsk); */ delayacct_add_tsk(tsk->signal->stats, tsk); ret: spin_unlock_irqrestore(&tsk->sighand->siglock, flags); return; } static int add_del_listener(pid_t pid, const struct cpumask *mask, int isadd) { struct listener_list *listeners; struct listener *s, *tmp, *s2; unsigned int cpu; if (!cpumask_subset(mask, cpu_possible_mask)) return -EINVAL; if (isadd == REGISTER) { for_each_cpu(cpu, mask) { s = kmalloc_node(sizeof(struct listener), GFP_KERNEL, cpu_to_node(cpu)); if (!s) goto cleanup; s->pid = pid; s->valid = 1; listeners = &per_cpu(listener_array, cpu); down_write(&listeners->sem); list_for_each_entry(s2, &listeners->list, list) { if (s2->pid == pid && s2->valid) goto exists; } list_add(&s->list, &listeners->list); s = NULL; exists: up_write(&listeners->sem); kfree(s); /* nop if NULL */ } return 0; } /* Deregister or cleanup */ cleanup: for_each_cpu(cpu, mask) { listeners = &per_cpu(listener_array, cpu); down_write(&listeners->sem); list_for_each_entry_safe(s, tmp, &listeners->list, list) { if (s->pid == pid) { list_del(&s->list); kfree(s); break; } } up_write(&listeners->sem); } return 0; } static int parse(struct nlattr *na, struct cpumask *mask) { char *data; int len; int ret; if (na == NULL) return 1; len = nla_len(na); if (len > TASKSTATS_CPUMASK_MAXLEN) return -E2BIG; if (len < 1) return -EINVAL; data = kmalloc(len, GFP_KERNEL); if (!data) return -ENOMEM; nla_strlcpy(data, na, len); ret = cpulist_parse(data, mask); kfree(data); return ret; } #if defined(CONFIG_64BIT) && !defined(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) #define TASKSTATS_NEEDS_PADDING 1 #endif static struct taskstats *mk_reply(struct sk_buff *skb, int type, u32 pid) { struct nlattr *na, *ret; int aggr; aggr = (type == TASKSTATS_TYPE_PID) ? TASKSTATS_TYPE_AGGR_PID : TASKSTATS_TYPE_AGGR_TGID; /* * The taskstats structure is internally aligned on 8 byte * boundaries but the layout of the aggregrate reply, with * two NLA headers and the pid (each 4 bytes), actually * force the entire structure to be unaligned. This causes * the kernel to issue unaligned access warnings on some * architectures like ia64. Unfortunately, some software out there * doesn't properly unroll the NLA packet and assumes that the start * of the taskstats structure will always be 20 bytes from the start * of the netlink payload. Aligning the start of the taskstats * structure breaks this software, which we don't want. So, for now * the alignment only happens on architectures that require it * and those users will have to update to fixed versions of those * packages. Space is reserved in the packet only when needed. * This ifdef should be removed in several years e.g. 2012 once * we can be confident that fixed versions are installed on most * systems. We add the padding before the aggregate since the * aggregate is already a defined type. */ #ifdef TASKSTATS_NEEDS_PADDING if (nla_put(skb, TASKSTATS_TYPE_NULL, 0, NULL) < 0) goto err; #endif na = nla_nest_start(skb, aggr); if (!na) goto err; if (nla_put(skb, type, sizeof(pid), &pid) < 0) goto err; ret = nla_reserve(skb, TASKSTATS_TYPE_STATS, sizeof(struct taskstats)); if (!ret) goto err; nla_nest_end(skb, na); return nla_data(ret); err: return NULL; } static int cgroupstats_user_cmd(struct sk_buff *skb, struct genl_info *info) { int rc = 0; struct sk_buff *rep_skb; struct cgroupstats *stats; struct nlattr *na; size_t size; u32 fd; struct file *file; int fput_needed; na = info->attrs[CGROUPSTATS_CMD_ATTR_FD]; if (!na) return -EINVAL; fd = nla_get_u32(info->attrs[CGROUPSTATS_CMD_ATTR_FD]); file = fget_light(fd, &fput_needed); if (!file) return 0; size = nla_total_size(sizeof(struct cgroupstats)); rc = prepare_reply(info, CGROUPSTATS_CMD_NEW, &rep_skb, size); if (rc < 0) goto err; na = nla_reserve(rep_skb, CGROUPSTATS_TYPE_CGROUP_STATS, sizeof(struct cgroupstats)); stats = nla_data(na); memset(stats, 0, sizeof(*stats)); rc = cgroupstats_build(stats, file->f_dentry); if (rc < 0) { nlmsg_free(rep_skb); goto err; } rc = send_reply(rep_skb, info); err: fput_light(file, fput_needed); return rc; } static int cmd_attr_register_cpumask(struct genl_info *info) { cpumask_var_t mask; int rc; if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; rc = parse(info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK], mask); if (rc < 0) goto out; rc = add_del_listener(info->snd_pid, mask, REGISTER); out: free_cpumask_var(mask); return rc; } static int cmd_attr_deregister_cpumask(struct genl_info *info) { cpumask_var_t mask; int rc; if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; rc = parse(info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK], mask); if (rc < 0) goto out; rc = add_del_listener(info->snd_pid, mask, DEREGISTER); out: free_cpumask_var(mask); return rc; } static size_t taskstats_packet_size(void) { size_t size; size = nla_total_size(sizeof(u32)) + nla_total_size(sizeof(struct taskstats)) + nla_total_size(0); #ifdef TASKSTATS_NEEDS_PADDING size += nla_total_size(0); /* Padding for alignment */ #endif return size; } static int cmd_attr_pid(struct genl_info *info) { struct taskstats *stats; struct sk_buff *rep_skb; size_t size; u32 pid; int rc; size = taskstats_packet_size(); rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size); if (rc < 0) return rc; rc = -EINVAL; pid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_PID]); stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID, pid); if (!stats) goto err; rc = fill_stats_for_pid(pid, stats); if (rc < 0) goto err; return send_reply(rep_skb, info); err: nlmsg_free(rep_skb); return rc; } static int cmd_attr_tgid(struct genl_info *info) { struct taskstats *stats; struct sk_buff *rep_skb; size_t size; u32 tgid; int rc; size = taskstats_packet_size(); rc = prepare_reply(info, TASKSTATS_CMD_NEW, &rep_skb, size); if (rc < 0) return rc; rc = -EINVAL; tgid = nla_get_u32(info->attrs[TASKSTATS_CMD_ATTR_TGID]); stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID, tgid); if (!stats) goto err; rc = fill_stats_for_tgid(tgid, stats); if (rc < 0) goto err; return send_reply(rep_skb, info); err: nlmsg_free(rep_skb); return rc; } static int taskstats_user_cmd(struct sk_buff *skb, struct genl_info *info) { if (info->attrs[TASKSTATS_CMD_ATTR_REGISTER_CPUMASK]) return cmd_attr_register_cpumask(info); else if (info->attrs[TASKSTATS_CMD_ATTR_DEREGISTER_CPUMASK]) return cmd_attr_deregister_cpumask(info); else if (info->attrs[TASKSTATS_CMD_ATTR_PID]) return cmd_attr_pid(info); else if (info->attrs[TASKSTATS_CMD_ATTR_TGID]) return cmd_attr_tgid(info); else return -EINVAL; } static struct taskstats *taskstats_tgid_alloc(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; struct taskstats *stats; if (sig->stats || thread_group_empty(tsk)) goto ret; /* No problem if kmem_cache_zalloc() fails */ stats = kmem_cache_zalloc(taskstats_cache, GFP_KERNEL); spin_lock_irq(&tsk->sighand->siglock); if (!sig->stats) { sig->stats = stats; stats = NULL; } spin_unlock_irq(&tsk->sighand->siglock); if (stats) kmem_cache_free(taskstats_cache, stats); ret: return sig->stats; } /* Send pid data out on exit */ void taskstats_exit(struct task_struct *tsk, int group_dead) { int rc; struct listener_list *listeners; struct taskstats *stats; struct sk_buff *rep_skb; size_t size; int is_thread_group; if (!family_registered) return; /* * Size includes space for nested attributes */ size = taskstats_packet_size(); is_thread_group = !!taskstats_tgid_alloc(tsk); if (is_thread_group) { /* PID + STATS + TGID + STATS */ size = 2 * size; /* fill the tsk->signal->stats structure */ fill_tgid_exit(tsk); } listeners = __this_cpu_ptr(&listener_array); if (list_empty(&listeners->list)) return; rc = prepare_reply(NULL, TASKSTATS_CMD_NEW, &rep_skb, size); if (rc < 0) return; stats = mk_reply(rep_skb, TASKSTATS_TYPE_PID, tsk->pid); if (!stats) goto err; fill_stats(tsk, stats); /* * Doesn't matter if tsk is the leader or the last group member leaving */ if (!is_thread_group || !group_dead) goto send; stats = mk_reply(rep_skb, TASKSTATS_TYPE_TGID, tsk->tgid); if (!stats) goto err; memcpy(stats, tsk->signal->stats, sizeof(*stats)); send: send_cpu_listeners(rep_skb, listeners); return; err: nlmsg_free(rep_skb); } static struct genl_ops taskstats_ops = { .cmd = TASKSTATS_CMD_GET, .doit = taskstats_user_cmd, .policy = taskstats_cmd_get_policy, }; static struct genl_ops cgroupstats_ops = { .cmd = CGROUPSTATS_CMD_GET, .doit = cgroupstats_user_cmd, .policy = cgroupstats_cmd_get_policy, }; /* Needed early in initialization */ void __init taskstats_init_early(void) { unsigned int i; taskstats_cache = KMEM_CACHE(taskstats, SLAB_PANIC); for_each_possible_cpu(i) { INIT_LIST_HEAD(&(per_cpu(listener_array, i).list)); init_rwsem(&(per_cpu(listener_array, i).sem)); } } static int __init taskstats_init(void) { int rc; rc = genl_register_family(&family); if (rc) return rc; rc = genl_register_ops(&family, &taskstats_ops); if (rc < 0) goto err; rc = genl_register_ops(&family, &cgroupstats_ops); if (rc < 0) goto err_cgroup_ops; family_registered = 1; pr_info("registered taskstats version %d\n", TASKSTATS_GENL_VERSION); return 0; err_cgroup_ops: genl_unregister_ops(&family, &taskstats_ops); err: genl_unregister_family(&family); return rc; } /* * late initcall ensures initialization of statistics collection * mechanisms precedes initialization of the taskstats interface */ late_initcall(taskstats_init);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3473_0
crossvul-cpp_data_good_5569_0
/* HIDP implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2003-2004 Marcel Holtmann <marcel@holtmann.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ #include <linux/module.h> #include <linux/file.h> #include <linux/kthread.h> #include <linux/hidraw.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include "hidp.h" #define VERSION "1.2" static DECLARE_RWSEM(hidp_session_sem); static LIST_HEAD(hidp_session_list); static unsigned char hidp_keycode[256] = { 0, 0, 0, 0, 30, 48, 46, 32, 18, 33, 34, 35, 23, 36, 37, 38, 50, 49, 24, 25, 16, 19, 31, 20, 22, 47, 17, 45, 21, 44, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 28, 1, 14, 15, 57, 12, 13, 26, 27, 43, 43, 39, 40, 41, 51, 52, 53, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 87, 88, 99, 70, 119, 110, 102, 104, 111, 107, 109, 106, 105, 108, 103, 69, 98, 55, 74, 78, 96, 79, 80, 81, 75, 76, 77, 71, 72, 73, 82, 83, 86, 127, 116, 117, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 134, 138, 130, 132, 128, 129, 131, 137, 133, 135, 136, 113, 115, 114, 0, 0, 0, 121, 0, 89, 93, 124, 92, 94, 95, 0, 0, 0, 122, 123, 90, 91, 85, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 29, 42, 56, 125, 97, 54, 100, 126, 164, 166, 165, 163, 161, 115, 114, 113, 150, 158, 159, 128, 136, 177, 178, 176, 142, 152, 173, 140 }; static unsigned char hidp_mkeyspat[] = { 0x01, 0x01, 0x01, 0x01, 0x01, 0x01 }; static struct hidp_session *__hidp_get_session(bdaddr_t *bdaddr) { struct hidp_session *session; BT_DBG(""); list_for_each_entry(session, &hidp_session_list, list) { if (!bacmp(bdaddr, &session->bdaddr)) return session; } return NULL; } static void __hidp_link_session(struct hidp_session *session) { list_add(&session->list, &hidp_session_list); } static void __hidp_unlink_session(struct hidp_session *session) { hci_conn_put_device(session->conn); list_del(&session->list); } static void __hidp_copy_session(struct hidp_session *session, struct hidp_conninfo *ci) { memset(ci, 0, sizeof(*ci)); bacpy(&ci->bdaddr, &session->bdaddr); ci->flags = session->flags; ci->state = session->state; ci->vendor = 0x0000; ci->product = 0x0000; ci->version = 0x0000; if (session->input) { ci->vendor = session->input->id.vendor; ci->product = session->input->id.product; ci->version = session->input->id.version; if (session->input->name) strncpy(ci->name, session->input->name, 128); else strncpy(ci->name, "HID Boot Device", 128); } if (session->hid) { ci->vendor = session->hid->vendor; ci->product = session->hid->product; ci->version = session->hid->version; strncpy(ci->name, session->hid->name, 128); } } static int hidp_queue_event(struct hidp_session *session, struct input_dev *dev, unsigned int type, unsigned int code, int value) { unsigned char newleds; struct sk_buff *skb; BT_DBG("session %p type %d code %d value %d", session, type, code, value); if (type != EV_LED) return -1; newleds = (!!test_bit(LED_KANA, dev->led) << 3) | (!!test_bit(LED_COMPOSE, dev->led) << 3) | (!!test_bit(LED_SCROLLL, dev->led) << 2) | (!!test_bit(LED_CAPSL, dev->led) << 1) | (!!test_bit(LED_NUML, dev->led)); if (session->leds == newleds) return 0; session->leds = newleds; skb = alloc_skb(3, GFP_ATOMIC); if (!skb) { BT_ERR("Can't allocate memory for new frame"); return -ENOMEM; } *skb_put(skb, 1) = HIDP_TRANS_DATA | HIDP_DATA_RTYPE_OUPUT; *skb_put(skb, 1) = 0x01; *skb_put(skb, 1) = newleds; skb_queue_tail(&session->intr_transmit, skb); hidp_schedule(session); return 0; } static int hidp_hidinput_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { struct hid_device *hid = input_get_drvdata(dev); struct hidp_session *session = hid->driver_data; return hidp_queue_event(session, dev, type, code, value); } static int hidp_input_event(struct input_dev *dev, unsigned int type, unsigned int code, int value) { struct hidp_session *session = input_get_drvdata(dev); return hidp_queue_event(session, dev, type, code, value); } static void hidp_input_report(struct hidp_session *session, struct sk_buff *skb) { struct input_dev *dev = session->input; unsigned char *keys = session->keys; unsigned char *udata = skb->data + 1; signed char *sdata = skb->data + 1; int i, size = skb->len - 1; switch (skb->data[0]) { case 0x01: /* Keyboard report */ for (i = 0; i < 8; i++) input_report_key(dev, hidp_keycode[i + 224], (udata[0] >> i) & 1); /* If all the key codes have been set to 0x01, it means * too many keys were pressed at the same time. */ if (!memcmp(udata + 2, hidp_mkeyspat, 6)) break; for (i = 2; i < 8; i++) { if (keys[i] > 3 && memscan(udata + 2, keys[i], 6) == udata + 8) { if (hidp_keycode[keys[i]]) input_report_key(dev, hidp_keycode[keys[i]], 0); else BT_ERR("Unknown key (scancode %#x) released.", keys[i]); } if (udata[i] > 3 && memscan(keys + 2, udata[i], 6) == keys + 8) { if (hidp_keycode[udata[i]]) input_report_key(dev, hidp_keycode[udata[i]], 1); else BT_ERR("Unknown key (scancode %#x) pressed.", udata[i]); } } memcpy(keys, udata, 8); break; case 0x02: /* Mouse report */ input_report_key(dev, BTN_LEFT, sdata[0] & 0x01); input_report_key(dev, BTN_RIGHT, sdata[0] & 0x02); input_report_key(dev, BTN_MIDDLE, sdata[0] & 0x04); input_report_key(dev, BTN_SIDE, sdata[0] & 0x08); input_report_key(dev, BTN_EXTRA, sdata[0] & 0x10); input_report_rel(dev, REL_X, sdata[1]); input_report_rel(dev, REL_Y, sdata[2]); if (size > 3) input_report_rel(dev, REL_WHEEL, sdata[3]); break; } input_sync(dev); } static int __hidp_send_ctrl_message(struct hidp_session *session, unsigned char hdr, unsigned char *data, int size) { struct sk_buff *skb; BT_DBG("session %p data %p size %d", session, data, size); if (atomic_read(&session->terminate)) return -EIO; skb = alloc_skb(size + 1, GFP_ATOMIC); if (!skb) { BT_ERR("Can't allocate memory for new frame"); return -ENOMEM; } *skb_put(skb, 1) = hdr; if (data && size > 0) memcpy(skb_put(skb, size), data, size); skb_queue_tail(&session->ctrl_transmit, skb); return 0; } static int hidp_send_ctrl_message(struct hidp_session *session, unsigned char hdr, unsigned char *data, int size) { int err; err = __hidp_send_ctrl_message(session, hdr, data, size); hidp_schedule(session); return err; } static int hidp_queue_report(struct hidp_session *session, unsigned char *data, int size) { struct sk_buff *skb; BT_DBG("session %p hid %p data %p size %d", session, session->hid, data, size); skb = alloc_skb(size + 1, GFP_ATOMIC); if (!skb) { BT_ERR("Can't allocate memory for new frame"); return -ENOMEM; } *skb_put(skb, 1) = 0xa2; if (size > 0) memcpy(skb_put(skb, size), data, size); skb_queue_tail(&session->intr_transmit, skb); hidp_schedule(session); return 0; } static int hidp_send_report(struct hidp_session *session, struct hid_report *report) { unsigned char buf[32]; int rsize; rsize = ((report->size - 1) >> 3) + 1 + (report->id > 0); if (rsize > sizeof(buf)) return -EIO; hid_output_report(report, buf); return hidp_queue_report(session, buf, rsize); } static int hidp_get_raw_report(struct hid_device *hid, unsigned char report_number, unsigned char *data, size_t count, unsigned char report_type) { struct hidp_session *session = hid->driver_data; struct sk_buff *skb; size_t len; int numbered_reports = hid->report_enum[report_type].numbered; int ret; switch (report_type) { case HID_FEATURE_REPORT: report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_FEATURE; break; case HID_INPUT_REPORT: report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_INPUT; break; case HID_OUTPUT_REPORT: report_type = HIDP_TRANS_GET_REPORT | HIDP_DATA_RTYPE_OUPUT; break; default: return -EINVAL; } if (mutex_lock_interruptible(&session->report_mutex)) return -ERESTARTSYS; /* Set up our wait, and send the report request to the device. */ session->waiting_report_type = report_type & HIDP_DATA_RTYPE_MASK; session->waiting_report_number = numbered_reports ? report_number : -1; set_bit(HIDP_WAITING_FOR_RETURN, &session->flags); data[0] = report_number; ret = hidp_send_ctrl_message(hid->driver_data, report_type, data, 1); if (ret) goto err; /* Wait for the return of the report. The returned report gets put in session->report_return. */ while (test_bit(HIDP_WAITING_FOR_RETURN, &session->flags)) { int res; res = wait_event_interruptible_timeout(session->report_queue, !test_bit(HIDP_WAITING_FOR_RETURN, &session->flags), 5*HZ); if (res == 0) { /* timeout */ ret = -EIO; goto err; } if (res < 0) { /* signal */ ret = -ERESTARTSYS; goto err; } } skb = session->report_return; if (skb) { len = skb->len < count ? skb->len : count; memcpy(data, skb->data, len); kfree_skb(skb); session->report_return = NULL; } else { /* Device returned a HANDSHAKE, indicating protocol error. */ len = -EIO; } clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags); mutex_unlock(&session->report_mutex); return len; err: clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags); mutex_unlock(&session->report_mutex); return ret; } static int hidp_output_raw_report(struct hid_device *hid, unsigned char *data, size_t count, unsigned char report_type) { struct hidp_session *session = hid->driver_data; int ret; switch (report_type) { case HID_FEATURE_REPORT: report_type = HIDP_TRANS_SET_REPORT | HIDP_DATA_RTYPE_FEATURE; break; case HID_OUTPUT_REPORT: report_type = HIDP_TRANS_SET_REPORT | HIDP_DATA_RTYPE_OUPUT; break; default: return -EINVAL; } if (mutex_lock_interruptible(&session->report_mutex)) return -ERESTARTSYS; /* Set up our wait, and send the report request to the device. */ set_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags); ret = hidp_send_ctrl_message(hid->driver_data, report_type, data, count); if (ret) goto err; /* Wait for the ACK from the device. */ while (test_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags)) { int res; res = wait_event_interruptible_timeout(session->report_queue, !test_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags), 10*HZ); if (res == 0) { /* timeout */ ret = -EIO; goto err; } if (res < 0) { /* signal */ ret = -ERESTARTSYS; goto err; } } if (!session->output_report_success) { ret = -EIO; goto err; } ret = count; err: clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags); mutex_unlock(&session->report_mutex); return ret; } static void hidp_idle_timeout(unsigned long arg) { struct hidp_session *session = (struct hidp_session *) arg; atomic_inc(&session->terminate); wake_up_process(session->task); } static void hidp_set_timer(struct hidp_session *session) { if (session->idle_to > 0) mod_timer(&session->timer, jiffies + HZ * session->idle_to); } static void hidp_del_timer(struct hidp_session *session) { if (session->idle_to > 0) del_timer(&session->timer); } static void hidp_process_handshake(struct hidp_session *session, unsigned char param) { BT_DBG("session %p param 0x%02x", session, param); session->output_report_success = 0; /* default condition */ switch (param) { case HIDP_HSHK_SUCCESSFUL: /* FIXME: Call into SET_ GET_ handlers here */ session->output_report_success = 1; break; case HIDP_HSHK_NOT_READY: case HIDP_HSHK_ERR_INVALID_REPORT_ID: case HIDP_HSHK_ERR_UNSUPPORTED_REQUEST: case HIDP_HSHK_ERR_INVALID_PARAMETER: if (test_and_clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags)) wake_up_interruptible(&session->report_queue); /* FIXME: Call into SET_ GET_ handlers here */ break; case HIDP_HSHK_ERR_UNKNOWN: break; case HIDP_HSHK_ERR_FATAL: /* Device requests a reboot, as this is the only way this error * can be recovered. */ __hidp_send_ctrl_message(session, HIDP_TRANS_HID_CONTROL | HIDP_CTRL_SOFT_RESET, NULL, 0); break; default: __hidp_send_ctrl_message(session, HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_INVALID_PARAMETER, NULL, 0); break; } /* Wake up the waiting thread. */ if (test_and_clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags)) wake_up_interruptible(&session->report_queue); } static void hidp_process_hid_control(struct hidp_session *session, unsigned char param) { BT_DBG("session %p param 0x%02x", session, param); if (param == HIDP_CTRL_VIRTUAL_CABLE_UNPLUG) { /* Flush the transmit queues */ skb_queue_purge(&session->ctrl_transmit); skb_queue_purge(&session->intr_transmit); atomic_inc(&session->terminate); wake_up_process(current); } } /* Returns true if the passed-in skb should be freed by the caller. */ static int hidp_process_data(struct hidp_session *session, struct sk_buff *skb, unsigned char param) { int done_with_skb = 1; BT_DBG("session %p skb %p len %d param 0x%02x", session, skb, skb->len, param); switch (param) { case HIDP_DATA_RTYPE_INPUT: hidp_set_timer(session); if (session->input) hidp_input_report(session, skb); if (session->hid) hid_input_report(session->hid, HID_INPUT_REPORT, skb->data, skb->len, 0); break; case HIDP_DATA_RTYPE_OTHER: case HIDP_DATA_RTYPE_OUPUT: case HIDP_DATA_RTYPE_FEATURE: break; default: __hidp_send_ctrl_message(session, HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_INVALID_PARAMETER, NULL, 0); } if (test_bit(HIDP_WAITING_FOR_RETURN, &session->flags) && param == session->waiting_report_type) { if (session->waiting_report_number < 0 || session->waiting_report_number == skb->data[0]) { /* hidp_get_raw_report() is waiting on this report. */ session->report_return = skb; done_with_skb = 0; clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags); wake_up_interruptible(&session->report_queue); } } return done_with_skb; } static void hidp_recv_ctrl_frame(struct hidp_session *session, struct sk_buff *skb) { unsigned char hdr, type, param; int free_skb = 1; BT_DBG("session %p skb %p len %d", session, skb, skb->len); hdr = skb->data[0]; skb_pull(skb, 1); type = hdr & HIDP_HEADER_TRANS_MASK; param = hdr & HIDP_HEADER_PARAM_MASK; switch (type) { case HIDP_TRANS_HANDSHAKE: hidp_process_handshake(session, param); break; case HIDP_TRANS_HID_CONTROL: hidp_process_hid_control(session, param); break; case HIDP_TRANS_DATA: free_skb = hidp_process_data(session, skb, param); break; default: __hidp_send_ctrl_message(session, HIDP_TRANS_HANDSHAKE | HIDP_HSHK_ERR_UNSUPPORTED_REQUEST, NULL, 0); break; } if (free_skb) kfree_skb(skb); } static void hidp_recv_intr_frame(struct hidp_session *session, struct sk_buff *skb) { unsigned char hdr; BT_DBG("session %p skb %p len %d", session, skb, skb->len); hdr = skb->data[0]; skb_pull(skb, 1); if (hdr == (HIDP_TRANS_DATA | HIDP_DATA_RTYPE_INPUT)) { hidp_set_timer(session); if (session->input) hidp_input_report(session, skb); if (session->hid) { hid_input_report(session->hid, HID_INPUT_REPORT, skb->data, skb->len, 1); BT_DBG("report len %d", skb->len); } } else { BT_DBG("Unsupported protocol header 0x%02x", hdr); } kfree_skb(skb); } static int hidp_send_frame(struct socket *sock, unsigned char *data, int len) { struct kvec iv = { data, len }; struct msghdr msg; BT_DBG("sock %p data %p len %d", sock, data, len); if (!len) return 0; memset(&msg, 0, sizeof(msg)); return kernel_sendmsg(sock, &msg, &iv, 1, len); } static void hidp_process_intr_transmit(struct hidp_session *session) { struct sk_buff *skb; BT_DBG("session %p", session); while ((skb = skb_dequeue(&session->intr_transmit))) { if (hidp_send_frame(session->intr_sock, skb->data, skb->len) < 0) { skb_queue_head(&session->intr_transmit, skb); break; } hidp_set_timer(session); kfree_skb(skb); } } static void hidp_process_ctrl_transmit(struct hidp_session *session) { struct sk_buff *skb; BT_DBG("session %p", session); while ((skb = skb_dequeue(&session->ctrl_transmit))) { if (hidp_send_frame(session->ctrl_sock, skb->data, skb->len) < 0) { skb_queue_head(&session->ctrl_transmit, skb); break; } hidp_set_timer(session); kfree_skb(skb); } } static int hidp_session(void *arg) { struct hidp_session *session = arg; struct sock *ctrl_sk = session->ctrl_sock->sk; struct sock *intr_sk = session->intr_sock->sk; struct sk_buff *skb; wait_queue_t ctrl_wait, intr_wait; BT_DBG("session %p", session); __module_get(THIS_MODULE); set_user_nice(current, -15); init_waitqueue_entry(&ctrl_wait, current); init_waitqueue_entry(&intr_wait, current); add_wait_queue(sk_sleep(ctrl_sk), &ctrl_wait); add_wait_queue(sk_sleep(intr_sk), &intr_wait); session->waiting_for_startup = 0; wake_up_interruptible(&session->startup_queue); set_current_state(TASK_INTERRUPTIBLE); while (!atomic_read(&session->terminate)) { if (ctrl_sk->sk_state != BT_CONNECTED || intr_sk->sk_state != BT_CONNECTED) break; while ((skb = skb_dequeue(&intr_sk->sk_receive_queue))) { skb_orphan(skb); if (!skb_linearize(skb)) hidp_recv_intr_frame(session, skb); else kfree_skb(skb); } hidp_process_intr_transmit(session); while ((skb = skb_dequeue(&ctrl_sk->sk_receive_queue))) { skb_orphan(skb); if (!skb_linearize(skb)) hidp_recv_ctrl_frame(session, skb); else kfree_skb(skb); } hidp_process_ctrl_transmit(session); schedule(); set_current_state(TASK_INTERRUPTIBLE); } set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(intr_sk), &intr_wait); remove_wait_queue(sk_sleep(ctrl_sk), &ctrl_wait); clear_bit(HIDP_WAITING_FOR_SEND_ACK, &session->flags); clear_bit(HIDP_WAITING_FOR_RETURN, &session->flags); wake_up_interruptible(&session->report_queue); down_write(&hidp_session_sem); hidp_del_timer(session); if (session->input) { input_unregister_device(session->input); session->input = NULL; } if (session->hid) { hid_destroy_device(session->hid); session->hid = NULL; } /* Wakeup user-space polling for socket errors */ session->intr_sock->sk->sk_err = EUNATCH; session->ctrl_sock->sk->sk_err = EUNATCH; hidp_schedule(session); fput(session->intr_sock->file); wait_event_timeout(*(sk_sleep(ctrl_sk)), (ctrl_sk->sk_state == BT_CLOSED), msecs_to_jiffies(500)); fput(session->ctrl_sock->file); __hidp_unlink_session(session); up_write(&hidp_session_sem); kfree(session->rd_data); kfree(session); module_put_and_exit(0); return 0; } static struct hci_conn *hidp_get_connection(struct hidp_session *session) { bdaddr_t *src = &bt_sk(session->ctrl_sock->sk)->src; bdaddr_t *dst = &bt_sk(session->ctrl_sock->sk)->dst; struct hci_conn *conn; struct hci_dev *hdev; hdev = hci_get_route(dst, src); if (!hdev) return NULL; hci_dev_lock(hdev); conn = hci_conn_hash_lookup_ba(hdev, ACL_LINK, dst); if (conn) hci_conn_hold_device(conn); hci_dev_unlock(hdev); hci_dev_put(hdev); return conn; } static int hidp_setup_input(struct hidp_session *session, struct hidp_connadd_req *req) { struct input_dev *input; int i; input = input_allocate_device(); if (!input) return -ENOMEM; session->input = input; input_set_drvdata(input, session); input->name = "Bluetooth HID Boot Protocol Device"; input->id.bustype = BUS_BLUETOOTH; input->id.vendor = req->vendor; input->id.product = req->product; input->id.version = req->version; if (req->subclass & 0x40) { set_bit(EV_KEY, input->evbit); set_bit(EV_LED, input->evbit); set_bit(EV_REP, input->evbit); set_bit(LED_NUML, input->ledbit); set_bit(LED_CAPSL, input->ledbit); set_bit(LED_SCROLLL, input->ledbit); set_bit(LED_COMPOSE, input->ledbit); set_bit(LED_KANA, input->ledbit); for (i = 0; i < sizeof(hidp_keycode); i++) set_bit(hidp_keycode[i], input->keybit); clear_bit(0, input->keybit); } if (req->subclass & 0x80) { input->evbit[0] = BIT_MASK(EV_KEY) | BIT_MASK(EV_REL); input->keybit[BIT_WORD(BTN_MOUSE)] = BIT_MASK(BTN_LEFT) | BIT_MASK(BTN_RIGHT) | BIT_MASK(BTN_MIDDLE); input->relbit[0] = BIT_MASK(REL_X) | BIT_MASK(REL_Y); input->keybit[BIT_WORD(BTN_MOUSE)] |= BIT_MASK(BTN_SIDE) | BIT_MASK(BTN_EXTRA); input->relbit[0] |= BIT_MASK(REL_WHEEL); } input->dev.parent = &session->conn->dev; input->event = hidp_input_event; return 0; } static int hidp_open(struct hid_device *hid) { return 0; } static void hidp_close(struct hid_device *hid) { } static int hidp_parse(struct hid_device *hid) { struct hidp_session *session = hid->driver_data; return hid_parse_report(session->hid, session->rd_data, session->rd_size); } static int hidp_start(struct hid_device *hid) { struct hidp_session *session = hid->driver_data; struct hid_report *report; if (hid->quirks & HID_QUIRK_NO_INIT_REPORTS) return 0; list_for_each_entry(report, &hid->report_enum[HID_INPUT_REPORT]. report_list, list) hidp_send_report(session, report); list_for_each_entry(report, &hid->report_enum[HID_FEATURE_REPORT]. report_list, list) hidp_send_report(session, report); return 0; } static void hidp_stop(struct hid_device *hid) { struct hidp_session *session = hid->driver_data; skb_queue_purge(&session->ctrl_transmit); skb_queue_purge(&session->intr_transmit); hid->claimed = 0; } static struct hid_ll_driver hidp_hid_driver = { .parse = hidp_parse, .start = hidp_start, .stop = hidp_stop, .open = hidp_open, .close = hidp_close, .hidinput_input_event = hidp_hidinput_event, }; /* This function sets up the hid device. It does not add it to the HID system. That is done in hidp_add_connection(). */ static int hidp_setup_hid(struct hidp_session *session, struct hidp_connadd_req *req) { struct hid_device *hid; int err; session->rd_data = kzalloc(req->rd_size, GFP_KERNEL); if (!session->rd_data) return -ENOMEM; if (copy_from_user(session->rd_data, req->rd_data, req->rd_size)) { err = -EFAULT; goto fault; } session->rd_size = req->rd_size; hid = hid_allocate_device(); if (IS_ERR(hid)) { err = PTR_ERR(hid); goto fault; } session->hid = hid; hid->driver_data = session; hid->bus = BUS_BLUETOOTH; hid->vendor = req->vendor; hid->product = req->product; hid->version = req->version; hid->country = req->country; strncpy(hid->name, req->name, sizeof(req->name) - 1); snprintf(hid->phys, sizeof(hid->phys), "%pMR", &bt_sk(session->ctrl_sock->sk)->src); snprintf(hid->uniq, sizeof(hid->uniq), "%pMR", &bt_sk(session->ctrl_sock->sk)->dst); hid->dev.parent = &session->conn->dev; hid->ll_driver = &hidp_hid_driver; hid->hid_get_raw_report = hidp_get_raw_report; hid->hid_output_raw_report = hidp_output_raw_report; /* True if device is blacklisted in drivers/hid/hid-core.c */ if (hid_ignore(hid)) { hid_destroy_device(session->hid); session->hid = NULL; return -ENODEV; } return 0; fault: kfree(session->rd_data); session->rd_data = NULL; return err; } int hidp_add_connection(struct hidp_connadd_req *req, struct socket *ctrl_sock, struct socket *intr_sock) { struct hidp_session *session, *s; int vendor, product; int err; BT_DBG(""); if (bacmp(&bt_sk(ctrl_sock->sk)->src, &bt_sk(intr_sock->sk)->src) || bacmp(&bt_sk(ctrl_sock->sk)->dst, &bt_sk(intr_sock->sk)->dst)) return -ENOTUNIQ; BT_DBG("rd_data %p rd_size %d", req->rd_data, req->rd_size); down_write(&hidp_session_sem); s = __hidp_get_session(&bt_sk(ctrl_sock->sk)->dst); if (s && s->state == BT_CONNECTED) { up_write(&hidp_session_sem); return -EEXIST; } session = kzalloc(sizeof(struct hidp_session), GFP_KERNEL); if (!session) { up_write(&hidp_session_sem); return -ENOMEM; } bacpy(&session->bdaddr, &bt_sk(ctrl_sock->sk)->dst); session->ctrl_mtu = min_t(uint, l2cap_pi(ctrl_sock->sk)->chan->omtu, l2cap_pi(ctrl_sock->sk)->chan->imtu); session->intr_mtu = min_t(uint, l2cap_pi(intr_sock->sk)->chan->omtu, l2cap_pi(intr_sock->sk)->chan->imtu); BT_DBG("ctrl mtu %d intr mtu %d", session->ctrl_mtu, session->intr_mtu); session->ctrl_sock = ctrl_sock; session->intr_sock = intr_sock; session->state = BT_CONNECTED; session->conn = hidp_get_connection(session); if (!session->conn) { err = -ENOTCONN; goto failed; } setup_timer(&session->timer, hidp_idle_timeout, (unsigned long)session); skb_queue_head_init(&session->ctrl_transmit); skb_queue_head_init(&session->intr_transmit); mutex_init(&session->report_mutex); init_waitqueue_head(&session->report_queue); init_waitqueue_head(&session->startup_queue); session->waiting_for_startup = 1; session->flags = req->flags & (1 << HIDP_BLUETOOTH_VENDOR_ID); session->idle_to = req->idle_to; __hidp_link_session(session); if (req->rd_size > 0) { err = hidp_setup_hid(session, req); if (err && err != -ENODEV) goto purge; } if (!session->hid) { err = hidp_setup_input(session, req); if (err < 0) goto purge; } hidp_set_timer(session); if (session->hid) { vendor = session->hid->vendor; product = session->hid->product; } else if (session->input) { vendor = session->input->id.vendor; product = session->input->id.product; } else { vendor = 0x0000; product = 0x0000; } session->task = kthread_run(hidp_session, session, "khidpd_%04x%04x", vendor, product); if (IS_ERR(session->task)) { err = PTR_ERR(session->task); goto unlink; } while (session->waiting_for_startup) { wait_event_interruptible(session->startup_queue, !session->waiting_for_startup); } if (session->hid) err = hid_add_device(session->hid); else err = input_register_device(session->input); if (err < 0) { atomic_inc(&session->terminate); wake_up_process(session->task); up_write(&hidp_session_sem); return err; } if (session->input) { hidp_send_ctrl_message(session, HIDP_TRANS_SET_PROTOCOL | HIDP_PROTO_BOOT, NULL, 0); session->flags |= (1 << HIDP_BOOT_PROTOCOL_MODE); session->leds = 0xff; hidp_input_event(session->input, EV_LED, 0, 0); } up_write(&hidp_session_sem); return 0; unlink: hidp_del_timer(session); if (session->input) { input_unregister_device(session->input); session->input = NULL; } if (session->hid) { hid_destroy_device(session->hid); session->hid = NULL; } kfree(session->rd_data); session->rd_data = NULL; purge: __hidp_unlink_session(session); skb_queue_purge(&session->ctrl_transmit); skb_queue_purge(&session->intr_transmit); failed: up_write(&hidp_session_sem); kfree(session); return err; } int hidp_del_connection(struct hidp_conndel_req *req) { struct hidp_session *session; int err = 0; BT_DBG(""); down_read(&hidp_session_sem); session = __hidp_get_session(&req->bdaddr); if (session) { if (req->flags & (1 << HIDP_VIRTUAL_CABLE_UNPLUG)) { hidp_send_ctrl_message(session, HIDP_TRANS_HID_CONTROL | HIDP_CTRL_VIRTUAL_CABLE_UNPLUG, NULL, 0); } else { /* Flush the transmit queues */ skb_queue_purge(&session->ctrl_transmit); skb_queue_purge(&session->intr_transmit); atomic_inc(&session->terminate); wake_up_process(session->task); } } else err = -ENOENT; up_read(&hidp_session_sem); return err; } int hidp_get_connlist(struct hidp_connlist_req *req) { struct hidp_session *session; int err = 0, n = 0; BT_DBG(""); down_read(&hidp_session_sem); list_for_each_entry(session, &hidp_session_list, list) { struct hidp_conninfo ci; __hidp_copy_session(session, &ci); if (copy_to_user(req->ci, &ci, sizeof(ci))) { err = -EFAULT; break; } if (++n >= req->cnum) break; req->ci++; } req->cnum = n; up_read(&hidp_session_sem); return err; } int hidp_get_conninfo(struct hidp_conninfo *ci) { struct hidp_session *session; int err = 0; down_read(&hidp_session_sem); session = __hidp_get_session(&ci->bdaddr); if (session) __hidp_copy_session(session, ci); else err = -ENOENT; up_read(&hidp_session_sem); return err; } static int __init hidp_init(void) { BT_INFO("HIDP (Human Interface Emulation) ver %s", VERSION); return hidp_init_sockets(); } static void __exit hidp_exit(void) { hidp_cleanup_sockets(); } module_init(hidp_init); module_exit(hidp_exit); MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>"); MODULE_DESCRIPTION("Bluetooth HIDP ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS("bt-proto-6");
./CrossVul/dataset_final_sorted/CWE-200/c/good_5569_0
crossvul-cpp_data_bad_5685_0
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2000-2001 Qualcomm Incorporated Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth SCO sockets. */ #include <linux/module.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/sco.h> static bool disable_esco; static const struct proto_ops sco_sock_ops; static struct bt_sock_list sco_sk_list = { .lock = __RW_LOCK_UNLOCKED(sco_sk_list.lock) }; static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent); static void sco_chan_del(struct sock *sk, int err); static void sco_sock_close(struct sock *sk); static void sco_sock_kill(struct sock *sk); /* ---- SCO timers ---- */ static void sco_sock_timeout(unsigned long arg) { struct sock *sk = (struct sock *) arg; BT_DBG("sock %p state %d", sk, sk->sk_state); bh_lock_sock(sk); sk->sk_err = ETIMEDOUT; sk->sk_state_change(sk); bh_unlock_sock(sk); sco_sock_kill(sk); sock_put(sk); } static void sco_sock_set_timer(struct sock *sk, long timeout) { BT_DBG("sock %p state %d timeout %ld", sk, sk->sk_state, timeout); sk_reset_timer(sk, &sk->sk_timer, jiffies + timeout); } static void sco_sock_clear_timer(struct sock *sk) { BT_DBG("sock %p state %d", sk, sk->sk_state); sk_stop_timer(sk, &sk->sk_timer); } /* ---- SCO connections ---- */ static struct sco_conn *sco_conn_add(struct hci_conn *hcon) { struct hci_dev *hdev = hcon->hdev; struct sco_conn *conn = hcon->sco_data; if (conn) return conn; conn = kzalloc(sizeof(struct sco_conn), GFP_ATOMIC); if (!conn) return NULL; spin_lock_init(&conn->lock); hcon->sco_data = conn; conn->hcon = hcon; conn->src = &hdev->bdaddr; conn->dst = &hcon->dst; if (hdev->sco_mtu > 0) conn->mtu = hdev->sco_mtu; else conn->mtu = 60; BT_DBG("hcon %p conn %p", hcon, conn); return conn; } static struct sock *sco_chan_get(struct sco_conn *conn) { struct sock *sk = NULL; sco_conn_lock(conn); sk = conn->sk; sco_conn_unlock(conn); return sk; } static int sco_conn_del(struct hci_conn *hcon, int err) { struct sco_conn *conn = hcon->sco_data; struct sock *sk; if (!conn) return 0; BT_DBG("hcon %p conn %p, err %d", hcon, conn, err); /* Kill socket */ sk = sco_chan_get(conn); if (sk) { bh_lock_sock(sk); sco_sock_clear_timer(sk); sco_chan_del(sk, err); bh_unlock_sock(sk); sco_sock_kill(sk); } hcon->sco_data = NULL; kfree(conn); return 0; } static int sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent) { int err = 0; sco_conn_lock(conn); if (conn->sk) err = -EBUSY; else __sco_chan_add(conn, sk, parent); sco_conn_unlock(conn); return err; } static int sco_connect(struct sock *sk) { bdaddr_t *src = &bt_sk(sk)->src; bdaddr_t *dst = &bt_sk(sk)->dst; struct sco_conn *conn; struct hci_conn *hcon; struct hci_dev *hdev; int err, type; BT_DBG("%pMR -> %pMR", src, dst); hdev = hci_get_route(dst, src); if (!hdev) return -EHOSTUNREACH; hci_dev_lock(hdev); if (lmp_esco_capable(hdev) && !disable_esco) type = ESCO_LINK; else type = SCO_LINK; hcon = hci_connect(hdev, type, dst, BDADDR_BREDR, BT_SECURITY_LOW, HCI_AT_NO_BONDING); if (IS_ERR(hcon)) { err = PTR_ERR(hcon); goto done; } conn = sco_conn_add(hcon); if (!conn) { hci_conn_put(hcon); err = -ENOMEM; goto done; } /* Update source addr of the socket */ bacpy(src, conn->src); err = sco_chan_add(conn, sk, NULL); if (err) goto done; if (hcon->state == BT_CONNECTED) { sco_sock_clear_timer(sk); sk->sk_state = BT_CONNECTED; } else { sk->sk_state = BT_CONNECT; sco_sock_set_timer(sk, sk->sk_sndtimeo); } done: hci_dev_unlock(hdev); hci_dev_put(hdev); return err; } static int sco_send_frame(struct sock *sk, struct msghdr *msg, int len) { struct sco_conn *conn = sco_pi(sk)->conn; struct sk_buff *skb; int err; /* Check outgoing MTU */ if (len > conn->mtu) return -EINVAL; BT_DBG("sk %p len %d", sk, len); skb = bt_skb_send_alloc(sk, len, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) return err; if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { kfree_skb(skb); return -EFAULT; } hci_send_sco(conn->hcon, skb); return len; } static void sco_recv_frame(struct sco_conn *conn, struct sk_buff *skb) { struct sock *sk = sco_chan_get(conn); if (!sk) goto drop; BT_DBG("sk %p len %d", sk, skb->len); if (sk->sk_state != BT_CONNECTED) goto drop; if (!sock_queue_rcv_skb(sk, skb)) return; drop: kfree_skb(skb); } /* -------- Socket interface ---------- */ static struct sock *__sco_get_sock_listen_by_addr(bdaddr_t *ba) { struct sock *sk; sk_for_each(sk, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; if (!bacmp(&bt_sk(sk)->src, ba)) return sk; } return NULL; } /* Find socket listening on source bdaddr. * Returns closest match. */ static struct sock *sco_get_sock_listen(bdaddr_t *src) { struct sock *sk = NULL, *sk1 = NULL; read_lock(&sco_sk_list.lock); sk_for_each(sk, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; /* Exact match. */ if (!bacmp(&bt_sk(sk)->src, src)) break; /* Closest match */ if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY)) sk1 = sk; } read_unlock(&sco_sk_list.lock); return sk ? sk : sk1; } static void sco_sock_destruct(struct sock *sk) { BT_DBG("sk %p", sk); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); } static void sco_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted channels */ while ((sk = bt_accept_dequeue(parent, NULL))) { sco_sock_close(sk); sco_sock_kill(sk); } parent->sk_state = BT_CLOSED; sock_set_flag(parent, SOCK_ZAPPED); } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void sco_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %d", sk, sk->sk_state); /* Kill poor orphan */ bt_sock_unlink(&sco_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static void __sco_sock_close(struct sock *sk) { BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket); switch (sk->sk_state) { case BT_LISTEN: sco_sock_cleanup_listen(sk); break; case BT_CONNECTED: case BT_CONFIG: if (sco_pi(sk)->conn->hcon) { sk->sk_state = BT_DISCONN; sco_sock_set_timer(sk, SCO_DISCONN_TIMEOUT); hci_conn_put(sco_pi(sk)->conn->hcon); sco_pi(sk)->conn->hcon = NULL; } else sco_chan_del(sk, ECONNRESET); break; case BT_CONNECT2: case BT_CONNECT: case BT_DISCONN: sco_chan_del(sk, ECONNRESET); break; default: sock_set_flag(sk, SOCK_ZAPPED); break; } } /* Must be called on unlocked socket. */ static void sco_sock_close(struct sock *sk) { sco_sock_clear_timer(sk); lock_sock(sk); __sco_sock_close(sk); release_sock(sk); sco_sock_kill(sk); } static void sco_sock_init(struct sock *sk, struct sock *parent) { BT_DBG("sk %p", sk); if (parent) { sk->sk_type = parent->sk_type; bt_sk(sk)->flags = bt_sk(parent)->flags; security_sk_clone(parent, sk); } } static struct proto sco_proto = { .name = "SCO", .owner = THIS_MODULE, .obj_size = sizeof(struct sco_pinfo) }; static struct sock *sco_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio) { struct sock *sk; sk = sk_alloc(net, PF_BLUETOOTH, prio, &sco_proto); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); sk->sk_destruct = sco_sock_destruct; sk->sk_sndtimeo = SCO_CONN_TIMEOUT; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; setup_timer(&sk->sk_timer, sco_sock_timeout, (unsigned long)sk); bt_sock_link(&sco_sk_list, sk); return sk; } static int sco_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_SEQPACKET) return -ESOCKTNOSUPPORT; sock->ops = &sco_sock_ops; sk = sco_sock_alloc(net, sock, protocol, GFP_ATOMIC); if (!sk) return -ENOMEM; sco_sock_init(sk, NULL); return 0; } static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&bt_sk(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } static int sco_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p", sk); if (alen < sizeof(struct sockaddr_sco) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) return -EBADFD; if (sk->sk_type != SOCK_SEQPACKET) return -EINVAL; lock_sock(sk); /* Set destination address and psm */ bacpy(&bt_sk(sk)->dst, &sa->sco_bdaddr); err = sco_connect(sk); if (err) goto done; err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } static int sco_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; bdaddr_t *src = &bt_sk(sk)->src; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } write_lock(&sco_sk_list.lock); if (__sco_get_sock_listen_by_addr(src)) { err = -EADDRINUSE; goto unlock; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; unlock: write_unlock(&sco_sk_list.lock); done: release_sock(sk); return err; } static int sco_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *ch; long timeo; int err = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } ch = bt_accept_dequeue(sk, newsock); if (ch) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", ch); done: release_sock(sk); return err; } static int sco_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_sco); if (peer) bacpy(&sa->sco_bdaddr, &bt_sk(sk)->dst); else bacpy(&sa->sco_bdaddr, &bt_sk(sk)->src); return 0; } static int sco_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; lock_sock(sk); if (sk->sk_state == BT_CONNECTED) err = sco_send_frame(sk, msg, len); else err = -ENOTCONN; release_sock(sk); return err; } static int sco_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct sco_pinfo *pi = sco_pi(sk); lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { hci_conn_accept(pi->conn->hcon, 0); sk->sk_state = BT_CONFIG; release_sock(sk); return 0; } release_sock(sk); return bt_sock_recvmsg(iocb, sock, msg, len, flags); } static int sco_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct sco_options opts; struct sco_conninfo cinfo; int len, err = 0; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case SCO_OPTIONS: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } opts.mtu = sco_pi(sk)->conn->mtu; BT_DBG("mtu %d", opts.mtu); len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *)&opts, len)) err = -EFAULT; break; case SCO_CONNINFO: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle; memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *)&cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_SCO) return sco_sock_getsockopt_old(sock, optname, optval, optlen); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; lock_sock(sk); if (!sk->sk_shutdown) { sk->sk_shutdown = SHUTDOWN_MASK; sco_sock_clear_timer(sk); __sco_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } release_sock(sk); return err; } static int sco_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; sco_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) { lock_sock(sk); err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); release_sock(sk); } sock_orphan(sk); sco_sock_kill(sk); return err; } static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent) { BT_DBG("conn %p", conn); sco_pi(sk)->conn = conn; conn->sk = sk; if (parent) bt_accept_enqueue(parent, sk); } /* Delete channel. * Must be called on the locked socket. */ static void sco_chan_del(struct sock *sk, int err) { struct sco_conn *conn; conn = sco_pi(sk)->conn; BT_DBG("sk %p, conn %p, err %d", sk, conn, err); if (conn) { sco_conn_lock(conn); conn->sk = NULL; sco_pi(sk)->conn = NULL; sco_conn_unlock(conn); if (conn->hcon) hci_conn_put(conn->hcon); } sk->sk_state = BT_CLOSED; sk->sk_err = err; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_ZAPPED); } static void sco_conn_ready(struct sco_conn *conn) { struct sock *parent; struct sock *sk = conn->sk; BT_DBG("conn %p", conn); if (sk) { sco_sock_clear_timer(sk); bh_lock_sock(sk); sk->sk_state = BT_CONNECTED; sk->sk_state_change(sk); bh_unlock_sock(sk); } else { sco_conn_lock(conn); parent = sco_get_sock_listen(conn->src); if (!parent) { sco_conn_unlock(conn); return; } bh_lock_sock(parent); sk = sco_sock_alloc(sock_net(parent), NULL, BTPROTO_SCO, GFP_ATOMIC); if (!sk) { bh_unlock_sock(parent); sco_conn_unlock(conn); return; } sco_sock_init(sk, parent); bacpy(&bt_sk(sk)->src, conn->src); bacpy(&bt_sk(sk)->dst, conn->dst); hci_conn_hold(conn->hcon); __sco_chan_add(conn, sk, parent); if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) sk->sk_state = BT_CONNECT2; else sk->sk_state = BT_CONNECTED; /* Wake up parent */ parent->sk_data_ready(parent, 1); bh_unlock_sock(parent); sco_conn_unlock(conn); } } /* ----- SCO interface with lower layer (HCI) ----- */ int sco_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr, __u8 *flags) { struct sock *sk; int lm = 0; BT_DBG("hdev %s, bdaddr %pMR", hdev->name, bdaddr); /* Find listening sockets */ read_lock(&sco_sk_list.lock); sk_for_each(sk, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; if (!bacmp(&bt_sk(sk)->src, &hdev->bdaddr) || !bacmp(&bt_sk(sk)->src, BDADDR_ANY)) { lm |= HCI_LM_ACCEPT; if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) *flags |= HCI_PROTO_DEFER; break; } } read_unlock(&sco_sk_list.lock); return lm; } void sco_connect_cfm(struct hci_conn *hcon, __u8 status) { BT_DBG("hcon %p bdaddr %pMR status %d", hcon, &hcon->dst, status); if (!status) { struct sco_conn *conn; conn = sco_conn_add(hcon); if (conn) sco_conn_ready(conn); } else sco_conn_del(hcon, bt_to_errno(status)); } void sco_disconn_cfm(struct hci_conn *hcon, __u8 reason) { BT_DBG("hcon %p reason %d", hcon, reason); sco_conn_del(hcon, bt_to_errno(reason)); } int sco_recv_scodata(struct hci_conn *hcon, struct sk_buff *skb) { struct sco_conn *conn = hcon->sco_data; if (!conn) goto drop; BT_DBG("conn %p len %d", conn, skb->len); if (skb->len) { sco_recv_frame(conn, skb); return 0; } drop: kfree_skb(skb); return 0; } static int sco_debugfs_show(struct seq_file *f, void *p) { struct sock *sk; read_lock(&sco_sk_list.lock); sk_for_each(sk, &sco_sk_list.head) { seq_printf(f, "%pMR %pMR %d\n", &bt_sk(sk)->src, &bt_sk(sk)->dst, sk->sk_state); } read_unlock(&sco_sk_list.lock); return 0; } static int sco_debugfs_open(struct inode *inode, struct file *file) { return single_open(file, sco_debugfs_show, inode->i_private); } static const struct file_operations sco_debugfs_fops = { .open = sco_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *sco_debugfs; static const struct proto_ops sco_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = sco_sock_release, .bind = sco_sock_bind, .connect = sco_sock_connect, .listen = sco_sock_listen, .accept = sco_sock_accept, .getname = sco_sock_getname, .sendmsg = sco_sock_sendmsg, .recvmsg = sco_sock_recvmsg, .poll = bt_sock_poll, .ioctl = bt_sock_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = sco_sock_shutdown, .setsockopt = sco_sock_setsockopt, .getsockopt = sco_sock_getsockopt }; static const struct net_proto_family sco_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = sco_sock_create, }; int __init sco_init(void) { int err; err = proto_register(&sco_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_SCO, &sco_sock_family_ops); if (err < 0) { BT_ERR("SCO socket registration failed"); goto error; } err = bt_procfs_init(THIS_MODULE, &init_net, "sco", &sco_sk_list, NULL); if (err < 0) { BT_ERR("Failed to create SCO proc file"); bt_sock_unregister(BTPROTO_SCO); goto error; } if (bt_debugfs) { sco_debugfs = debugfs_create_file("sco", 0444, bt_debugfs, NULL, &sco_debugfs_fops); if (!sco_debugfs) BT_ERR("Failed to create SCO debug file"); } BT_INFO("SCO socket layer initialized"); return 0; error: proto_unregister(&sco_proto); return err; } void __exit sco_exit(void) { bt_procfs_cleanup(&init_net, "sco"); debugfs_remove(sco_debugfs); if (bt_sock_unregister(BTPROTO_SCO) < 0) BT_ERR("SCO socket unregistration failed"); proto_unregister(&sco_proto); } module_param(disable_esco, bool, 0644); MODULE_PARM_DESC(disable_esco, "Disable eSCO connection creation");
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5685_0
crossvul-cpp_data_good_5098_0
/* * Copyright (c) 2014, Ericsson AB * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * Alternatively, this software may be distributed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include "core.h" #include "bearer.h" #include "link.h" #include "name_table.h" #include "socket.h" #include "node.h" #include "net.h" #include <net/genetlink.h> #include <linux/tipc_config.h> /* The legacy API had an artificial message length limit called * ULTRA_STRING_MAX_LEN. */ #define ULTRA_STRING_MAX_LEN 32768 #define TIPC_SKB_MAX TLV_SPACE(ULTRA_STRING_MAX_LEN) #define REPLY_TRUNCATED "<truncated>\n" struct tipc_nl_compat_msg { u16 cmd; int rep_type; int rep_size; int req_type; struct net *net; struct sk_buff *rep; struct tlv_desc *req; struct sock *dst_sk; }; struct tipc_nl_compat_cmd_dump { int (*header)(struct tipc_nl_compat_msg *); int (*dumpit)(struct sk_buff *, struct netlink_callback *); int (*format)(struct tipc_nl_compat_msg *msg, struct nlattr **attrs); }; struct tipc_nl_compat_cmd_doit { int (*doit)(struct sk_buff *skb, struct genl_info *info); int (*transcode)(struct tipc_nl_compat_cmd_doit *cmd, struct sk_buff *skb, struct tipc_nl_compat_msg *msg); }; static int tipc_skb_tailroom(struct sk_buff *skb) { int tailroom; int limit; tailroom = skb_tailroom(skb); limit = TIPC_SKB_MAX - skb->len; if (tailroom < limit) return tailroom; return limit; } static int tipc_add_tlv(struct sk_buff *skb, u16 type, void *data, u16 len) { struct tlv_desc *tlv = (struct tlv_desc *)skb_tail_pointer(skb); if (tipc_skb_tailroom(skb) < TLV_SPACE(len)) return -EMSGSIZE; skb_put(skb, TLV_SPACE(len)); tlv->tlv_type = htons(type); tlv->tlv_len = htons(TLV_LENGTH(len)); if (len && data) memcpy(TLV_DATA(tlv), data, len); return 0; } static void tipc_tlv_init(struct sk_buff *skb, u16 type) { struct tlv_desc *tlv = (struct tlv_desc *)skb->data; TLV_SET_LEN(tlv, 0); TLV_SET_TYPE(tlv, type); skb_put(skb, sizeof(struct tlv_desc)); } static int tipc_tlv_sprintf(struct sk_buff *skb, const char *fmt, ...) { int n; u16 len; u32 rem; char *buf; struct tlv_desc *tlv; va_list args; rem = tipc_skb_tailroom(skb); tlv = (struct tlv_desc *)skb->data; len = TLV_GET_LEN(tlv); buf = TLV_DATA(tlv) + len; va_start(args, fmt); n = vscnprintf(buf, rem, fmt, args); va_end(args); TLV_SET_LEN(tlv, n + len); skb_put(skb, n); return n; } static struct sk_buff *tipc_tlv_alloc(int size) { int hdr_len; struct sk_buff *buf; size = TLV_SPACE(size); hdr_len = nlmsg_total_size(GENL_HDRLEN + TIPC_GENL_HDRLEN); buf = alloc_skb(hdr_len + size, GFP_KERNEL); if (!buf) return NULL; skb_reserve(buf, hdr_len); return buf; } static struct sk_buff *tipc_get_err_tlv(char *str) { int str_len = strlen(str) + 1; struct sk_buff *buf; buf = tipc_tlv_alloc(TLV_SPACE(str_len)); if (buf) tipc_add_tlv(buf, TIPC_TLV_ERROR_STRING, str, str_len); return buf; } static int __tipc_nl_compat_dumpit(struct tipc_nl_compat_cmd_dump *cmd, struct tipc_nl_compat_msg *msg, struct sk_buff *arg) { int len = 0; int err; struct sk_buff *buf; struct nlmsghdr *nlmsg; struct netlink_callback cb; memset(&cb, 0, sizeof(cb)); cb.nlh = (struct nlmsghdr *)arg->data; cb.skb = arg; buf = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL); if (!buf) return -ENOMEM; buf->sk = msg->dst_sk; do { int rem; len = (*cmd->dumpit)(buf, &cb); nlmsg_for_each_msg(nlmsg, nlmsg_hdr(buf), len, rem) { struct nlattr **attrs; err = tipc_nlmsg_parse(nlmsg, &attrs); if (err) goto err_out; err = (*cmd->format)(msg, attrs); if (err) goto err_out; if (tipc_skb_tailroom(msg->rep) <= 1) { err = -EMSGSIZE; goto err_out; } } skb_reset_tail_pointer(buf); buf->len = 0; } while (len); err = 0; err_out: kfree_skb(buf); if (err == -EMSGSIZE) { /* The legacy API only considered messages filling * "ULTRA_STRING_MAX_LEN" to be truncated. */ if ((TIPC_SKB_MAX - msg->rep->len) <= 1) { char *tail = skb_tail_pointer(msg->rep); if (*tail != '\0') sprintf(tail - sizeof(REPLY_TRUNCATED) - 1, REPLY_TRUNCATED); } return 0; } return err; } static int tipc_nl_compat_dumpit(struct tipc_nl_compat_cmd_dump *cmd, struct tipc_nl_compat_msg *msg) { int err; struct sk_buff *arg; if (msg->req_type && !TLV_CHECK_TYPE(msg->req, msg->req_type)) return -EINVAL; msg->rep = tipc_tlv_alloc(msg->rep_size); if (!msg->rep) return -ENOMEM; if (msg->rep_type) tipc_tlv_init(msg->rep, msg->rep_type); if (cmd->header) (*cmd->header)(msg); arg = nlmsg_new(0, GFP_KERNEL); if (!arg) { kfree_skb(msg->rep); return -ENOMEM; } err = __tipc_nl_compat_dumpit(cmd, msg, arg); if (err) kfree_skb(msg->rep); kfree_skb(arg); return err; } static int __tipc_nl_compat_doit(struct tipc_nl_compat_cmd_doit *cmd, struct tipc_nl_compat_msg *msg) { int err; struct sk_buff *doit_buf; struct sk_buff *trans_buf; struct nlattr **attrbuf; struct genl_info info; trans_buf = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!trans_buf) return -ENOMEM; err = (*cmd->transcode)(cmd, trans_buf, msg); if (err) goto trans_out; attrbuf = kmalloc((tipc_genl_family.maxattr + 1) * sizeof(struct nlattr *), GFP_KERNEL); if (!attrbuf) { err = -ENOMEM; goto trans_out; } err = nla_parse(attrbuf, tipc_genl_family.maxattr, (const struct nlattr *)trans_buf->data, trans_buf->len, NULL); if (err) goto parse_out; doit_buf = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!doit_buf) { err = -ENOMEM; goto parse_out; } doit_buf->sk = msg->dst_sk; memset(&info, 0, sizeof(info)); info.attrs = attrbuf; err = (*cmd->doit)(doit_buf, &info); kfree_skb(doit_buf); parse_out: kfree(attrbuf); trans_out: kfree_skb(trans_buf); return err; } static int tipc_nl_compat_doit(struct tipc_nl_compat_cmd_doit *cmd, struct tipc_nl_compat_msg *msg) { int err; if (msg->req_type && !TLV_CHECK_TYPE(msg->req, msg->req_type)) return -EINVAL; err = __tipc_nl_compat_doit(cmd, msg); if (err) return err; /* The legacy API considered an empty message a success message */ msg->rep = tipc_tlv_alloc(0); if (!msg->rep) return -ENOMEM; return 0; } static int tipc_nl_compat_bearer_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { struct nlattr *bearer[TIPC_NLA_BEARER_MAX + 1]; int err; if (!attrs[TIPC_NLA_BEARER]) return -EINVAL; err = nla_parse_nested(bearer, TIPC_NLA_BEARER_MAX, attrs[TIPC_NLA_BEARER], NULL); if (err) return err; return tipc_add_tlv(msg->rep, TIPC_TLV_BEARER_NAME, nla_data(bearer[TIPC_NLA_BEARER_NAME]), nla_len(bearer[TIPC_NLA_BEARER_NAME])); } static int tipc_nl_compat_bearer_enable(struct tipc_nl_compat_cmd_doit *cmd, struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { struct nlattr *prop; struct nlattr *bearer; struct tipc_bearer_config *b; b = (struct tipc_bearer_config *)TLV_DATA(msg->req); bearer = nla_nest_start(skb, TIPC_NLA_BEARER); if (!bearer) return -EMSGSIZE; if (nla_put_string(skb, TIPC_NLA_BEARER_NAME, b->name)) return -EMSGSIZE; if (nla_put_u32(skb, TIPC_NLA_BEARER_DOMAIN, ntohl(b->disc_domain))) return -EMSGSIZE; if (ntohl(b->priority) <= TIPC_MAX_LINK_PRI) { prop = nla_nest_start(skb, TIPC_NLA_BEARER_PROP); if (!prop) return -EMSGSIZE; if (nla_put_u32(skb, TIPC_NLA_PROP_PRIO, ntohl(b->priority))) return -EMSGSIZE; nla_nest_end(skb, prop); } nla_nest_end(skb, bearer); return 0; } static int tipc_nl_compat_bearer_disable(struct tipc_nl_compat_cmd_doit *cmd, struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { char *name; struct nlattr *bearer; name = (char *)TLV_DATA(msg->req); bearer = nla_nest_start(skb, TIPC_NLA_BEARER); if (!bearer) return -EMSGSIZE; if (nla_put_string(skb, TIPC_NLA_BEARER_NAME, name)) return -EMSGSIZE; nla_nest_end(skb, bearer); return 0; } static inline u32 perc(u32 count, u32 total) { return (count * 100 + (total / 2)) / total; } static void __fill_bc_link_stat(struct tipc_nl_compat_msg *msg, struct nlattr *prop[], struct nlattr *stats[]) { tipc_tlv_sprintf(msg->rep, " Window:%u packets\n", nla_get_u32(prop[TIPC_NLA_PROP_WIN])); tipc_tlv_sprintf(msg->rep, " RX packets:%u fragments:%u/%u bundles:%u/%u\n", nla_get_u32(stats[TIPC_NLA_STATS_RX_INFO]), nla_get_u32(stats[TIPC_NLA_STATS_RX_FRAGMENTS]), nla_get_u32(stats[TIPC_NLA_STATS_RX_FRAGMENTED]), nla_get_u32(stats[TIPC_NLA_STATS_RX_BUNDLES]), nla_get_u32(stats[TIPC_NLA_STATS_RX_BUNDLED])); tipc_tlv_sprintf(msg->rep, " TX packets:%u fragments:%u/%u bundles:%u/%u\n", nla_get_u32(stats[TIPC_NLA_STATS_TX_INFO]), nla_get_u32(stats[TIPC_NLA_STATS_TX_FRAGMENTS]), nla_get_u32(stats[TIPC_NLA_STATS_TX_FRAGMENTED]), nla_get_u32(stats[TIPC_NLA_STATS_TX_BUNDLES]), nla_get_u32(stats[TIPC_NLA_STATS_TX_BUNDLED])); tipc_tlv_sprintf(msg->rep, " RX naks:%u defs:%u dups:%u\n", nla_get_u32(stats[TIPC_NLA_STATS_RX_NACKS]), nla_get_u32(stats[TIPC_NLA_STATS_RX_DEFERRED]), nla_get_u32(stats[TIPC_NLA_STATS_DUPLICATES])); tipc_tlv_sprintf(msg->rep, " TX naks:%u acks:%u dups:%u\n", nla_get_u32(stats[TIPC_NLA_STATS_TX_NACKS]), nla_get_u32(stats[TIPC_NLA_STATS_TX_ACKS]), nla_get_u32(stats[TIPC_NLA_STATS_RETRANSMITTED])); tipc_tlv_sprintf(msg->rep, " Congestion link:%u Send queue max:%u avg:%u", nla_get_u32(stats[TIPC_NLA_STATS_LINK_CONGS]), nla_get_u32(stats[TIPC_NLA_STATS_MAX_QUEUE]), nla_get_u32(stats[TIPC_NLA_STATS_AVG_QUEUE])); } static int tipc_nl_compat_link_stat_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { char *name; struct nlattr *link[TIPC_NLA_LINK_MAX + 1]; struct nlattr *prop[TIPC_NLA_PROP_MAX + 1]; struct nlattr *stats[TIPC_NLA_STATS_MAX + 1]; int err; if (!attrs[TIPC_NLA_LINK]) return -EINVAL; err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK], NULL); if (err) return err; if (!link[TIPC_NLA_LINK_PROP]) return -EINVAL; err = nla_parse_nested(prop, TIPC_NLA_PROP_MAX, link[TIPC_NLA_LINK_PROP], NULL); if (err) return err; if (!link[TIPC_NLA_LINK_STATS]) return -EINVAL; err = nla_parse_nested(stats, TIPC_NLA_STATS_MAX, link[TIPC_NLA_LINK_STATS], NULL); if (err) return err; name = (char *)TLV_DATA(msg->req); if (strcmp(name, nla_data(link[TIPC_NLA_LINK_NAME])) != 0) return 0; tipc_tlv_sprintf(msg->rep, "\nLink <%s>\n", nla_data(link[TIPC_NLA_LINK_NAME])); if (link[TIPC_NLA_LINK_BROADCAST]) { __fill_bc_link_stat(msg, prop, stats); return 0; } if (link[TIPC_NLA_LINK_ACTIVE]) tipc_tlv_sprintf(msg->rep, " ACTIVE"); else if (link[TIPC_NLA_LINK_UP]) tipc_tlv_sprintf(msg->rep, " STANDBY"); else tipc_tlv_sprintf(msg->rep, " DEFUNCT"); tipc_tlv_sprintf(msg->rep, " MTU:%u Priority:%u", nla_get_u32(link[TIPC_NLA_LINK_MTU]), nla_get_u32(prop[TIPC_NLA_PROP_PRIO])); tipc_tlv_sprintf(msg->rep, " Tolerance:%u ms Window:%u packets\n", nla_get_u32(prop[TIPC_NLA_PROP_TOL]), nla_get_u32(prop[TIPC_NLA_PROP_WIN])); tipc_tlv_sprintf(msg->rep, " RX packets:%u fragments:%u/%u bundles:%u/%u\n", nla_get_u32(link[TIPC_NLA_LINK_RX]) - nla_get_u32(stats[TIPC_NLA_STATS_RX_INFO]), nla_get_u32(stats[TIPC_NLA_STATS_RX_FRAGMENTS]), nla_get_u32(stats[TIPC_NLA_STATS_RX_FRAGMENTED]), nla_get_u32(stats[TIPC_NLA_STATS_RX_BUNDLES]), nla_get_u32(stats[TIPC_NLA_STATS_RX_BUNDLED])); tipc_tlv_sprintf(msg->rep, " TX packets:%u fragments:%u/%u bundles:%u/%u\n", nla_get_u32(link[TIPC_NLA_LINK_TX]) - nla_get_u32(stats[TIPC_NLA_STATS_TX_INFO]), nla_get_u32(stats[TIPC_NLA_STATS_TX_FRAGMENTS]), nla_get_u32(stats[TIPC_NLA_STATS_TX_FRAGMENTED]), nla_get_u32(stats[TIPC_NLA_STATS_TX_BUNDLES]), nla_get_u32(stats[TIPC_NLA_STATS_TX_BUNDLED])); tipc_tlv_sprintf(msg->rep, " TX profile sample:%u packets average:%u octets\n", nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_CNT]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_TOT]) / nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT])); tipc_tlv_sprintf(msg->rep, " 0-64:%u%% -256:%u%% -1024:%u%% -4096:%u%% ", perc(nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_P0]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT])), perc(nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_P1]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT])), perc(nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_P2]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT])), perc(nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_P3]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT]))); tipc_tlv_sprintf(msg->rep, "-16384:%u%% -32768:%u%% -66000:%u%%\n", perc(nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_P4]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT])), perc(nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_P5]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT])), perc(nla_get_u32(stats[TIPC_NLA_STATS_MSG_LEN_P6]), nla_get_u32(stats[TIPC_NLA_STATS_MSG_PROF_TOT]))); tipc_tlv_sprintf(msg->rep, " RX states:%u probes:%u naks:%u defs:%u dups:%u\n", nla_get_u32(stats[TIPC_NLA_STATS_RX_STATES]), nla_get_u32(stats[TIPC_NLA_STATS_RX_PROBES]), nla_get_u32(stats[TIPC_NLA_STATS_RX_NACKS]), nla_get_u32(stats[TIPC_NLA_STATS_RX_DEFERRED]), nla_get_u32(stats[TIPC_NLA_STATS_DUPLICATES])); tipc_tlv_sprintf(msg->rep, " TX states:%u probes:%u naks:%u acks:%u dups:%u\n", nla_get_u32(stats[TIPC_NLA_STATS_TX_STATES]), nla_get_u32(stats[TIPC_NLA_STATS_TX_PROBES]), nla_get_u32(stats[TIPC_NLA_STATS_TX_NACKS]), nla_get_u32(stats[TIPC_NLA_STATS_TX_ACKS]), nla_get_u32(stats[TIPC_NLA_STATS_RETRANSMITTED])); tipc_tlv_sprintf(msg->rep, " Congestion link:%u Send queue max:%u avg:%u", nla_get_u32(stats[TIPC_NLA_STATS_LINK_CONGS]), nla_get_u32(stats[TIPC_NLA_STATS_MAX_QUEUE]), nla_get_u32(stats[TIPC_NLA_STATS_AVG_QUEUE])); return 0; } static int tipc_nl_compat_link_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { struct nlattr *link[TIPC_NLA_LINK_MAX + 1]; struct tipc_link_info link_info; int err; if (!attrs[TIPC_NLA_LINK]) return -EINVAL; err = nla_parse_nested(link, TIPC_NLA_LINK_MAX, attrs[TIPC_NLA_LINK], NULL); if (err) return err; link_info.dest = nla_get_flag(link[TIPC_NLA_LINK_DEST]); link_info.up = htonl(nla_get_flag(link[TIPC_NLA_LINK_UP])); nla_strlcpy(link_info.str, nla_data(link[TIPC_NLA_LINK_NAME]), TIPC_MAX_LINK_NAME); return tipc_add_tlv(msg->rep, TIPC_TLV_LINK_INFO, &link_info, sizeof(link_info)); } static int __tipc_add_link_prop(struct sk_buff *skb, struct tipc_nl_compat_msg *msg, struct tipc_link_config *lc) { switch (msg->cmd) { case TIPC_CMD_SET_LINK_PRI: return nla_put_u32(skb, TIPC_NLA_PROP_PRIO, ntohl(lc->value)); case TIPC_CMD_SET_LINK_TOL: return nla_put_u32(skb, TIPC_NLA_PROP_TOL, ntohl(lc->value)); case TIPC_CMD_SET_LINK_WINDOW: return nla_put_u32(skb, TIPC_NLA_PROP_WIN, ntohl(lc->value)); } return -EINVAL; } static int tipc_nl_compat_media_set(struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { struct nlattr *prop; struct nlattr *media; struct tipc_link_config *lc; lc = (struct tipc_link_config *)TLV_DATA(msg->req); media = nla_nest_start(skb, TIPC_NLA_MEDIA); if (!media) return -EMSGSIZE; if (nla_put_string(skb, TIPC_NLA_MEDIA_NAME, lc->name)) return -EMSGSIZE; prop = nla_nest_start(skb, TIPC_NLA_MEDIA_PROP); if (!prop) return -EMSGSIZE; __tipc_add_link_prop(skb, msg, lc); nla_nest_end(skb, prop); nla_nest_end(skb, media); return 0; } static int tipc_nl_compat_bearer_set(struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { struct nlattr *prop; struct nlattr *bearer; struct tipc_link_config *lc; lc = (struct tipc_link_config *)TLV_DATA(msg->req); bearer = nla_nest_start(skb, TIPC_NLA_BEARER); if (!bearer) return -EMSGSIZE; if (nla_put_string(skb, TIPC_NLA_BEARER_NAME, lc->name)) return -EMSGSIZE; prop = nla_nest_start(skb, TIPC_NLA_BEARER_PROP); if (!prop) return -EMSGSIZE; __tipc_add_link_prop(skb, msg, lc); nla_nest_end(skb, prop); nla_nest_end(skb, bearer); return 0; } static int __tipc_nl_compat_link_set(struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { struct nlattr *prop; struct nlattr *link; struct tipc_link_config *lc; lc = (struct tipc_link_config *)TLV_DATA(msg->req); link = nla_nest_start(skb, TIPC_NLA_LINK); if (!link) return -EMSGSIZE; if (nla_put_string(skb, TIPC_NLA_LINK_NAME, lc->name)) return -EMSGSIZE; prop = nla_nest_start(skb, TIPC_NLA_LINK_PROP); if (!prop) return -EMSGSIZE; __tipc_add_link_prop(skb, msg, lc); nla_nest_end(skb, prop); nla_nest_end(skb, link); return 0; } static int tipc_nl_compat_link_set(struct tipc_nl_compat_cmd_doit *cmd, struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { struct tipc_link_config *lc; struct tipc_bearer *bearer; struct tipc_media *media; lc = (struct tipc_link_config *)TLV_DATA(msg->req); media = tipc_media_find(lc->name); if (media) { cmd->doit = &tipc_nl_media_set; return tipc_nl_compat_media_set(skb, msg); } bearer = tipc_bearer_find(msg->net, lc->name); if (bearer) { cmd->doit = &tipc_nl_bearer_set; return tipc_nl_compat_bearer_set(skb, msg); } return __tipc_nl_compat_link_set(skb, msg); } static int tipc_nl_compat_link_reset_stats(struct tipc_nl_compat_cmd_doit *cmd, struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { char *name; struct nlattr *link; name = (char *)TLV_DATA(msg->req); link = nla_nest_start(skb, TIPC_NLA_LINK); if (!link) return -EMSGSIZE; if (nla_put_string(skb, TIPC_NLA_LINK_NAME, name)) return -EMSGSIZE; nla_nest_end(skb, link); return 0; } static int tipc_nl_compat_name_table_dump_header(struct tipc_nl_compat_msg *msg) { int i; u32 depth; struct tipc_name_table_query *ntq; static const char * const header[] = { "Type ", "Lower Upper ", "Port Identity ", "Publication Scope" }; ntq = (struct tipc_name_table_query *)TLV_DATA(msg->req); depth = ntohl(ntq->depth); if (depth > 4) depth = 4; for (i = 0; i < depth; i++) tipc_tlv_sprintf(msg->rep, header[i]); tipc_tlv_sprintf(msg->rep, "\n"); return 0; } static int tipc_nl_compat_name_table_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { char port_str[27]; struct tipc_name_table_query *ntq; struct nlattr *nt[TIPC_NLA_NAME_TABLE_MAX + 1]; struct nlattr *publ[TIPC_NLA_PUBL_MAX + 1]; u32 node, depth, type, lowbound, upbound; static const char * const scope_str[] = {"", " zone", " cluster", " node"}; int err; if (!attrs[TIPC_NLA_NAME_TABLE]) return -EINVAL; err = nla_parse_nested(nt, TIPC_NLA_NAME_TABLE_MAX, attrs[TIPC_NLA_NAME_TABLE], NULL); if (err) return err; if (!nt[TIPC_NLA_NAME_TABLE_PUBL]) return -EINVAL; err = nla_parse_nested(publ, TIPC_NLA_PUBL_MAX, nt[TIPC_NLA_NAME_TABLE_PUBL], NULL); if (err) return err; ntq = (struct tipc_name_table_query *)TLV_DATA(msg->req); depth = ntohl(ntq->depth); type = ntohl(ntq->type); lowbound = ntohl(ntq->lowbound); upbound = ntohl(ntq->upbound); if (!(depth & TIPC_NTQ_ALLTYPES) && (type != nla_get_u32(publ[TIPC_NLA_PUBL_TYPE]))) return 0; if (lowbound && (lowbound > nla_get_u32(publ[TIPC_NLA_PUBL_UPPER]))) return 0; if (upbound && (upbound < nla_get_u32(publ[TIPC_NLA_PUBL_LOWER]))) return 0; tipc_tlv_sprintf(msg->rep, "%-10u ", nla_get_u32(publ[TIPC_NLA_PUBL_TYPE])); if (depth == 1) goto out; tipc_tlv_sprintf(msg->rep, "%-10u %-10u ", nla_get_u32(publ[TIPC_NLA_PUBL_LOWER]), nla_get_u32(publ[TIPC_NLA_PUBL_UPPER])); if (depth == 2) goto out; node = nla_get_u32(publ[TIPC_NLA_PUBL_NODE]); sprintf(port_str, "<%u.%u.%u:%u>", tipc_zone(node), tipc_cluster(node), tipc_node(node), nla_get_u32(publ[TIPC_NLA_PUBL_REF])); tipc_tlv_sprintf(msg->rep, "%-26s ", port_str); if (depth == 3) goto out; tipc_tlv_sprintf(msg->rep, "%-10u %s", nla_get_u32(publ[TIPC_NLA_PUBL_KEY]), scope_str[nla_get_u32(publ[TIPC_NLA_PUBL_SCOPE])]); out: tipc_tlv_sprintf(msg->rep, "\n"); return 0; } static int __tipc_nl_compat_publ_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { u32 type, lower, upper; struct nlattr *publ[TIPC_NLA_PUBL_MAX + 1]; int err; if (!attrs[TIPC_NLA_PUBL]) return -EINVAL; err = nla_parse_nested(publ, TIPC_NLA_PUBL_MAX, attrs[TIPC_NLA_PUBL], NULL); if (err) return err; type = nla_get_u32(publ[TIPC_NLA_PUBL_TYPE]); lower = nla_get_u32(publ[TIPC_NLA_PUBL_LOWER]); upper = nla_get_u32(publ[TIPC_NLA_PUBL_UPPER]); if (lower == upper) tipc_tlv_sprintf(msg->rep, " {%u,%u}", type, lower); else tipc_tlv_sprintf(msg->rep, " {%u,%u,%u}", type, lower, upper); return 0; } static int tipc_nl_compat_publ_dump(struct tipc_nl_compat_msg *msg, u32 sock) { int err; void *hdr; struct nlattr *nest; struct sk_buff *args; struct tipc_nl_compat_cmd_dump dump; args = nlmsg_new(NLMSG_GOODSIZE, GFP_KERNEL); if (!args) return -ENOMEM; hdr = genlmsg_put(args, 0, 0, &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET); nest = nla_nest_start(args, TIPC_NLA_SOCK); if (!nest) { kfree_skb(args); return -EMSGSIZE; } if (nla_put_u32(args, TIPC_NLA_SOCK_REF, sock)) { kfree_skb(args); return -EMSGSIZE; } nla_nest_end(args, nest); genlmsg_end(args, hdr); dump.dumpit = tipc_nl_publ_dump; dump.format = __tipc_nl_compat_publ_dump; err = __tipc_nl_compat_dumpit(&dump, msg, args); kfree_skb(args); return err; } static int tipc_nl_compat_sk_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { int err; u32 sock_ref; struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1]; if (!attrs[TIPC_NLA_SOCK]) return -EINVAL; err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX, attrs[TIPC_NLA_SOCK], NULL); if (err) return err; sock_ref = nla_get_u32(sock[TIPC_NLA_SOCK_REF]); tipc_tlv_sprintf(msg->rep, "%u:", sock_ref); if (sock[TIPC_NLA_SOCK_CON]) { u32 node; struct nlattr *con[TIPC_NLA_CON_MAX + 1]; nla_parse_nested(con, TIPC_NLA_CON_MAX, sock[TIPC_NLA_SOCK_CON], NULL); node = nla_get_u32(con[TIPC_NLA_CON_NODE]); tipc_tlv_sprintf(msg->rep, " connected to <%u.%u.%u:%u>", tipc_zone(node), tipc_cluster(node), tipc_node(node), nla_get_u32(con[TIPC_NLA_CON_SOCK])); if (con[TIPC_NLA_CON_FLAG]) tipc_tlv_sprintf(msg->rep, " via {%u,%u}\n", nla_get_u32(con[TIPC_NLA_CON_TYPE]), nla_get_u32(con[TIPC_NLA_CON_INST])); else tipc_tlv_sprintf(msg->rep, "\n"); } else if (sock[TIPC_NLA_SOCK_HAS_PUBL]) { tipc_tlv_sprintf(msg->rep, " bound to"); err = tipc_nl_compat_publ_dump(msg, sock_ref); if (err) return err; } tipc_tlv_sprintf(msg->rep, "\n"); return 0; } static int tipc_nl_compat_media_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { struct nlattr *media[TIPC_NLA_MEDIA_MAX + 1]; int err; if (!attrs[TIPC_NLA_MEDIA]) return -EINVAL; err = nla_parse_nested(media, TIPC_NLA_MEDIA_MAX, attrs[TIPC_NLA_MEDIA], NULL); if (err) return err; return tipc_add_tlv(msg->rep, TIPC_TLV_MEDIA_NAME, nla_data(media[TIPC_NLA_MEDIA_NAME]), nla_len(media[TIPC_NLA_MEDIA_NAME])); } static int tipc_nl_compat_node_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { struct tipc_node_info node_info; struct nlattr *node[TIPC_NLA_NODE_MAX + 1]; int err; if (!attrs[TIPC_NLA_NODE]) return -EINVAL; err = nla_parse_nested(node, TIPC_NLA_NODE_MAX, attrs[TIPC_NLA_NODE], NULL); if (err) return err; node_info.addr = htonl(nla_get_u32(node[TIPC_NLA_NODE_ADDR])); node_info.up = htonl(nla_get_flag(node[TIPC_NLA_NODE_UP])); return tipc_add_tlv(msg->rep, TIPC_TLV_NODE_INFO, &node_info, sizeof(node_info)); } static int tipc_nl_compat_net_set(struct tipc_nl_compat_cmd_doit *cmd, struct sk_buff *skb, struct tipc_nl_compat_msg *msg) { u32 val; struct nlattr *net; val = ntohl(*(__be32 *)TLV_DATA(msg->req)); net = nla_nest_start(skb, TIPC_NLA_NET); if (!net) return -EMSGSIZE; if (msg->cmd == TIPC_CMD_SET_NODE_ADDR) { if (nla_put_u32(skb, TIPC_NLA_NET_ADDR, val)) return -EMSGSIZE; } else if (msg->cmd == TIPC_CMD_SET_NETID) { if (nla_put_u32(skb, TIPC_NLA_NET_ID, val)) return -EMSGSIZE; } nla_nest_end(skb, net); return 0; } static int tipc_nl_compat_net_dump(struct tipc_nl_compat_msg *msg, struct nlattr **attrs) { __be32 id; struct nlattr *net[TIPC_NLA_NET_MAX + 1]; int err; if (!attrs[TIPC_NLA_NET]) return -EINVAL; err = nla_parse_nested(net, TIPC_NLA_NET_MAX, attrs[TIPC_NLA_NET], NULL); if (err) return err; id = htonl(nla_get_u32(net[TIPC_NLA_NET_ID])); return tipc_add_tlv(msg->rep, TIPC_TLV_UNSIGNED, &id, sizeof(id)); } static int tipc_cmd_show_stats_compat(struct tipc_nl_compat_msg *msg) { msg->rep = tipc_tlv_alloc(ULTRA_STRING_MAX_LEN); if (!msg->rep) return -ENOMEM; tipc_tlv_init(msg->rep, TIPC_TLV_ULTRA_STRING); tipc_tlv_sprintf(msg->rep, "TIPC version " TIPC_MOD_VER "\n"); return 0; } static int tipc_nl_compat_handle(struct tipc_nl_compat_msg *msg) { struct tipc_nl_compat_cmd_dump dump; struct tipc_nl_compat_cmd_doit doit; memset(&dump, 0, sizeof(dump)); memset(&doit, 0, sizeof(doit)); switch (msg->cmd) { case TIPC_CMD_NOOP: msg->rep = tipc_tlv_alloc(0); if (!msg->rep) return -ENOMEM; return 0; case TIPC_CMD_GET_BEARER_NAMES: msg->rep_size = MAX_BEARERS * TLV_SPACE(TIPC_MAX_BEARER_NAME); dump.dumpit = tipc_nl_bearer_dump; dump.format = tipc_nl_compat_bearer_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_ENABLE_BEARER: msg->req_type = TIPC_TLV_BEARER_CONFIG; doit.doit = tipc_nl_bearer_enable; doit.transcode = tipc_nl_compat_bearer_enable; return tipc_nl_compat_doit(&doit, msg); case TIPC_CMD_DISABLE_BEARER: msg->req_type = TIPC_TLV_BEARER_NAME; doit.doit = tipc_nl_bearer_disable; doit.transcode = tipc_nl_compat_bearer_disable; return tipc_nl_compat_doit(&doit, msg); case TIPC_CMD_SHOW_LINK_STATS: msg->req_type = TIPC_TLV_LINK_NAME; msg->rep_size = ULTRA_STRING_MAX_LEN; msg->rep_type = TIPC_TLV_ULTRA_STRING; dump.dumpit = tipc_nl_node_dump_link; dump.format = tipc_nl_compat_link_stat_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_GET_LINKS: msg->req_type = TIPC_TLV_NET_ADDR; msg->rep_size = ULTRA_STRING_MAX_LEN; dump.dumpit = tipc_nl_node_dump_link; dump.format = tipc_nl_compat_link_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_SET_LINK_TOL: case TIPC_CMD_SET_LINK_PRI: case TIPC_CMD_SET_LINK_WINDOW: msg->req_type = TIPC_TLV_LINK_CONFIG; doit.doit = tipc_nl_node_set_link; doit.transcode = tipc_nl_compat_link_set; return tipc_nl_compat_doit(&doit, msg); case TIPC_CMD_RESET_LINK_STATS: msg->req_type = TIPC_TLV_LINK_NAME; doit.doit = tipc_nl_node_reset_link_stats; doit.transcode = tipc_nl_compat_link_reset_stats; return tipc_nl_compat_doit(&doit, msg); case TIPC_CMD_SHOW_NAME_TABLE: msg->req_type = TIPC_TLV_NAME_TBL_QUERY; msg->rep_size = ULTRA_STRING_MAX_LEN; msg->rep_type = TIPC_TLV_ULTRA_STRING; dump.header = tipc_nl_compat_name_table_dump_header; dump.dumpit = tipc_nl_name_table_dump; dump.format = tipc_nl_compat_name_table_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_SHOW_PORTS: msg->rep_size = ULTRA_STRING_MAX_LEN; msg->rep_type = TIPC_TLV_ULTRA_STRING; dump.dumpit = tipc_nl_sk_dump; dump.format = tipc_nl_compat_sk_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_GET_MEDIA_NAMES: msg->rep_size = MAX_MEDIA * TLV_SPACE(TIPC_MAX_MEDIA_NAME); dump.dumpit = tipc_nl_media_dump; dump.format = tipc_nl_compat_media_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_GET_NODES: msg->rep_size = ULTRA_STRING_MAX_LEN; dump.dumpit = tipc_nl_node_dump; dump.format = tipc_nl_compat_node_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_SET_NODE_ADDR: msg->req_type = TIPC_TLV_NET_ADDR; doit.doit = tipc_nl_net_set; doit.transcode = tipc_nl_compat_net_set; return tipc_nl_compat_doit(&doit, msg); case TIPC_CMD_SET_NETID: msg->req_type = TIPC_TLV_UNSIGNED; doit.doit = tipc_nl_net_set; doit.transcode = tipc_nl_compat_net_set; return tipc_nl_compat_doit(&doit, msg); case TIPC_CMD_GET_NETID: msg->rep_size = sizeof(u32); dump.dumpit = tipc_nl_net_dump; dump.format = tipc_nl_compat_net_dump; return tipc_nl_compat_dumpit(&dump, msg); case TIPC_CMD_SHOW_STATS: return tipc_cmd_show_stats_compat(msg); } return -EOPNOTSUPP; } static int tipc_nl_compat_recv(struct sk_buff *skb, struct genl_info *info) { int err; int len; struct tipc_nl_compat_msg msg; struct nlmsghdr *req_nlh; struct nlmsghdr *rep_nlh; struct tipc_genlmsghdr *req_userhdr = info->userhdr; memset(&msg, 0, sizeof(msg)); req_nlh = (struct nlmsghdr *)skb->data; msg.req = nlmsg_data(req_nlh) + GENL_HDRLEN + TIPC_GENL_HDRLEN; msg.cmd = req_userhdr->cmd; msg.net = genl_info_net(info); msg.dst_sk = skb->sk; if ((msg.cmd & 0xC000) && (!netlink_net_capable(skb, CAP_NET_ADMIN))) { msg.rep = tipc_get_err_tlv(TIPC_CFG_NOT_NET_ADMIN); err = -EACCES; goto send; } len = nlmsg_attrlen(req_nlh, GENL_HDRLEN + TIPC_GENL_HDRLEN); if (len && !TLV_OK(msg.req, len)) { msg.rep = tipc_get_err_tlv(TIPC_CFG_NOT_SUPPORTED); err = -EOPNOTSUPP; goto send; } err = tipc_nl_compat_handle(&msg); if ((err == -EOPNOTSUPP) || (err == -EPERM)) msg.rep = tipc_get_err_tlv(TIPC_CFG_NOT_SUPPORTED); else if (err == -EINVAL) msg.rep = tipc_get_err_tlv(TIPC_CFG_TLV_ERROR); send: if (!msg.rep) return err; len = nlmsg_total_size(GENL_HDRLEN + TIPC_GENL_HDRLEN); skb_push(msg.rep, len); rep_nlh = nlmsg_hdr(msg.rep); memcpy(rep_nlh, info->nlhdr, len); rep_nlh->nlmsg_len = msg.rep->len; genlmsg_unicast(msg.net, msg.rep, NETLINK_CB(skb).portid); return err; } static struct genl_family tipc_genl_compat_family = { .id = GENL_ID_GENERATE, .name = TIPC_GENL_NAME, .version = TIPC_GENL_VERSION, .hdrsize = TIPC_GENL_HDRLEN, .maxattr = 0, .netnsok = true, }; static struct genl_ops tipc_genl_compat_ops[] = { { .cmd = TIPC_GENL_CMD, .doit = tipc_nl_compat_recv, }, }; int tipc_netlink_compat_start(void) { int res; res = genl_register_family_with_ops(&tipc_genl_compat_family, tipc_genl_compat_ops); if (res) { pr_err("Failed to register legacy compat interface\n"); return res; } return 0; } void tipc_netlink_compat_stop(void) { genl_unregister_family(&tipc_genl_compat_family); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_5098_0
crossvul-cpp_data_bad_5690_0
/* * af_llc.c - LLC User Interface SAPs * Description: * Functions in this module are implementation of socket based llc * communications for the Linux operating system. Support of llc class * one and class two is provided via SOCK_DGRAM and SOCK_STREAM * respectively. * * An llc2 connection is (mac + sap), only one llc2 sap connection * is allowed per mac. Though one sap may have multiple mac + sap * connections. * * Copyright (c) 2001 by Jay Schulist <jschlst@samba.org> * 2002-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * This program can be redistributed or modified under the terms of the * GNU General Public License as published by the Free Software Foundation. * This program is distributed without any warranty or implied warranty * of merchantability or fitness for a particular purpose. * * See the GNU General Public License for more details. */ #include <linux/compiler.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/init.h> #include <linux/slab.h> #include <net/llc.h> #include <net/llc_sap.h> #include <net/llc_pdu.h> #include <net/llc_conn.h> #include <net/tcp_states.h> /* remember: uninitialized global data is zeroed because its in .bss */ static u16 llc_ui_sap_last_autoport = LLC_SAP_DYN_START; static u16 llc_ui_sap_link_no_max[256]; static struct sockaddr_llc llc_ui_addrnull; static const struct proto_ops llc_ui_ops; static int llc_ui_wait_for_conn(struct sock *sk, long timeout); static int llc_ui_wait_for_disc(struct sock *sk, long timeout); static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout); #if 0 #define dprintk(args...) printk(KERN_DEBUG args) #else #define dprintk(args...) #endif /* Maybe we'll add some more in the future. */ #define LLC_CMSG_PKTINFO 1 /** * llc_ui_next_link_no - return the next unused link number for a sap * @sap: Address of sap to get link number from. * * Return the next unused link number for a given sap. */ static inline u16 llc_ui_next_link_no(int sap) { return llc_ui_sap_link_no_max[sap]++; } /** * llc_proto_type - return eth protocol for ARP header type * @arphrd: ARP header type. * * Given an ARP header type return the corresponding ethernet protocol. */ static inline __be16 llc_proto_type(u16 arphrd) { return htons(ETH_P_802_2); } /** * llc_ui_addr_null - determines if a address structure is null * @addr: Address to test if null. */ static inline u8 llc_ui_addr_null(struct sockaddr_llc *addr) { return !memcmp(addr, &llc_ui_addrnull, sizeof(*addr)); } /** * llc_ui_header_len - return length of llc header based on operation * @sk: Socket which contains a valid llc socket type. * @addr: Complete sockaddr_llc structure received from the user. * * Provide the length of the llc header depending on what kind of * operation the user would like to perform and the type of socket. * Returns the correct llc header length. */ static inline u8 llc_ui_header_len(struct sock *sk, struct sockaddr_llc *addr) { u8 rc = LLC_PDU_LEN_U; if (addr->sllc_test || addr->sllc_xid) rc = LLC_PDU_LEN_U; else if (sk->sk_type == SOCK_STREAM) rc = LLC_PDU_LEN_I; return rc; } /** * llc_ui_send_data - send data via reliable llc2 connection * @sk: Connection the socket is using. * @skb: Data the user wishes to send. * @noblock: can we block waiting for data? * * Send data via reliable llc2 connection. * Returns 0 upon success, non-zero if action did not succeed. */ static int llc_ui_send_data(struct sock* sk, struct sk_buff *skb, int noblock) { struct llc_sock* llc = llc_sk(sk); int rc = 0; if (unlikely(llc_data_accept_state(llc->state) || llc->remote_busy_flag || llc->p_flag)) { long timeout = sock_sndtimeo(sk, noblock); rc = llc_ui_wait_for_busy_core(sk, timeout); } if (unlikely(!rc)) rc = llc_build_and_send_pkt(sk, skb); return rc; } static void llc_ui_sk_init(struct socket *sock, struct sock *sk) { sock_graft(sk, sock); sk->sk_type = sock->type; sock->ops = &llc_ui_ops; } static struct proto llc_proto = { .name = "LLC", .owner = THIS_MODULE, .obj_size = sizeof(struct llc_sock), .slab_flags = SLAB_DESTROY_BY_RCU, }; /** * llc_ui_create - alloc and init a new llc_ui socket * @net: network namespace (must be default network) * @sock: Socket to initialize and attach allocated sk to. * @protocol: Unused. * @kern: on behalf of kernel or userspace * * Allocate and initialize a new llc_ui socket, validate the user wants a * socket type we have available. * Returns 0 upon success, negative upon failure. */ static int llc_ui_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; int rc = -ESOCKTNOSUPPORT; if (!ns_capable(net->user_ns, CAP_NET_RAW)) return -EPERM; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; if (likely(sock->type == SOCK_DGRAM || sock->type == SOCK_STREAM)) { rc = -ENOMEM; sk = llc_sk_alloc(net, PF_LLC, GFP_KERNEL, &llc_proto); if (sk) { rc = 0; llc_ui_sk_init(sock, sk); } } return rc; } /** * llc_ui_release - shutdown socket * @sock: Socket to release. * * Shutdown and deallocate an existing socket. */ static int llc_ui_release(struct socket *sock) { struct sock *sk = sock->sk; struct llc_sock *llc; if (unlikely(sk == NULL)) goto out; sock_hold(sk); lock_sock(sk); llc = llc_sk(sk); dprintk("%s: closing local(%02X) remote(%02X)\n", __func__, llc->laddr.lsap, llc->daddr.lsap); if (!llc_send_disc(sk)) llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo); if (!sock_flag(sk, SOCK_ZAPPED)) llc_sap_remove_socket(llc->sap, sk); release_sock(sk); if (llc->dev) dev_put(llc->dev); sock_put(sk); llc_sk_free(sk); out: return 0; } /** * llc_ui_autoport - provide dynamically allocate SAP number * * Provide the caller with a dynamically allocated SAP number according * to the rules that are set in this function. Returns: 0, upon failure, * SAP number otherwise. */ static int llc_ui_autoport(void) { struct llc_sap *sap; int i, tries = 0; while (tries < LLC_SAP_DYN_TRIES) { for (i = llc_ui_sap_last_autoport; i < LLC_SAP_DYN_STOP; i += 2) { sap = llc_sap_find(i); if (!sap) { llc_ui_sap_last_autoport = i + 2; goto out; } llc_sap_put(sap); } llc_ui_sap_last_autoport = LLC_SAP_DYN_START; tries++; } i = 0; out: return i; } /** * llc_ui_autobind - automatically bind a socket to a sap * @sock: socket to bind * @addr: address to connect to * * Used by llc_ui_connect and llc_ui_sendmsg when the user hasn't * specifically used llc_ui_bind to bind to an specific address/sap * * Returns: 0 upon success, negative otherwise. */ static int llc_ui_autobind(struct socket *sock, struct sockaddr_llc *addr) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct llc_sap *sap; int rc = -EINVAL; if (!sock_flag(sk, SOCK_ZAPPED)) goto out; rc = -ENODEV; if (sk->sk_bound_dev_if) { llc->dev = dev_get_by_index(&init_net, sk->sk_bound_dev_if); if (llc->dev && addr->sllc_arphrd != llc->dev->type) { dev_put(llc->dev); llc->dev = NULL; } } else llc->dev = dev_getfirstbyhwtype(&init_net, addr->sllc_arphrd); if (!llc->dev) goto out; rc = -EUSERS; llc->laddr.lsap = llc_ui_autoport(); if (!llc->laddr.lsap) goto out; rc = -EBUSY; /* some other network layer is using the sap */ sap = llc_sap_open(llc->laddr.lsap, NULL); if (!sap) goto out; memcpy(llc->laddr.mac, llc->dev->dev_addr, IFHWADDRLEN); memcpy(&llc->addr, addr, sizeof(llc->addr)); /* assign new connection to its SAP */ llc_sap_add_socket(sap, sk); sock_reset_flag(sk, SOCK_ZAPPED); rc = 0; out: return rc; } /** * llc_ui_bind - bind a socket to a specific address. * @sock: Socket to bind an address to. * @uaddr: Address the user wants the socket bound to. * @addrlen: Length of the uaddr structure. * * Bind a socket to a specific address. For llc a user is able to bind to * a specific sap only or mac + sap. * If the user desires to bind to a specific mac + sap, it is possible to * have multiple sap connections via multiple macs. * Bind and autobind for that matter must enforce the correct sap usage * otherwise all hell will break loose. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_bind(struct socket *sock, struct sockaddr *uaddr, int addrlen) { struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct llc_sap *sap; int rc = -EINVAL; dprintk("%s: binding %02X\n", __func__, addr->sllc_sap); if (unlikely(!sock_flag(sk, SOCK_ZAPPED) || addrlen != sizeof(*addr))) goto out; rc = -EAFNOSUPPORT; if (unlikely(addr->sllc_family != AF_LLC)) goto out; rc = -ENODEV; rcu_read_lock(); if (sk->sk_bound_dev_if) { llc->dev = dev_get_by_index_rcu(&init_net, sk->sk_bound_dev_if); if (llc->dev) { if (!addr->sllc_arphrd) addr->sllc_arphrd = llc->dev->type; if (llc_mac_null(addr->sllc_mac)) memcpy(addr->sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); if (addr->sllc_arphrd != llc->dev->type || !llc_mac_match(addr->sllc_mac, llc->dev->dev_addr)) { rc = -EINVAL; llc->dev = NULL; } } } else llc->dev = dev_getbyhwaddr_rcu(&init_net, addr->sllc_arphrd, addr->sllc_mac); if (llc->dev) dev_hold(llc->dev); rcu_read_unlock(); if (!llc->dev) goto out; if (!addr->sllc_sap) { rc = -EUSERS; addr->sllc_sap = llc_ui_autoport(); if (!addr->sllc_sap) goto out; } sap = llc_sap_find(addr->sllc_sap); if (!sap) { sap = llc_sap_open(addr->sllc_sap, NULL); rc = -EBUSY; /* some other network layer is using the sap */ if (!sap) goto out; } else { struct llc_addr laddr, daddr; struct sock *ask; memset(&laddr, 0, sizeof(laddr)); memset(&daddr, 0, sizeof(daddr)); /* * FIXME: check if the address is multicast, * only SOCK_DGRAM can do this. */ memcpy(laddr.mac, addr->sllc_mac, IFHWADDRLEN); laddr.lsap = addr->sllc_sap; rc = -EADDRINUSE; /* mac + sap clash. */ ask = llc_lookup_established(sap, &daddr, &laddr); if (ask) { sock_put(ask); goto out_put; } } llc->laddr.lsap = addr->sllc_sap; memcpy(llc->laddr.mac, addr->sllc_mac, IFHWADDRLEN); memcpy(&llc->addr, addr, sizeof(llc->addr)); /* assign new connection to its SAP */ llc_sap_add_socket(sap, sk); sock_reset_flag(sk, SOCK_ZAPPED); rc = 0; out_put: llc_sap_put(sap); out: return rc; } /** * llc_ui_shutdown - shutdown a connect llc2 socket. * @sock: Socket to shutdown. * @how: What part of the socket to shutdown. * * Shutdown a connected llc2 socket. Currently this function only supports * shutting down both sends and receives (2), we could probably make this * function such that a user can shutdown only half the connection but not * right now. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int rc = -ENOTCONN; lock_sock(sk); if (unlikely(sk->sk_state != TCP_ESTABLISHED)) goto out; rc = -EINVAL; if (how != 2) goto out; rc = llc_send_disc(sk); if (!rc) rc = llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo); /* Wake up anyone sleeping in poll */ sk->sk_state_change(sk); out: release_sock(sk); return rc; } /** * llc_ui_connect - Connect to a remote llc2 mac + sap. * @sock: Socket which will be connected to the remote destination. * @uaddr: Remote and possibly the local address of the new connection. * @addrlen: Size of uaddr structure. * @flags: Operational flags specified by the user. * * Connect to a remote llc2 mac + sap. The caller must specify the * destination mac and address to connect to. If the user hasn't previously * called bind(2) with a smac the address of the first interface of the * specified arp type will be used. * This function will autobind if user did not previously call bind. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_connect(struct socket *sock, struct sockaddr *uaddr, int addrlen, int flags) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; int rc = -EINVAL; lock_sock(sk); if (unlikely(addrlen != sizeof(*addr))) goto out; rc = -EAFNOSUPPORT; if (unlikely(addr->sllc_family != AF_LLC)) goto out; if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EALREADY; if (unlikely(sock->state == SS_CONNECTING)) goto out; /* bind connection to sap if user hasn't done it. */ if (sock_flag(sk, SOCK_ZAPPED)) { /* bind to sap with null dev, exclusive */ rc = llc_ui_autobind(sock, addr); if (rc) goto out; } llc->daddr.lsap = addr->sllc_sap; memcpy(llc->daddr.mac, addr->sllc_mac, IFHWADDRLEN); sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; llc->link = llc_ui_next_link_no(llc->sap->laddr.lsap); rc = llc_establish_connection(sk, llc->dev->dev_addr, addr->sllc_mac, addr->sllc_sap); if (rc) { dprintk("%s: llc_ui_send_conn failed :-(\n", __func__); sock->state = SS_UNCONNECTED; sk->sk_state = TCP_CLOSE; goto out; } if (sk->sk_state == TCP_SYN_SENT) { const long timeo = sock_sndtimeo(sk, flags & O_NONBLOCK); if (!timeo || !llc_ui_wait_for_conn(sk, timeo)) goto out; rc = sock_intr_errno(timeo); if (signal_pending(current)) goto out; } if (sk->sk_state == TCP_CLOSE) goto sock_error; sock->state = SS_CONNECTED; rc = 0; out: release_sock(sk); return rc; sock_error: rc = sock_error(sk) ? : -ECONNABORTED; sock->state = SS_UNCONNECTED; goto out; } /** * llc_ui_listen - allow a normal socket to accept incoming connections * @sock: Socket to allow incoming connections on. * @backlog: Number of connections to queue. * * Allow a normal socket to accept incoming connections. * Returns 0 upon success, negative otherwise. */ static int llc_ui_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int rc = -EINVAL; lock_sock(sk); if (unlikely(sock->state != SS_UNCONNECTED)) goto out; rc = -EOPNOTSUPP; if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EAGAIN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; rc = 0; if (!(unsigned int)backlog) /* BSDism */ backlog = 1; sk->sk_max_ack_backlog = backlog; if (sk->sk_state != TCP_LISTEN) { sk->sk_ack_backlog = 0; sk->sk_state = TCP_LISTEN; } sk->sk_socket->flags |= __SO_ACCEPTCON; out: release_sock(sk); return rc; } static int llc_ui_wait_for_disc(struct sock *sk, long timeout) { DEFINE_WAIT(wait); int rc = 0; while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk_wait_event(sk, &timeout, sk->sk_state == TCP_CLOSE)) break; rc = -ERESTARTSYS; if (signal_pending(current)) break; rc = -EAGAIN; if (!timeout) break; rc = 0; } finish_wait(sk_sleep(sk), &wait); return rc; } static int llc_ui_wait_for_conn(struct sock *sk, long timeout) { DEFINE_WAIT(wait); while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk_wait_event(sk, &timeout, sk->sk_state != TCP_SYN_SENT)) break; if (signal_pending(current) || !timeout) break; } finish_wait(sk_sleep(sk), &wait); return timeout; } static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout) { DEFINE_WAIT(wait); struct llc_sock *llc = llc_sk(sk); int rc; while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); rc = 0; if (sk_wait_event(sk, &timeout, (sk->sk_shutdown & RCV_SHUTDOWN) || (!llc_data_accept_state(llc->state) && !llc->remote_busy_flag && !llc->p_flag))) break; rc = -ERESTARTSYS; if (signal_pending(current)) break; rc = -EAGAIN; if (!timeout) break; } finish_wait(sk_sleep(sk), &wait); return rc; } static int llc_wait_data(struct sock *sk, long timeo) { int rc; while (1) { /* * POSIX 1003.1g mandates this order. */ rc = sock_error(sk); if (rc) break; rc = 0; if (sk->sk_shutdown & RCV_SHUTDOWN) break; rc = -EAGAIN; if (!timeo) break; rc = sock_intr_errno(timeo); if (signal_pending(current)) break; rc = 0; if (sk_wait_data(sk, &timeo)) break; } return rc; } static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } } /** * llc_ui_accept - accept a new incoming connection. * @sock: Socket which connections arrive on. * @newsock: Socket to move incoming connection to. * @flags: User specified operational flags. * * Accept a new incoming connection. * Returns 0 upon success, negative otherwise. */ static int llc_ui_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk, *newsk; struct llc_sock *llc, *newllc; struct sk_buff *skb; int rc = -EOPNOTSUPP; dprintk("%s: accepting on %02X\n", __func__, llc_sk(sk)->laddr.lsap); lock_sock(sk); if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EINVAL; if (unlikely(sock->state != SS_UNCONNECTED || sk->sk_state != TCP_LISTEN)) goto out; /* wait for a connection to arrive. */ if (skb_queue_empty(&sk->sk_receive_queue)) { rc = llc_wait_data(sk, sk->sk_rcvtimeo); if (rc) goto out; } dprintk("%s: got a new connection on %02X\n", __func__, llc_sk(sk)->laddr.lsap); skb = skb_dequeue(&sk->sk_receive_queue); rc = -EINVAL; if (!skb->sk) goto frees; rc = 0; newsk = skb->sk; /* attach connection to a new socket. */ llc_ui_sk_init(newsock, newsk); sock_reset_flag(newsk, SOCK_ZAPPED); newsk->sk_state = TCP_ESTABLISHED; newsock->state = SS_CONNECTED; llc = llc_sk(sk); newllc = llc_sk(newsk); memcpy(&newllc->addr, &llc->addr, sizeof(newllc->addr)); newllc->link = llc_ui_next_link_no(newllc->laddr.lsap); /* put original socket back into a clean listen state. */ sk->sk_state = TCP_LISTEN; sk->sk_ack_backlog--; dprintk("%s: ok success on %02X, client on %02X\n", __func__, llc_sk(sk)->addr.sllc_sap, newllc->daddr.lsap); frees: kfree_skb(skb); out: release_sock(sk); return rc; } /** * llc_ui_recvmsg - copy received data to the socket user. * @sock: Socket to copy data from. * @msg: Various user space related information. * @len: Size of user buffer. * @flags: User specified flags. * * Copy received data to the socket user. * Returns non-negative upon success, negative otherwise. */ static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; const int nonblock = flags & MSG_DONTWAIT; struct sk_buff *skb = NULL; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned long cpu_flags; size_t copied = 0; u32 peek_seq = 0; u32 *seq; unsigned long used; int target; /* Read at least this many bytes */ long timeo; lock_sock(sk); copied = -ENOTCONN; if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) goto out; timeo = sock_rcvtimeo(sk, nonblock); seq = &llc->copied_seq; if (flags & MSG_PEEK) { peek_seq = llc->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); copied = 0; do { u32 offset; /* * We need to check signals first, to get correct SIGURG * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { if (copied) break; copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } /* Next get a buffer. */ skb = skb_peek(&sk->sk_receive_queue); if (skb) { offset = *seq; goto found_ok_skb; } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || (flags & MSG_PEEK)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* * This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo); if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = llc->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; if (!(flags & MSG_TRUNC)) { int rc = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, used); if (rc) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; /* For non stream protcols we get one packet per recvmsg call */ if (sk->sk_type != SOCK_STREAM) goto copy_uaddr; if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } /* Partial read */ if (used + offset < skb->len) continue; } while (len > 0); out: release_sock(sk); return copied; copy_uaddr: if (uaddr != NULL && skb != NULL) { memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); msg->msg_namelen = sizeof(*uaddr); } if (llc_sk(sk)->cmsg_flags) llc_cmsg_rcv(msg, skb); if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } goto out; } /** * llc_ui_sendmsg - Transmit data provided by the socket user. * @sock: Socket to transmit data from. * @msg: Various user related information. * @len: Length of data to transmit. * * Transmit data provided by the socket user. * Returns non-negative upon success, negative otherwise. */ static int llc_ui_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct sockaddr_llc *addr = (struct sockaddr_llc *)msg->msg_name; int flags = msg->msg_flags; int noblock = flags & MSG_DONTWAIT; struct sk_buff *skb; size_t size = 0; int rc = -EINVAL, copied = 0, hdrlen; dprintk("%s: sending from %02X to %02X\n", __func__, llc->laddr.lsap, llc->daddr.lsap); lock_sock(sk); if (addr) { if (msg->msg_namelen < sizeof(*addr)) goto release; } else { if (llc_ui_addr_null(&llc->addr)) goto release; addr = &llc->addr; } /* must bind connection to sap if user hasn't done it. */ if (sock_flag(sk, SOCK_ZAPPED)) { /* bind to sap with null dev, exclusive. */ rc = llc_ui_autobind(sock, addr); if (rc) goto release; } hdrlen = llc->dev->hard_header_len + llc_ui_header_len(sk, addr); size = hdrlen + len; if (size > llc->dev->mtu) size = llc->dev->mtu; copied = size - hdrlen; release_sock(sk); skb = sock_alloc_send_skb(sk, size, noblock, &rc); lock_sock(sk); if (!skb) goto release; skb->dev = llc->dev; skb->protocol = llc_proto_type(addr->sllc_arphrd); skb_reserve(skb, hdrlen); rc = memcpy_fromiovec(skb_put(skb, copied), msg->msg_iov, copied); if (rc) goto out; if (sk->sk_type == SOCK_DGRAM || addr->sllc_ua) { llc_build_and_send_ui_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } if (addr->sllc_test) { llc_build_and_send_test_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } if (addr->sllc_xid) { llc_build_and_send_xid_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } rc = -ENOPROTOOPT; if (!(sk->sk_type == SOCK_STREAM && !addr->sllc_ua)) goto out; rc = llc_ui_send_data(sk, skb, noblock); out: if (rc) { kfree_skb(skb); release: dprintk("%s: failed sending from %02X to %02X: %d\n", __func__, llc->laddr.lsap, llc->daddr.lsap, rc); } release_sock(sk); return rc ? : copied; } /** * llc_ui_getname - return the address info of a socket * @sock: Socket to get address of. * @uaddr: Address structure to return information. * @uaddrlen: Length of address structure. * @peer: Does user want local or remote address information. * * Return the address information of a socket. */ static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = -EBADF; memset(&sllc, 0, sizeof(sllc)); lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; } /** * llc_ui_ioctl - io controls for PF_LLC * @sock: Socket to get/set info * @cmd: command * @arg: optional argument for cmd * * get/set info on llc sockets */ static int llc_ui_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -ENOIOCTLCMD; } /** * llc_ui_setsockopt - set various connection specific parameters. * @sock: Socket to set options on. * @level: Socket level user is requesting operations on. * @optname: Operation name. * @optval: User provided operation data. * @optlen: Length of optval. * * Set various connection specific parameters. */ static int llc_ui_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned int opt; int rc = -EINVAL; lock_sock(sk); if (unlikely(level != SOL_LLC || optlen != sizeof(int))) goto out; rc = get_user(opt, (int __user *)optval); if (rc) goto out; rc = -EINVAL; switch (optname) { case LLC_OPT_RETRY: if (opt > LLC_OPT_MAX_RETRY) goto out; llc->n2 = opt; break; case LLC_OPT_SIZE: if (opt > LLC_OPT_MAX_SIZE) goto out; llc->n1 = opt; break; case LLC_OPT_ACK_TMR_EXP: if (opt > LLC_OPT_MAX_ACK_TMR_EXP) goto out; llc->ack_timer.expire = opt * HZ; break; case LLC_OPT_P_TMR_EXP: if (opt > LLC_OPT_MAX_P_TMR_EXP) goto out; llc->pf_cycle_timer.expire = opt * HZ; break; case LLC_OPT_REJ_TMR_EXP: if (opt > LLC_OPT_MAX_REJ_TMR_EXP) goto out; llc->rej_sent_timer.expire = opt * HZ; break; case LLC_OPT_BUSY_TMR_EXP: if (opt > LLC_OPT_MAX_BUSY_TMR_EXP) goto out; llc->busy_state_timer.expire = opt * HZ; break; case LLC_OPT_TX_WIN: if (opt > LLC_OPT_MAX_WIN) goto out; llc->k = opt; break; case LLC_OPT_RX_WIN: if (opt > LLC_OPT_MAX_WIN) goto out; llc->rw = opt; break; case LLC_OPT_PKTINFO: if (opt) llc->cmsg_flags |= LLC_CMSG_PKTINFO; else llc->cmsg_flags &= ~LLC_CMSG_PKTINFO; break; default: rc = -ENOPROTOOPT; goto out; } rc = 0; out: release_sock(sk); return rc; } /** * llc_ui_getsockopt - get connection specific socket info * @sock: Socket to get information from. * @level: Socket level user is requesting operations on. * @optname: Operation name. * @optval: Variable to return operation data in. * @optlen: Length of optval. * * Get connection specific socket information. */ static int llc_ui_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int val = 0, len = 0, rc = -EINVAL; lock_sock(sk); if (unlikely(level != SOL_LLC)) goto out; rc = get_user(len, optlen); if (rc) goto out; rc = -EINVAL; if (len != sizeof(int)) goto out; switch (optname) { case LLC_OPT_RETRY: val = llc->n2; break; case LLC_OPT_SIZE: val = llc->n1; break; case LLC_OPT_ACK_TMR_EXP: val = llc->ack_timer.expire / HZ; break; case LLC_OPT_P_TMR_EXP: val = llc->pf_cycle_timer.expire / HZ; break; case LLC_OPT_REJ_TMR_EXP: val = llc->rej_sent_timer.expire / HZ; break; case LLC_OPT_BUSY_TMR_EXP: val = llc->busy_state_timer.expire / HZ; break; case LLC_OPT_TX_WIN: val = llc->k; break; case LLC_OPT_RX_WIN: val = llc->rw; break; case LLC_OPT_PKTINFO: val = (llc->cmsg_flags & LLC_CMSG_PKTINFO) != 0; break; default: rc = -ENOPROTOOPT; goto out; } rc = 0; if (put_user(len, optlen) || copy_to_user(optval, &val, len)) rc = -EFAULT; out: release_sock(sk); return rc; } static const struct net_proto_family llc_ui_family_ops = { .family = PF_LLC, .create = llc_ui_create, .owner = THIS_MODULE, }; static const struct proto_ops llc_ui_ops = { .family = PF_LLC, .owner = THIS_MODULE, .release = llc_ui_release, .bind = llc_ui_bind, .connect = llc_ui_connect, .socketpair = sock_no_socketpair, .accept = llc_ui_accept, .getname = llc_ui_getname, .poll = datagram_poll, .ioctl = llc_ui_ioctl, .listen = llc_ui_listen, .shutdown = llc_ui_shutdown, .setsockopt = llc_ui_setsockopt, .getsockopt = llc_ui_getsockopt, .sendmsg = llc_ui_sendmsg, .recvmsg = llc_ui_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const char llc_proc_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the proc_fs entries\n"; static const char llc_sysctl_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the sysctl entries\n"; static const char llc_sock_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the network family\n"; static int __init llc2_init(void) { int rc = proto_register(&llc_proto, 0); if (rc != 0) goto out; llc_build_offset_table(); llc_station_init(); llc_ui_sap_last_autoport = LLC_SAP_DYN_START; rc = llc_proc_init(); if (rc != 0) { printk(llc_proc_err_msg); goto out_station; } rc = llc_sysctl_init(); if (rc) { printk(llc_sysctl_err_msg); goto out_proc; } rc = sock_register(&llc_ui_family_ops); if (rc) { printk(llc_sock_err_msg); goto out_sysctl; } llc_add_pack(LLC_DEST_SAP, llc_sap_handler); llc_add_pack(LLC_DEST_CONN, llc_conn_handler); out: return rc; out_sysctl: llc_sysctl_exit(); out_proc: llc_proc_exit(); out_station: llc_station_exit(); proto_unregister(&llc_proto); goto out; } static void __exit llc2_exit(void) { llc_station_exit(); llc_remove_pack(LLC_DEST_SAP); llc_remove_pack(LLC_DEST_CONN); sock_unregister(PF_LLC); llc_proc_exit(); llc_sysctl_exit(); proto_unregister(&llc_proto); } module_init(llc2_init); module_exit(llc2_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Procom 1997, Jay Schullist 2001, Arnaldo C. Melo 2001-2003"); MODULE_DESCRIPTION("IEEE 802.2 PF_LLC support"); MODULE_ALIAS_NETPROTO(PF_LLC);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5690_0
crossvul-cpp_data_good_4240_3
// SPDX-License-Identifier: GPL-2.0 /* * This is a maximally equidistributed combined Tausworthe generator * based on code from GNU Scientific Library 1.5 (30 Jun 2004) * * lfsr113 version: * * x_n = (s1_n ^ s2_n ^ s3_n ^ s4_n) * * s1_{n+1} = (((s1_n & 4294967294) << 18) ^ (((s1_n << 6) ^ s1_n) >> 13)) * s2_{n+1} = (((s2_n & 4294967288) << 2) ^ (((s2_n << 2) ^ s2_n) >> 27)) * s3_{n+1} = (((s3_n & 4294967280) << 7) ^ (((s3_n << 13) ^ s3_n) >> 21)) * s4_{n+1} = (((s4_n & 4294967168) << 13) ^ (((s4_n << 3) ^ s4_n) >> 12)) * * The period of this generator is about 2^113 (see erratum paper). * * From: P. L'Ecuyer, "Maximally Equidistributed Combined Tausworthe * Generators", Mathematics of Computation, 65, 213 (1996), 203--213: * http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme.ps * ftp://ftp.iro.umontreal.ca/pub/simulation/lecuyer/papers/tausme.ps * * There is an erratum in the paper "Tables of Maximally Equidistributed * Combined LFSR Generators", Mathematics of Computation, 68, 225 (1999), * 261--269: http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps * * ... the k_j most significant bits of z_j must be non-zero, * for each j. (Note: this restriction also applies to the * computer code given in [4], but was mistakenly not mentioned * in that paper.) * * This affects the seeding procedure by imposing the requirement * s1 > 1, s2 > 7, s3 > 15, s4 > 127. */ #include <linux/types.h> #include <linux/percpu.h> #include <linux/export.h> #include <linux/jiffies.h> #include <linux/random.h> #include <linux/sched.h> #include <asm/unaligned.h> #ifdef CONFIG_RANDOM32_SELFTEST static void __init prandom_state_selftest(void); #else static inline void prandom_state_selftest(void) { } #endif DEFINE_PER_CPU(struct rnd_state, net_rand_state) __latent_entropy; /** * prandom_u32_state - seeded pseudo-random number generator. * @state: pointer to state structure holding seeded state. * * This is used for pseudo-randomness with no outside seeding. * For more random results, use prandom_u32(). */ u32 prandom_u32_state(struct rnd_state *state) { #define TAUSWORTHE(s, a, b, c, d) ((s & c) << d) ^ (((s << a) ^ s) >> b) state->s1 = TAUSWORTHE(state->s1, 6U, 13U, 4294967294U, 18U); state->s2 = TAUSWORTHE(state->s2, 2U, 27U, 4294967288U, 2U); state->s3 = TAUSWORTHE(state->s3, 13U, 21U, 4294967280U, 7U); state->s4 = TAUSWORTHE(state->s4, 3U, 12U, 4294967168U, 13U); return (state->s1 ^ state->s2 ^ state->s3 ^ state->s4); } EXPORT_SYMBOL(prandom_u32_state); /** * prandom_u32 - pseudo random number generator * * A 32 bit pseudo-random number is generated using a fast * algorithm suitable for simulation. This algorithm is NOT * considered safe for cryptographic use. */ u32 prandom_u32(void) { struct rnd_state *state = &get_cpu_var(net_rand_state); u32 res; res = prandom_u32_state(state); put_cpu_var(net_rand_state); return res; } EXPORT_SYMBOL(prandom_u32); /** * prandom_bytes_state - get the requested number of pseudo-random bytes * * @state: pointer to state structure holding seeded state. * @buf: where to copy the pseudo-random bytes to * @bytes: the requested number of bytes * * This is used for pseudo-randomness with no outside seeding. * For more random results, use prandom_bytes(). */ void prandom_bytes_state(struct rnd_state *state, void *buf, size_t bytes) { u8 *ptr = buf; while (bytes >= sizeof(u32)) { put_unaligned(prandom_u32_state(state), (u32 *) ptr); ptr += sizeof(u32); bytes -= sizeof(u32); } if (bytes > 0) { u32 rem = prandom_u32_state(state); do { *ptr++ = (u8) rem; bytes--; rem >>= BITS_PER_BYTE; } while (bytes > 0); } } EXPORT_SYMBOL(prandom_bytes_state); /** * prandom_bytes - get the requested number of pseudo-random bytes * @buf: where to copy the pseudo-random bytes to * @bytes: the requested number of bytes */ void prandom_bytes(void *buf, size_t bytes) { struct rnd_state *state = &get_cpu_var(net_rand_state); prandom_bytes_state(state, buf, bytes); put_cpu_var(net_rand_state); } EXPORT_SYMBOL(prandom_bytes); static void prandom_warmup(struct rnd_state *state) { /* Calling RNG ten times to satisfy recurrence condition */ prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); prandom_u32_state(state); } static u32 __extract_hwseed(void) { unsigned int val = 0; (void)(arch_get_random_seed_int(&val) || arch_get_random_int(&val)); return val; } static void prandom_seed_early(struct rnd_state *state, u32 seed, bool mix_with_hwseed) { #define LCG(x) ((x) * 69069U) /* super-duper LCG */ #define HWSEED() (mix_with_hwseed ? __extract_hwseed() : 0) state->s1 = __seed(HWSEED() ^ LCG(seed), 2U); state->s2 = __seed(HWSEED() ^ LCG(state->s1), 8U); state->s3 = __seed(HWSEED() ^ LCG(state->s2), 16U); state->s4 = __seed(HWSEED() ^ LCG(state->s3), 128U); } /** * prandom_seed - add entropy to pseudo random number generator * @entropy: entropy value * * Add some additional entropy to the prandom pool. */ void prandom_seed(u32 entropy) { int i; /* * No locking on the CPUs, but then somewhat random results are, well, * expected. */ for_each_possible_cpu(i) { struct rnd_state *state = &per_cpu(net_rand_state, i); state->s1 = __seed(state->s1 ^ entropy, 2U); prandom_warmup(state); } } EXPORT_SYMBOL(prandom_seed); /* * Generate some initially weak seeding values to allow * to start the prandom_u32() engine. */ static int __init prandom_init(void) { int i; prandom_state_selftest(); for_each_possible_cpu(i) { struct rnd_state *state = &per_cpu(net_rand_state, i); u32 weak_seed = (i + jiffies) ^ random_get_entropy(); prandom_seed_early(state, weak_seed, true); prandom_warmup(state); } return 0; } core_initcall(prandom_init); static void __prandom_timer(struct timer_list *unused); static DEFINE_TIMER(seed_timer, __prandom_timer); static void __prandom_timer(struct timer_list *unused) { u32 entropy; unsigned long expires; get_random_bytes(&entropy, sizeof(entropy)); prandom_seed(entropy); /* reseed every ~60 seconds, in [40 .. 80) interval with slack */ expires = 40 + prandom_u32_max(40); seed_timer.expires = jiffies + msecs_to_jiffies(expires * MSEC_PER_SEC); add_timer(&seed_timer); } static void __init __prandom_start_seed_timer(void) { seed_timer.expires = jiffies + msecs_to_jiffies(40 * MSEC_PER_SEC); add_timer(&seed_timer); } void prandom_seed_full_state(struct rnd_state __percpu *pcpu_state) { int i; for_each_possible_cpu(i) { struct rnd_state *state = per_cpu_ptr(pcpu_state, i); u32 seeds[4]; get_random_bytes(&seeds, sizeof(seeds)); state->s1 = __seed(seeds[0], 2U); state->s2 = __seed(seeds[1], 8U); state->s3 = __seed(seeds[2], 16U); state->s4 = __seed(seeds[3], 128U); prandom_warmup(state); } } EXPORT_SYMBOL(prandom_seed_full_state); /* * Generate better values after random number generator * is fully initialized. */ static void __prandom_reseed(bool late) { unsigned long flags; static bool latch = false; static DEFINE_SPINLOCK(lock); /* Asking for random bytes might result in bytes getting * moved into the nonblocking pool and thus marking it * as initialized. In this case we would double back into * this function and attempt to do a late reseed. * Ignore the pointless attempt to reseed again if we're * already waiting for bytes when the nonblocking pool * got initialized. */ /* only allow initial seeding (late == false) once */ if (!spin_trylock_irqsave(&lock, flags)) return; if (latch && !late) goto out; latch = true; prandom_seed_full_state(&net_rand_state); out: spin_unlock_irqrestore(&lock, flags); } void prandom_reseed_late(void) { __prandom_reseed(true); } static int __init prandom_reseed(void) { __prandom_reseed(false); __prandom_start_seed_timer(); return 0; } late_initcall(prandom_reseed); #ifdef CONFIG_RANDOM32_SELFTEST static struct prandom_test1 { u32 seed; u32 result; } test1[] = { { 1U, 3484351685U }, { 2U, 2623130059U }, { 3U, 3125133893U }, { 4U, 984847254U }, }; static struct prandom_test2 { u32 seed; u32 iteration; u32 result; } test2[] = { /* Test cases against taus113 from GSL library. */ { 931557656U, 959U, 2975593782U }, { 1339693295U, 876U, 3887776532U }, { 1545556285U, 961U, 1615538833U }, { 601730776U, 723U, 1776162651U }, { 1027516047U, 687U, 511983079U }, { 416526298U, 700U, 916156552U }, { 1395522032U, 652U, 2222063676U }, { 366221443U, 617U, 2992857763U }, { 1539836965U, 714U, 3783265725U }, { 556206671U, 994U, 799626459U }, { 684907218U, 799U, 367789491U }, { 2121230701U, 931U, 2115467001U }, { 1668516451U, 644U, 3620590685U }, { 768046066U, 883U, 2034077390U }, { 1989159136U, 833U, 1195767305U }, { 536585145U, 996U, 3577259204U }, { 1008129373U, 642U, 1478080776U }, { 1740775604U, 939U, 1264980372U }, { 1967883163U, 508U, 10734624U }, { 1923019697U, 730U, 3821419629U }, { 442079932U, 560U, 3440032343U }, { 1961302714U, 845U, 841962572U }, { 2030205964U, 962U, 1325144227U }, { 1160407529U, 507U, 240940858U }, { 635482502U, 779U, 4200489746U }, { 1252788931U, 699U, 867195434U }, { 1961817131U, 719U, 668237657U }, { 1071468216U, 983U, 917876630U }, { 1281848367U, 932U, 1003100039U }, { 582537119U, 780U, 1127273778U }, { 1973672777U, 853U, 1071368872U }, { 1896756996U, 762U, 1127851055U }, { 847917054U, 500U, 1717499075U }, { 1240520510U, 951U, 2849576657U }, { 1685071682U, 567U, 1961810396U }, { 1516232129U, 557U, 3173877U }, { 1208118903U, 612U, 1613145022U }, { 1817269927U, 693U, 4279122573U }, { 1510091701U, 717U, 638191229U }, { 365916850U, 807U, 600424314U }, { 399324359U, 702U, 1803598116U }, { 1318480274U, 779U, 2074237022U }, { 697758115U, 840U, 1483639402U }, { 1696507773U, 840U, 577415447U }, { 2081979121U, 981U, 3041486449U }, { 955646687U, 742U, 3846494357U }, { 1250683506U, 749U, 836419859U }, { 595003102U, 534U, 366794109U }, { 47485338U, 558U, 3521120834U }, { 619433479U, 610U, 3991783875U }, { 704096520U, 518U, 4139493852U }, { 1712224984U, 606U, 2393312003U }, { 1318233152U, 922U, 3880361134U }, { 855572992U, 761U, 1472974787U }, { 64721421U, 703U, 683860550U }, { 678931758U, 840U, 380616043U }, { 692711973U, 778U, 1382361947U }, { 677703619U, 530U, 2826914161U }, { 92393223U, 586U, 1522128471U }, { 1222592920U, 743U, 3466726667U }, { 358288986U, 695U, 1091956998U }, { 1935056945U, 958U, 514864477U }, { 735675993U, 990U, 1294239989U }, { 1560089402U, 897U, 2238551287U }, { 70616361U, 829U, 22483098U }, { 368234700U, 731U, 2913875084U }, { 20221190U, 879U, 1564152970U }, { 539444654U, 682U, 1835141259U }, { 1314987297U, 840U, 1801114136U }, { 2019295544U, 645U, 3286438930U }, { 469023838U, 716U, 1637918202U }, { 1843754496U, 653U, 2562092152U }, { 400672036U, 809U, 4264212785U }, { 404722249U, 965U, 2704116999U }, { 600702209U, 758U, 584979986U }, { 519953954U, 667U, 2574436237U }, { 1658071126U, 694U, 2214569490U }, { 420480037U, 749U, 3430010866U }, { 690103647U, 969U, 3700758083U }, { 1029424799U, 937U, 3787746841U }, { 2012608669U, 506U, 3362628973U }, { 1535432887U, 998U, 42610943U }, { 1330635533U, 857U, 3040806504U }, { 1223800550U, 539U, 3954229517U }, { 1322411537U, 680U, 3223250324U }, { 1877847898U, 945U, 2915147143U }, { 1646356099U, 874U, 965988280U }, { 805687536U, 744U, 4032277920U }, { 1948093210U, 633U, 1346597684U }, { 392609744U, 783U, 1636083295U }, { 690241304U, 770U, 1201031298U }, { 1360302965U, 696U, 1665394461U }, { 1220090946U, 780U, 1316922812U }, { 447092251U, 500U, 3438743375U }, { 1613868791U, 592U, 828546883U }, { 523430951U, 548U, 2552392304U }, { 726692899U, 810U, 1656872867U }, { 1364340021U, 836U, 3710513486U }, { 1986257729U, 931U, 935013962U }, { 407983964U, 921U, 728767059U }, }; static void __init prandom_state_selftest(void) { int i, j, errors = 0, runs = 0; bool error = false; for (i = 0; i < ARRAY_SIZE(test1); i++) { struct rnd_state state; prandom_seed_early(&state, test1[i].seed, false); prandom_warmup(&state); if (test1[i].result != prandom_u32_state(&state)) error = true; } if (error) pr_warn("prandom: seed boundary self test failed\n"); else pr_info("prandom: seed boundary self test passed\n"); for (i = 0; i < ARRAY_SIZE(test2); i++) { struct rnd_state state; prandom_seed_early(&state, test2[i].seed, false); prandom_warmup(&state); for (j = 0; j < test2[i].iteration - 1; j++) prandom_u32_state(&state); if (test2[i].result != prandom_u32_state(&state)) errors++; runs++; cond_resched(); } if (errors) pr_warn("prandom: %d/%d self tests failed\n", errors, runs); else pr_info("prandom: %d self tests passed\n", runs); } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/good_4240_3
crossvul-cpp_data_bad_2825_0
/* * linux/kernel/exit.c * * Copyright (C) 1991, 1992 Linus Torvalds */ #include <linux/mm.h> #include <linux/slab.h> #include <linux/sched/autogroup.h> #include <linux/sched/mm.h> #include <linux/sched/stat.h> #include <linux/sched/task.h> #include <linux/sched/task_stack.h> #include <linux/sched/cputime.h> #include <linux/interrupt.h> #include <linux/module.h> #include <linux/capability.h> #include <linux/completion.h> #include <linux/personality.h> #include <linux/tty.h> #include <linux/iocontext.h> #include <linux/key.h> #include <linux/cpu.h> #include <linux/acct.h> #include <linux/tsacct_kern.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/freezer.h> #include <linux/binfmts.h> #include <linux/nsproxy.h> #include <linux/pid_namespace.h> #include <linux/ptrace.h> #include <linux/profile.h> #include <linux/mount.h> #include <linux/proc_fs.h> #include <linux/kthread.h> #include <linux/mempolicy.h> #include <linux/taskstats_kern.h> #include <linux/delayacct.h> #include <linux/cgroup.h> #include <linux/syscalls.h> #include <linux/signal.h> #include <linux/posix-timers.h> #include <linux/cn_proc.h> #include <linux/mutex.h> #include <linux/futex.h> #include <linux/pipe_fs_i.h> #include <linux/audit.h> /* for audit_free() */ #include <linux/resource.h> #include <linux/blkdev.h> #include <linux/task_io_accounting_ops.h> #include <linux/tracehook.h> #include <linux/fs_struct.h> #include <linux/init_task.h> #include <linux/perf_event.h> #include <trace/events/sched.h> #include <linux/hw_breakpoint.h> #include <linux/oom.h> #include <linux/writeback.h> #include <linux/shm.h> #include <linux/kcov.h> #include <linux/random.h> #include <linux/rcuwait.h> #include <linux/compat.h> #include <linux/uaccess.h> #include <asm/unistd.h> #include <asm/pgtable.h> #include <asm/mmu_context.h> static void __unhash_process(struct task_struct *p, bool group_dead) { nr_threads--; detach_pid(p, PIDTYPE_PID); if (group_dead) { detach_pid(p, PIDTYPE_PGID); detach_pid(p, PIDTYPE_SID); list_del_rcu(&p->tasks); list_del_init(&p->sibling); __this_cpu_dec(process_counts); } list_del_rcu(&p->thread_group); list_del_rcu(&p->thread_node); } /* * This function expects the tasklist_lock write-locked. */ static void __exit_signal(struct task_struct *tsk) { struct signal_struct *sig = tsk->signal; bool group_dead = thread_group_leader(tsk); struct sighand_struct *sighand; struct tty_struct *uninitialized_var(tty); u64 utime, stime; sighand = rcu_dereference_check(tsk->sighand, lockdep_tasklist_lock_is_held()); spin_lock(&sighand->siglock); #ifdef CONFIG_POSIX_TIMERS posix_cpu_timers_exit(tsk); if (group_dead) { posix_cpu_timers_exit_group(tsk); } else { /* * This can only happen if the caller is de_thread(). * FIXME: this is the temporary hack, we should teach * posix-cpu-timers to handle this case correctly. */ if (unlikely(has_group_leader_pid(tsk))) posix_cpu_timers_exit_group(tsk); } #endif if (group_dead) { tty = sig->tty; sig->tty = NULL; } else { /* * If there is any task waiting for the group exit * then notify it: */ if (sig->notify_count > 0 && !--sig->notify_count) wake_up_process(sig->group_exit_task); if (tsk == sig->curr_target) sig->curr_target = next_thread(tsk); } add_device_randomness((const void*) &tsk->se.sum_exec_runtime, sizeof(unsigned long long)); /* * Accumulate here the counters for all threads as they die. We could * skip the group leader because it is the last user of signal_struct, * but we want to avoid the race with thread_group_cputime() which can * see the empty ->thread_head list. */ task_cputime(tsk, &utime, &stime); write_seqlock(&sig->stats_lock); sig->utime += utime; sig->stime += stime; sig->gtime += task_gtime(tsk); sig->min_flt += tsk->min_flt; sig->maj_flt += tsk->maj_flt; sig->nvcsw += tsk->nvcsw; sig->nivcsw += tsk->nivcsw; sig->inblock += task_io_get_inblock(tsk); sig->oublock += task_io_get_oublock(tsk); task_io_accounting_add(&sig->ioac, &tsk->ioac); sig->sum_sched_runtime += tsk->se.sum_exec_runtime; sig->nr_threads--; __unhash_process(tsk, group_dead); write_sequnlock(&sig->stats_lock); /* * Do this under ->siglock, we can race with another thread * doing sigqueue_free() if we have SIGQUEUE_PREALLOC signals. */ flush_sigqueue(&tsk->pending); tsk->sighand = NULL; spin_unlock(&sighand->siglock); __cleanup_sighand(sighand); clear_tsk_thread_flag(tsk, TIF_SIGPENDING); if (group_dead) { flush_sigqueue(&sig->shared_pending); tty_kref_put(tty); } } static void delayed_put_task_struct(struct rcu_head *rhp) { struct task_struct *tsk = container_of(rhp, struct task_struct, rcu); perf_event_delayed_put(tsk); trace_sched_process_free(tsk); put_task_struct(tsk); } void release_task(struct task_struct *p) { struct task_struct *leader; int zap_leader; repeat: /* don't need to get the RCU readlock here - the process is dead and * can't be modifying its own credentials. But shut RCU-lockdep up */ rcu_read_lock(); atomic_dec(&__task_cred(p)->user->processes); rcu_read_unlock(); proc_flush_task(p); write_lock_irq(&tasklist_lock); ptrace_release_task(p); __exit_signal(p); /* * If we are the last non-leader member of the thread * group, and the leader is zombie, then notify the * group leader's parent process. (if it wants notification.) */ zap_leader = 0; leader = p->group_leader; if (leader != p && thread_group_empty(leader) && leader->exit_state == EXIT_ZOMBIE) { /* * If we were the last child thread and the leader has * exited already, and the leader's parent ignores SIGCHLD, * then we are the one who should release the leader. */ zap_leader = do_notify_parent(leader, leader->exit_signal); if (zap_leader) leader->exit_state = EXIT_DEAD; } write_unlock_irq(&tasklist_lock); release_thread(p); call_rcu(&p->rcu, delayed_put_task_struct); p = leader; if (unlikely(zap_leader)) goto repeat; } /* * Note that if this function returns a valid task_struct pointer (!NULL) * task->usage must remain >0 for the duration of the RCU critical section. */ struct task_struct *task_rcu_dereference(struct task_struct **ptask) { struct sighand_struct *sighand; struct task_struct *task; /* * We need to verify that release_task() was not called and thus * delayed_put_task_struct() can't run and drop the last reference * before rcu_read_unlock(). We check task->sighand != NULL, * but we can read the already freed and reused memory. */ retry: task = rcu_dereference(*ptask); if (!task) return NULL; probe_kernel_address(&task->sighand, sighand); /* * Pairs with atomic_dec_and_test() in put_task_struct(). If this task * was already freed we can not miss the preceding update of this * pointer. */ smp_rmb(); if (unlikely(task != READ_ONCE(*ptask))) goto retry; /* * We've re-checked that "task == *ptask", now we have two different * cases: * * 1. This is actually the same task/task_struct. In this case * sighand != NULL tells us it is still alive. * * 2. This is another task which got the same memory for task_struct. * We can't know this of course, and we can not trust * sighand != NULL. * * In this case we actually return a random value, but this is * correct. * * If we return NULL - we can pretend that we actually noticed that * *ptask was updated when the previous task has exited. Or pretend * that probe_slab_address(&sighand) reads NULL. * * If we return the new task (because sighand is not NULL for any * reason) - this is fine too. This (new) task can't go away before * another gp pass. * * And note: We could even eliminate the false positive if re-read * task->sighand once again to avoid the falsely NULL. But this case * is very unlikely so we don't care. */ if (!sighand) return NULL; return task; } void rcuwait_wake_up(struct rcuwait *w) { struct task_struct *task; rcu_read_lock(); /* * Order condition vs @task, such that everything prior to the load * of @task is visible. This is the condition as to why the user called * rcuwait_trywake() in the first place. Pairs with set_current_state() * barrier (A) in rcuwait_wait_event(). * * WAIT WAKE * [S] tsk = current [S] cond = true * MB (A) MB (B) * [L] cond [L] tsk */ smp_rmb(); /* (B) */ /* * Avoid using task_rcu_dereference() magic as long as we are careful, * see comment in rcuwait_wait_event() regarding ->exit_state. */ task = rcu_dereference(w->task); if (task) wake_up_process(task); rcu_read_unlock(); } /* * Determine if a process group is "orphaned", according to the POSIX * definition in 2.2.2.52. Orphaned process groups are not to be affected * by terminal-generated stop signals. Newly orphaned process groups are * to receive a SIGHUP and a SIGCONT. * * "I ask you, have you ever known what it is to be an orphan?" */ static int will_become_orphaned_pgrp(struct pid *pgrp, struct task_struct *ignored_task) { struct task_struct *p; do_each_pid_task(pgrp, PIDTYPE_PGID, p) { if ((p == ignored_task) || (p->exit_state && thread_group_empty(p)) || is_global_init(p->real_parent)) continue; if (task_pgrp(p->real_parent) != pgrp && task_session(p->real_parent) == task_session(p)) return 0; } while_each_pid_task(pgrp, PIDTYPE_PGID, p); return 1; } int is_current_pgrp_orphaned(void) { int retval; read_lock(&tasklist_lock); retval = will_become_orphaned_pgrp(task_pgrp(current), NULL); read_unlock(&tasklist_lock); return retval; } static bool has_stopped_jobs(struct pid *pgrp) { struct task_struct *p; do_each_pid_task(pgrp, PIDTYPE_PGID, p) { if (p->signal->flags & SIGNAL_STOP_STOPPED) return true; } while_each_pid_task(pgrp, PIDTYPE_PGID, p); return false; } /* * Check to see if any process groups have become orphaned as * a result of our exiting, and if they have any stopped jobs, * send them a SIGHUP and then a SIGCONT. (POSIX 3.2.2.2) */ static void kill_orphaned_pgrp(struct task_struct *tsk, struct task_struct *parent) { struct pid *pgrp = task_pgrp(tsk); struct task_struct *ignored_task = tsk; if (!parent) /* exit: our father is in a different pgrp than * we are and we were the only connection outside. */ parent = tsk->real_parent; else /* reparent: our child is in a different pgrp than * we are, and it was the only connection outside. */ ignored_task = NULL; if (task_pgrp(parent) != pgrp && task_session(parent) == task_session(tsk) && will_become_orphaned_pgrp(pgrp, ignored_task) && has_stopped_jobs(pgrp)) { __kill_pgrp_info(SIGHUP, SEND_SIG_PRIV, pgrp); __kill_pgrp_info(SIGCONT, SEND_SIG_PRIV, pgrp); } } #ifdef CONFIG_MEMCG /* * A task is exiting. If it owned this mm, find a new owner for the mm. */ void mm_update_next_owner(struct mm_struct *mm) { struct task_struct *c, *g, *p = current; retry: /* * If the exiting or execing task is not the owner, it's * someone else's problem. */ if (mm->owner != p) return; /* * The current owner is exiting/execing and there are no other * candidates. Do not leave the mm pointing to a possibly * freed task structure. */ if (atomic_read(&mm->mm_users) <= 1) { mm->owner = NULL; return; } read_lock(&tasklist_lock); /* * Search in the children */ list_for_each_entry(c, &p->children, sibling) { if (c->mm == mm) goto assign_new_owner; } /* * Search in the siblings */ list_for_each_entry(c, &p->real_parent->children, sibling) { if (c->mm == mm) goto assign_new_owner; } /* * Search through everything else, we should not get here often. */ for_each_process(g) { if (g->flags & PF_KTHREAD) continue; for_each_thread(g, c) { if (c->mm == mm) goto assign_new_owner; if (c->mm) break; } } read_unlock(&tasklist_lock); /* * We found no owner yet mm_users > 1: this implies that we are * most likely racing with swapoff (try_to_unuse()) or /proc or * ptrace or page migration (get_task_mm()). Mark owner as NULL. */ mm->owner = NULL; return; assign_new_owner: BUG_ON(c == p); get_task_struct(c); /* * The task_lock protects c->mm from changing. * We always want mm->owner->mm == mm */ task_lock(c); /* * Delay read_unlock() till we have the task_lock() * to ensure that c does not slip away underneath us */ read_unlock(&tasklist_lock); if (c->mm != mm) { task_unlock(c); put_task_struct(c); goto retry; } mm->owner = c; task_unlock(c); put_task_struct(c); } #endif /* CONFIG_MEMCG */ /* * Turn us into a lazy TLB process if we * aren't already.. */ static void exit_mm(void) { struct mm_struct *mm = current->mm; struct core_state *core_state; mm_release(current, mm); if (!mm) return; sync_mm_rss(mm); /* * Serialize with any possible pending coredump. * We must hold mmap_sem around checking core_state * and clearing tsk->mm. The core-inducing thread * will increment ->nr_threads for each thread in the * group with ->mm != NULL. */ down_read(&mm->mmap_sem); core_state = mm->core_state; if (core_state) { struct core_thread self; up_read(&mm->mmap_sem); self.task = current; self.next = xchg(&core_state->dumper.next, &self); /* * Implies mb(), the result of xchg() must be visible * to core_state->dumper. */ if (atomic_dec_and_test(&core_state->nr_threads)) complete(&core_state->startup); for (;;) { set_current_state(TASK_UNINTERRUPTIBLE); if (!self.task) /* see coredump_finish() */ break; freezable_schedule(); } __set_current_state(TASK_RUNNING); down_read(&mm->mmap_sem); } mmgrab(mm); BUG_ON(mm != current->active_mm); /* more a memory barrier than a real lock */ task_lock(current); current->mm = NULL; up_read(&mm->mmap_sem); enter_lazy_tlb(mm, current); task_unlock(current); mm_update_next_owner(mm); mmput(mm); if (test_thread_flag(TIF_MEMDIE)) exit_oom_victim(); } static struct task_struct *find_alive_thread(struct task_struct *p) { struct task_struct *t; for_each_thread(p, t) { if (!(t->flags & PF_EXITING)) return t; } return NULL; } static struct task_struct *find_child_reaper(struct task_struct *father) __releases(&tasklist_lock) __acquires(&tasklist_lock) { struct pid_namespace *pid_ns = task_active_pid_ns(father); struct task_struct *reaper = pid_ns->child_reaper; if (likely(reaper != father)) return reaper; reaper = find_alive_thread(father); if (reaper) { pid_ns->child_reaper = reaper; return reaper; } write_unlock_irq(&tasklist_lock); if (unlikely(pid_ns == &init_pid_ns)) { panic("Attempted to kill init! exitcode=0x%08x\n", father->signal->group_exit_code ?: father->exit_code); } zap_pid_ns_processes(pid_ns); write_lock_irq(&tasklist_lock); return father; } /* * When we die, we re-parent all our children, and try to: * 1. give them to another thread in our thread group, if such a member exists * 2. give it to the first ancestor process which prctl'd itself as a * child_subreaper for its children (like a service manager) * 3. give it to the init process (PID 1) in our pid namespace */ static struct task_struct *find_new_reaper(struct task_struct *father, struct task_struct *child_reaper) { struct task_struct *thread, *reaper; thread = find_alive_thread(father); if (thread) return thread; if (father->signal->has_child_subreaper) { unsigned int ns_level = task_pid(father)->level; /* * Find the first ->is_child_subreaper ancestor in our pid_ns. * We can't check reaper != child_reaper to ensure we do not * cross the namespaces, the exiting parent could be injected * by setns() + fork(). * We check pid->level, this is slightly more efficient than * task_active_pid_ns(reaper) != task_active_pid_ns(father). */ for (reaper = father->real_parent; task_pid(reaper)->level == ns_level; reaper = reaper->real_parent) { if (reaper == &init_task) break; if (!reaper->signal->is_child_subreaper) continue; thread = find_alive_thread(reaper); if (thread) return thread; } } return child_reaper; } /* * Any that need to be release_task'd are put on the @dead list. */ static void reparent_leader(struct task_struct *father, struct task_struct *p, struct list_head *dead) { if (unlikely(p->exit_state == EXIT_DEAD)) return; /* We don't want people slaying init. */ p->exit_signal = SIGCHLD; /* If it has exited notify the new parent about this child's death. */ if (!p->ptrace && p->exit_state == EXIT_ZOMBIE && thread_group_empty(p)) { if (do_notify_parent(p, p->exit_signal)) { p->exit_state = EXIT_DEAD; list_add(&p->ptrace_entry, dead); } } kill_orphaned_pgrp(p, father); } /* * This does two things: * * A. Make init inherit all the child processes * B. Check to see if any process groups have become orphaned * as a result of our exiting, and if they have any stopped * jobs, send them a SIGHUP and then a SIGCONT. (POSIX 3.2.2.2) */ static void forget_original_parent(struct task_struct *father, struct list_head *dead) { struct task_struct *p, *t, *reaper; if (unlikely(!list_empty(&father->ptraced))) exit_ptrace(father, dead); /* Can drop and reacquire tasklist_lock */ reaper = find_child_reaper(father); if (list_empty(&father->children)) return; reaper = find_new_reaper(father, reaper); list_for_each_entry(p, &father->children, sibling) { for_each_thread(p, t) { t->real_parent = reaper; BUG_ON((!t->ptrace) != (t->parent == father)); if (likely(!t->ptrace)) t->parent = t->real_parent; if (t->pdeath_signal) group_send_sig_info(t->pdeath_signal, SEND_SIG_NOINFO, t); } /* * If this is a threaded reparent there is no need to * notify anyone anything has happened. */ if (!same_thread_group(reaper, father)) reparent_leader(father, p, dead); } list_splice_tail_init(&father->children, &reaper->children); } /* * Send signals to all our closest relatives so that they know * to properly mourn us.. */ static void exit_notify(struct task_struct *tsk, int group_dead) { bool autoreap; struct task_struct *p, *n; LIST_HEAD(dead); write_lock_irq(&tasklist_lock); forget_original_parent(tsk, &dead); if (group_dead) kill_orphaned_pgrp(tsk->group_leader, NULL); if (unlikely(tsk->ptrace)) { int sig = thread_group_leader(tsk) && thread_group_empty(tsk) && !ptrace_reparented(tsk) ? tsk->exit_signal : SIGCHLD; autoreap = do_notify_parent(tsk, sig); } else if (thread_group_leader(tsk)) { autoreap = thread_group_empty(tsk) && do_notify_parent(tsk, tsk->exit_signal); } else { autoreap = true; } tsk->exit_state = autoreap ? EXIT_DEAD : EXIT_ZOMBIE; if (tsk->exit_state == EXIT_DEAD) list_add(&tsk->ptrace_entry, &dead); /* mt-exec, de_thread() is waiting for group leader */ if (unlikely(tsk->signal->notify_count < 0)) wake_up_process(tsk->signal->group_exit_task); write_unlock_irq(&tasklist_lock); list_for_each_entry_safe(p, n, &dead, ptrace_entry) { list_del_init(&p->ptrace_entry); release_task(p); } } #ifdef CONFIG_DEBUG_STACK_USAGE static void check_stack_usage(void) { static DEFINE_SPINLOCK(low_water_lock); static int lowest_to_date = THREAD_SIZE; unsigned long free; free = stack_not_used(current); if (free >= lowest_to_date) return; spin_lock(&low_water_lock); if (free < lowest_to_date) { pr_info("%s (%d) used greatest stack depth: %lu bytes left\n", current->comm, task_pid_nr(current), free); lowest_to_date = free; } spin_unlock(&low_water_lock); } #else static inline void check_stack_usage(void) {} #endif void __noreturn do_exit(long code) { struct task_struct *tsk = current; int group_dead; profile_task_exit(tsk); kcov_task_exit(tsk); WARN_ON(blk_needs_flush_plug(tsk)); if (unlikely(in_interrupt())) panic("Aiee, killing interrupt handler!"); if (unlikely(!tsk->pid)) panic("Attempted to kill the idle task!"); /* * If do_exit is called because this processes oopsed, it's possible * that get_fs() was left as KERNEL_DS, so reset it to USER_DS before * continuing. Amongst other possible reasons, this is to prevent * mm_release()->clear_child_tid() from writing to a user-controlled * kernel address. */ set_fs(USER_DS); ptrace_event(PTRACE_EVENT_EXIT, code); validate_creds_for_do_exit(tsk); /* * We're taking recursive faults here in do_exit. Safest is to just * leave this task alone and wait for reboot. */ if (unlikely(tsk->flags & PF_EXITING)) { pr_alert("Fixing recursive fault but reboot is needed!\n"); /* * We can do this unlocked here. The futex code uses * this flag just to verify whether the pi state * cleanup has been done or not. In the worst case it * loops once more. We pretend that the cleanup was * done as there is no way to return. Either the * OWNER_DIED bit is set by now or we push the blocked * task into the wait for ever nirwana as well. */ tsk->flags |= PF_EXITPIDONE; set_current_state(TASK_UNINTERRUPTIBLE); schedule(); } exit_signals(tsk); /* sets PF_EXITING */ /* * Ensure that all new tsk->pi_lock acquisitions must observe * PF_EXITING. Serializes against futex.c:attach_to_pi_owner(). */ smp_mb(); /* * Ensure that we must observe the pi_state in exit_mm() -> * mm_release() -> exit_pi_state_list(). */ raw_spin_lock_irq(&tsk->pi_lock); raw_spin_unlock_irq(&tsk->pi_lock); if (unlikely(in_atomic())) { pr_info("note: %s[%d] exited with preempt_count %d\n", current->comm, task_pid_nr(current), preempt_count()); preempt_count_set(PREEMPT_ENABLED); } /* sync mm's RSS info before statistics gathering */ if (tsk->mm) sync_mm_rss(tsk->mm); acct_update_integrals(tsk); group_dead = atomic_dec_and_test(&tsk->signal->live); if (group_dead) { #ifdef CONFIG_POSIX_TIMERS hrtimer_cancel(&tsk->signal->real_timer); exit_itimers(tsk->signal); #endif if (tsk->mm) setmax_mm_hiwater_rss(&tsk->signal->maxrss, tsk->mm); } acct_collect(code, group_dead); if (group_dead) tty_audit_exit(); audit_free(tsk); tsk->exit_code = code; taskstats_exit(tsk, group_dead); exit_mm(); if (group_dead) acct_process(); trace_sched_process_exit(tsk); exit_sem(tsk); exit_shm(tsk); exit_files(tsk); exit_fs(tsk); if (group_dead) disassociate_ctty(1); exit_task_namespaces(tsk); exit_task_work(tsk); exit_thread(tsk); /* * Flush inherited counters to the parent - before the parent * gets woken up by child-exit notifications. * * because of cgroup mode, must be called before cgroup_exit() */ perf_event_exit_task(tsk); sched_autogroup_exit_task(tsk); cgroup_exit(tsk); /* * FIXME: do that only when needed, using sched_exit tracepoint */ flush_ptrace_hw_breakpoint(tsk); exit_tasks_rcu_start(); exit_notify(tsk, group_dead); proc_exit_connector(tsk); mpol_put_task_policy(tsk); #ifdef CONFIG_FUTEX if (unlikely(current->pi_state_cache)) kfree(current->pi_state_cache); #endif /* * Make sure we are holding no locks: */ debug_check_no_locks_held(); /* * We can do this unlocked here. The futex code uses this flag * just to verify whether the pi state cleanup has been done * or not. In the worst case it loops once more. */ tsk->flags |= PF_EXITPIDONE; if (tsk->io_context) exit_io_context(tsk); if (tsk->splice_pipe) free_pipe_info(tsk->splice_pipe); if (tsk->task_frag.page) put_page(tsk->task_frag.page); validate_creds_for_do_exit(tsk); check_stack_usage(); preempt_disable(); if (tsk->nr_dirtied) __this_cpu_add(dirty_throttle_leaks, tsk->nr_dirtied); exit_rcu(); exit_tasks_rcu_finish(); lockdep_free_task(tsk); do_task_dead(); } EXPORT_SYMBOL_GPL(do_exit); void complete_and_exit(struct completion *comp, long code) { if (comp) complete(comp); do_exit(code); } EXPORT_SYMBOL(complete_and_exit); SYSCALL_DEFINE1(exit, int, error_code) { do_exit((error_code&0xff)<<8); } /* * Take down every thread in the group. This is called by fatal signals * as well as by sys_exit_group (below). */ void do_group_exit(int exit_code) { struct signal_struct *sig = current->signal; BUG_ON(exit_code & 0x80); /* core dumps don't get here */ if (signal_group_exit(sig)) exit_code = sig->group_exit_code; else if (!thread_group_empty(current)) { struct sighand_struct *const sighand = current->sighand; spin_lock_irq(&sighand->siglock); if (signal_group_exit(sig)) /* Another thread got here before we took the lock. */ exit_code = sig->group_exit_code; else { sig->group_exit_code = exit_code; sig->flags = SIGNAL_GROUP_EXIT; zap_other_threads(current); } spin_unlock_irq(&sighand->siglock); } do_exit(exit_code); /* NOTREACHED */ } /* * this kills every thread in the thread group. Note that any externally * wait4()-ing process will get the correct exit code - even if this * thread is not the thread group leader. */ SYSCALL_DEFINE1(exit_group, int, error_code) { do_group_exit((error_code & 0xff) << 8); /* NOTREACHED */ return 0; } struct waitid_info { pid_t pid; uid_t uid; int status; int cause; }; struct wait_opts { enum pid_type wo_type; int wo_flags; struct pid *wo_pid; struct waitid_info *wo_info; int wo_stat; struct rusage *wo_rusage; wait_queue_entry_t child_wait; int notask_error; }; static inline struct pid *task_pid_type(struct task_struct *task, enum pid_type type) { if (type != PIDTYPE_PID) task = task->group_leader; return task->pids[type].pid; } static int eligible_pid(struct wait_opts *wo, struct task_struct *p) { return wo->wo_type == PIDTYPE_MAX || task_pid_type(p, wo->wo_type) == wo->wo_pid; } static int eligible_child(struct wait_opts *wo, bool ptrace, struct task_struct *p) { if (!eligible_pid(wo, p)) return 0; /* * Wait for all children (clone and not) if __WALL is set or * if it is traced by us. */ if (ptrace || (wo->wo_flags & __WALL)) return 1; /* * Otherwise, wait for clone children *only* if __WCLONE is set; * otherwise, wait for non-clone children *only*. * * Note: a "clone" child here is one that reports to its parent * using a signal other than SIGCHLD, or a non-leader thread which * we can only see if it is traced by us. */ if ((p->exit_signal != SIGCHLD) ^ !!(wo->wo_flags & __WCLONE)) return 0; return 1; } /* * Handle sys_wait4 work for one task in state EXIT_ZOMBIE. We hold * read_lock(&tasklist_lock) on entry. If we return zero, we still hold * the lock and this task is uninteresting. If we return nonzero, we have * released the lock and the system call should return. */ static int wait_task_zombie(struct wait_opts *wo, struct task_struct *p) { int state, status; pid_t pid = task_pid_vnr(p); uid_t uid = from_kuid_munged(current_user_ns(), task_uid(p)); struct waitid_info *infop; if (!likely(wo->wo_flags & WEXITED)) return 0; if (unlikely(wo->wo_flags & WNOWAIT)) { status = p->exit_code; get_task_struct(p); read_unlock(&tasklist_lock); sched_annotate_sleep(); if (wo->wo_rusage) getrusage(p, RUSAGE_BOTH, wo->wo_rusage); put_task_struct(p); goto out_info; } /* * Move the task's state to DEAD/TRACE, only one thread can do this. */ state = (ptrace_reparented(p) && thread_group_leader(p)) ? EXIT_TRACE : EXIT_DEAD; if (cmpxchg(&p->exit_state, EXIT_ZOMBIE, state) != EXIT_ZOMBIE) return 0; /* * We own this thread, nobody else can reap it. */ read_unlock(&tasklist_lock); sched_annotate_sleep(); /* * Check thread_group_leader() to exclude the traced sub-threads. */ if (state == EXIT_DEAD && thread_group_leader(p)) { struct signal_struct *sig = p->signal; struct signal_struct *psig = current->signal; unsigned long maxrss; u64 tgutime, tgstime; /* * The resource counters for the group leader are in its * own task_struct. Those for dead threads in the group * are in its signal_struct, as are those for the child * processes it has previously reaped. All these * accumulate in the parent's signal_struct c* fields. * * We don't bother to take a lock here to protect these * p->signal fields because the whole thread group is dead * and nobody can change them. * * psig->stats_lock also protects us from our sub-theads * which can reap other children at the same time. Until * we change k_getrusage()-like users to rely on this lock * we have to take ->siglock as well. * * We use thread_group_cputime_adjusted() to get times for * the thread group, which consolidates times for all threads * in the group including the group leader. */ thread_group_cputime_adjusted(p, &tgutime, &tgstime); spin_lock_irq(&current->sighand->siglock); write_seqlock(&psig->stats_lock); psig->cutime += tgutime + sig->cutime; psig->cstime += tgstime + sig->cstime; psig->cgtime += task_gtime(p) + sig->gtime + sig->cgtime; psig->cmin_flt += p->min_flt + sig->min_flt + sig->cmin_flt; psig->cmaj_flt += p->maj_flt + sig->maj_flt + sig->cmaj_flt; psig->cnvcsw += p->nvcsw + sig->nvcsw + sig->cnvcsw; psig->cnivcsw += p->nivcsw + sig->nivcsw + sig->cnivcsw; psig->cinblock += task_io_get_inblock(p) + sig->inblock + sig->cinblock; psig->coublock += task_io_get_oublock(p) + sig->oublock + sig->coublock; maxrss = max(sig->maxrss, sig->cmaxrss); if (psig->cmaxrss < maxrss) psig->cmaxrss = maxrss; task_io_accounting_add(&psig->ioac, &p->ioac); task_io_accounting_add(&psig->ioac, &sig->ioac); write_sequnlock(&psig->stats_lock); spin_unlock_irq(&current->sighand->siglock); } if (wo->wo_rusage) getrusage(p, RUSAGE_BOTH, wo->wo_rusage); status = (p->signal->flags & SIGNAL_GROUP_EXIT) ? p->signal->group_exit_code : p->exit_code; wo->wo_stat = status; if (state == EXIT_TRACE) { write_lock_irq(&tasklist_lock); /* We dropped tasklist, ptracer could die and untrace */ ptrace_unlink(p); /* If parent wants a zombie, don't release it now */ state = EXIT_ZOMBIE; if (do_notify_parent(p, p->exit_signal)) state = EXIT_DEAD; p->exit_state = state; write_unlock_irq(&tasklist_lock); } if (state == EXIT_DEAD) release_task(p); out_info: infop = wo->wo_info; if (infop) { if ((status & 0x7f) == 0) { infop->cause = CLD_EXITED; infop->status = status >> 8; } else { infop->cause = (status & 0x80) ? CLD_DUMPED : CLD_KILLED; infop->status = status & 0x7f; } infop->pid = pid; infop->uid = uid; } return pid; } static int *task_stopped_code(struct task_struct *p, bool ptrace) { if (ptrace) { if (task_is_traced(p) && !(p->jobctl & JOBCTL_LISTENING)) return &p->exit_code; } else { if (p->signal->flags & SIGNAL_STOP_STOPPED) return &p->signal->group_exit_code; } return NULL; } /** * wait_task_stopped - Wait for %TASK_STOPPED or %TASK_TRACED * @wo: wait options * @ptrace: is the wait for ptrace * @p: task to wait for * * Handle sys_wait4() work for %p in state %TASK_STOPPED or %TASK_TRACED. * * CONTEXT: * read_lock(&tasklist_lock), which is released if return value is * non-zero. Also, grabs and releases @p->sighand->siglock. * * RETURNS: * 0 if wait condition didn't exist and search for other wait conditions * should continue. Non-zero return, -errno on failure and @p's pid on * success, implies that tasklist_lock is released and wait condition * search should terminate. */ static int wait_task_stopped(struct wait_opts *wo, int ptrace, struct task_struct *p) { struct waitid_info *infop; int exit_code, *p_code, why; uid_t uid = 0; /* unneeded, required by compiler */ pid_t pid; /* * Traditionally we see ptrace'd stopped tasks regardless of options. */ if (!ptrace && !(wo->wo_flags & WUNTRACED)) return 0; if (!task_stopped_code(p, ptrace)) return 0; exit_code = 0; spin_lock_irq(&p->sighand->siglock); p_code = task_stopped_code(p, ptrace); if (unlikely(!p_code)) goto unlock_sig; exit_code = *p_code; if (!exit_code) goto unlock_sig; if (!unlikely(wo->wo_flags & WNOWAIT)) *p_code = 0; uid = from_kuid_munged(current_user_ns(), task_uid(p)); unlock_sig: spin_unlock_irq(&p->sighand->siglock); if (!exit_code) return 0; /* * Now we are pretty sure this task is interesting. * Make sure it doesn't get reaped out from under us while we * give up the lock and then examine it below. We don't want to * keep holding onto the tasklist_lock while we call getrusage and * possibly take page faults for user memory. */ get_task_struct(p); pid = task_pid_vnr(p); why = ptrace ? CLD_TRAPPED : CLD_STOPPED; read_unlock(&tasklist_lock); sched_annotate_sleep(); if (wo->wo_rusage) getrusage(p, RUSAGE_BOTH, wo->wo_rusage); put_task_struct(p); if (likely(!(wo->wo_flags & WNOWAIT))) wo->wo_stat = (exit_code << 8) | 0x7f; infop = wo->wo_info; if (infop) { infop->cause = why; infop->status = exit_code; infop->pid = pid; infop->uid = uid; } return pid; } /* * Handle do_wait work for one task in a live, non-stopped state. * read_lock(&tasklist_lock) on entry. If we return zero, we still hold * the lock and this task is uninteresting. If we return nonzero, we have * released the lock and the system call should return. */ static int wait_task_continued(struct wait_opts *wo, struct task_struct *p) { struct waitid_info *infop; pid_t pid; uid_t uid; if (!unlikely(wo->wo_flags & WCONTINUED)) return 0; if (!(p->signal->flags & SIGNAL_STOP_CONTINUED)) return 0; spin_lock_irq(&p->sighand->siglock); /* Re-check with the lock held. */ if (!(p->signal->flags & SIGNAL_STOP_CONTINUED)) { spin_unlock_irq(&p->sighand->siglock); return 0; } if (!unlikely(wo->wo_flags & WNOWAIT)) p->signal->flags &= ~SIGNAL_STOP_CONTINUED; uid = from_kuid_munged(current_user_ns(), task_uid(p)); spin_unlock_irq(&p->sighand->siglock); pid = task_pid_vnr(p); get_task_struct(p); read_unlock(&tasklist_lock); sched_annotate_sleep(); if (wo->wo_rusage) getrusage(p, RUSAGE_BOTH, wo->wo_rusage); put_task_struct(p); infop = wo->wo_info; if (!infop) { wo->wo_stat = 0xffff; } else { infop->cause = CLD_CONTINUED; infop->pid = pid; infop->uid = uid; infop->status = SIGCONT; } return pid; } /* * Consider @p for a wait by @parent. * * -ECHILD should be in ->notask_error before the first call. * Returns nonzero for a final return, when we have unlocked tasklist_lock. * Returns zero if the search for a child should continue; * then ->notask_error is 0 if @p is an eligible child, * or still -ECHILD. */ static int wait_consider_task(struct wait_opts *wo, int ptrace, struct task_struct *p) { /* * We can race with wait_task_zombie() from another thread. * Ensure that EXIT_ZOMBIE -> EXIT_DEAD/EXIT_TRACE transition * can't confuse the checks below. */ int exit_state = ACCESS_ONCE(p->exit_state); int ret; if (unlikely(exit_state == EXIT_DEAD)) return 0; ret = eligible_child(wo, ptrace, p); if (!ret) return ret; if (unlikely(exit_state == EXIT_TRACE)) { /* * ptrace == 0 means we are the natural parent. In this case * we should clear notask_error, debugger will notify us. */ if (likely(!ptrace)) wo->notask_error = 0; return 0; } if (likely(!ptrace) && unlikely(p->ptrace)) { /* * If it is traced by its real parent's group, just pretend * the caller is ptrace_do_wait() and reap this child if it * is zombie. * * This also hides group stop state from real parent; otherwise * a single stop can be reported twice as group and ptrace stop. * If a ptracer wants to distinguish these two events for its * own children it should create a separate process which takes * the role of real parent. */ if (!ptrace_reparented(p)) ptrace = 1; } /* slay zombie? */ if (exit_state == EXIT_ZOMBIE) { /* we don't reap group leaders with subthreads */ if (!delay_group_leader(p)) { /* * A zombie ptracee is only visible to its ptracer. * Notification and reaping will be cascaded to the * real parent when the ptracer detaches. */ if (unlikely(ptrace) || likely(!p->ptrace)) return wait_task_zombie(wo, p); } /* * Allow access to stopped/continued state via zombie by * falling through. Clearing of notask_error is complex. * * When !@ptrace: * * If WEXITED is set, notask_error should naturally be * cleared. If not, subset of WSTOPPED|WCONTINUED is set, * so, if there are live subthreads, there are events to * wait for. If all subthreads are dead, it's still safe * to clear - this function will be called again in finite * amount time once all the subthreads are released and * will then return without clearing. * * When @ptrace: * * Stopped state is per-task and thus can't change once the * target task dies. Only continued and exited can happen. * Clear notask_error if WCONTINUED | WEXITED. */ if (likely(!ptrace) || (wo->wo_flags & (WCONTINUED | WEXITED))) wo->notask_error = 0; } else { /* * @p is alive and it's gonna stop, continue or exit, so * there always is something to wait for. */ wo->notask_error = 0; } /* * Wait for stopped. Depending on @ptrace, different stopped state * is used and the two don't interact with each other. */ ret = wait_task_stopped(wo, ptrace, p); if (ret) return ret; /* * Wait for continued. There's only one continued state and the * ptracer can consume it which can confuse the real parent. Don't * use WCONTINUED from ptracer. You don't need or want it. */ return wait_task_continued(wo, p); } /* * Do the work of do_wait() for one thread in the group, @tsk. * * -ECHILD should be in ->notask_error before the first call. * Returns nonzero for a final return, when we have unlocked tasklist_lock. * Returns zero if the search for a child should continue; then * ->notask_error is 0 if there were any eligible children, * or still -ECHILD. */ static int do_wait_thread(struct wait_opts *wo, struct task_struct *tsk) { struct task_struct *p; list_for_each_entry(p, &tsk->children, sibling) { int ret = wait_consider_task(wo, 0, p); if (ret) return ret; } return 0; } static int ptrace_do_wait(struct wait_opts *wo, struct task_struct *tsk) { struct task_struct *p; list_for_each_entry(p, &tsk->ptraced, ptrace_entry) { int ret = wait_consider_task(wo, 1, p); if (ret) return ret; } return 0; } static int child_wait_callback(wait_queue_entry_t *wait, unsigned mode, int sync, void *key) { struct wait_opts *wo = container_of(wait, struct wait_opts, child_wait); struct task_struct *p = key; if (!eligible_pid(wo, p)) return 0; if ((wo->wo_flags & __WNOTHREAD) && wait->private != p->parent) return 0; return default_wake_function(wait, mode, sync, key); } void __wake_up_parent(struct task_struct *p, struct task_struct *parent) { __wake_up_sync_key(&parent->signal->wait_chldexit, TASK_INTERRUPTIBLE, 1, p); } static long do_wait(struct wait_opts *wo) { struct task_struct *tsk; int retval; trace_sched_process_wait(wo->wo_pid); init_waitqueue_func_entry(&wo->child_wait, child_wait_callback); wo->child_wait.private = current; add_wait_queue(&current->signal->wait_chldexit, &wo->child_wait); repeat: /* * If there is nothing that can match our criteria, just get out. * We will clear ->notask_error to zero if we see any child that * might later match our criteria, even if we are not able to reap * it yet. */ wo->notask_error = -ECHILD; if ((wo->wo_type < PIDTYPE_MAX) && (!wo->wo_pid || hlist_empty(&wo->wo_pid->tasks[wo->wo_type]))) goto notask; set_current_state(TASK_INTERRUPTIBLE); read_lock(&tasklist_lock); tsk = current; do { retval = do_wait_thread(wo, tsk); if (retval) goto end; retval = ptrace_do_wait(wo, tsk); if (retval) goto end; if (wo->wo_flags & __WNOTHREAD) break; } while_each_thread(current, tsk); read_unlock(&tasklist_lock); notask: retval = wo->notask_error; if (!retval && !(wo->wo_flags & WNOHANG)) { retval = -ERESTARTSYS; if (!signal_pending(current)) { schedule(); goto repeat; } } end: __set_current_state(TASK_RUNNING); remove_wait_queue(&current->signal->wait_chldexit, &wo->child_wait); return retval; } static long kernel_waitid(int which, pid_t upid, struct waitid_info *infop, int options, struct rusage *ru) { struct wait_opts wo; struct pid *pid = NULL; enum pid_type type; long ret; if (options & ~(WNOHANG|WNOWAIT|WEXITED|WSTOPPED|WCONTINUED| __WNOTHREAD|__WCLONE|__WALL)) return -EINVAL; if (!(options & (WEXITED|WSTOPPED|WCONTINUED))) return -EINVAL; switch (which) { case P_ALL: type = PIDTYPE_MAX; break; case P_PID: type = PIDTYPE_PID; if (upid <= 0) return -EINVAL; break; case P_PGID: type = PIDTYPE_PGID; if (upid <= 0) return -EINVAL; break; default: return -EINVAL; } if (type < PIDTYPE_MAX) pid = find_get_pid(upid); wo.wo_type = type; wo.wo_pid = pid; wo.wo_flags = options; wo.wo_info = infop; wo.wo_rusage = ru; ret = do_wait(&wo); put_pid(pid); return ret; } SYSCALL_DEFINE5(waitid, int, which, pid_t, upid, struct siginfo __user *, infop, int, options, struct rusage __user *, ru) { struct rusage r; struct waitid_info info = {.status = 0}; long err = kernel_waitid(which, upid, &info, options, ru ? &r : NULL); int signo = 0; if (err > 0) { signo = SIGCHLD; err = 0; } if (!err) { if (ru && copy_to_user(ru, &r, sizeof(struct rusage))) return -EFAULT; } if (!infop) return err; user_access_begin(); unsafe_put_user(signo, &infop->si_signo, Efault); unsafe_put_user(0, &infop->si_errno, Efault); unsafe_put_user(info.cause, &infop->si_code, Efault); unsafe_put_user(info.pid, &infop->si_pid, Efault); unsafe_put_user(info.uid, &infop->si_uid, Efault); unsafe_put_user(info.status, &infop->si_status, Efault); user_access_end(); return err; Efault: user_access_end(); return -EFAULT; } long kernel_wait4(pid_t upid, int __user *stat_addr, int options, struct rusage *ru) { struct wait_opts wo; struct pid *pid = NULL; enum pid_type type; long ret; if (options & ~(WNOHANG|WUNTRACED|WCONTINUED| __WNOTHREAD|__WCLONE|__WALL)) return -EINVAL; /* -INT_MIN is not defined */ if (upid == INT_MIN) return -ESRCH; if (upid == -1) type = PIDTYPE_MAX; else if (upid < 0) { type = PIDTYPE_PGID; pid = find_get_pid(-upid); } else if (upid == 0) { type = PIDTYPE_PGID; pid = get_task_pid(current, PIDTYPE_PGID); } else /* upid > 0 */ { type = PIDTYPE_PID; pid = find_get_pid(upid); } wo.wo_type = type; wo.wo_pid = pid; wo.wo_flags = options | WEXITED; wo.wo_info = NULL; wo.wo_stat = 0; wo.wo_rusage = ru; ret = do_wait(&wo); put_pid(pid); if (ret > 0 && stat_addr && put_user(wo.wo_stat, stat_addr)) ret = -EFAULT; return ret; } SYSCALL_DEFINE4(wait4, pid_t, upid, int __user *, stat_addr, int, options, struct rusage __user *, ru) { struct rusage r; long err = kernel_wait4(upid, stat_addr, options, ru ? &r : NULL); if (err > 0) { if (ru && copy_to_user(ru, &r, sizeof(struct rusage))) return -EFAULT; } return err; } #ifdef __ARCH_WANT_SYS_WAITPID /* * sys_waitpid() remains for compatibility. waitpid() should be * implemented by calling sys_wait4() from libc.a. */ SYSCALL_DEFINE3(waitpid, pid_t, pid, int __user *, stat_addr, int, options) { return sys_wait4(pid, stat_addr, options, NULL); } #endif #ifdef CONFIG_COMPAT COMPAT_SYSCALL_DEFINE4(wait4, compat_pid_t, pid, compat_uint_t __user *, stat_addr, int, options, struct compat_rusage __user *, ru) { struct rusage r; long err = kernel_wait4(pid, stat_addr, options, ru ? &r : NULL); if (err > 0) { if (ru && put_compat_rusage(&r, ru)) return -EFAULT; } return err; } COMPAT_SYSCALL_DEFINE5(waitid, int, which, compat_pid_t, pid, struct compat_siginfo __user *, infop, int, options, struct compat_rusage __user *, uru) { struct rusage ru; struct waitid_info info = {.status = 0}; long err = kernel_waitid(which, pid, &info, options, uru ? &ru : NULL); int signo = 0; if (err > 0) { signo = SIGCHLD; err = 0; } if (!err && uru) { /* kernel_waitid() overwrites everything in ru */ if (COMPAT_USE_64BIT_TIME) err = copy_to_user(uru, &ru, sizeof(ru)); else err = put_compat_rusage(&ru, uru); if (err) return -EFAULT; } if (!infop) return err; user_access_begin(); unsafe_put_user(signo, &infop->si_signo, Efault); unsafe_put_user(0, &infop->si_errno, Efault); unsafe_put_user(info.cause, &infop->si_code, Efault); unsafe_put_user(info.pid, &infop->si_pid, Efault); unsafe_put_user(info.uid, &infop->si_uid, Efault); unsafe_put_user(info.status, &infop->si_status, Efault); user_access_end(); return err; Efault: user_access_end(); return -EFAULT; } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2825_0
crossvul-cpp_data_bad_5073_0
/* * linux/fs/isofs/rock.c * * (C) 1992, 1993 Eric Youngdale * * Rock Ridge Extensions to iso9660 */ #include <linux/slab.h> #include <linux/pagemap.h> #include "isofs.h" #include "rock.h" /* * These functions are designed to read the system areas of a directory record * and extract relevant information. There are different functions provided * depending upon what information we need at the time. One function fills * out an inode structure, a second one extracts a filename, a third one * returns a symbolic link name, and a fourth one returns the extent number * for the file. */ #define SIG(A,B) ((A) | ((B) << 8)) /* isonum_721() */ struct rock_state { void *buffer; unsigned char *chr; int len; int cont_size; int cont_extent; int cont_offset; int cont_loops; struct inode *inode; }; /* * This is a way of ensuring that we have something in the system * use fields that is compatible with Rock Ridge. Return zero on success. */ static int check_sp(struct rock_ridge *rr, struct inode *inode) { if (rr->u.SP.magic[0] != 0xbe) return -1; if (rr->u.SP.magic[1] != 0xef) return -1; ISOFS_SB(inode->i_sb)->s_rock_offset = rr->u.SP.skip; return 0; } static void setup_rock_ridge(struct iso_directory_record *de, struct inode *inode, struct rock_state *rs) { rs->len = sizeof(struct iso_directory_record) + de->name_len[0]; if (rs->len & 1) (rs->len)++; rs->chr = (unsigned char *)de + rs->len; rs->len = *((unsigned char *)de) - rs->len; if (rs->len < 0) rs->len = 0; if (ISOFS_SB(inode->i_sb)->s_rock_offset != -1) { rs->len -= ISOFS_SB(inode->i_sb)->s_rock_offset; rs->chr += ISOFS_SB(inode->i_sb)->s_rock_offset; if (rs->len < 0) rs->len = 0; } } static void init_rock_state(struct rock_state *rs, struct inode *inode) { memset(rs, 0, sizeof(*rs)); rs->inode = inode; } /* Maximum number of Rock Ridge continuation entries */ #define RR_MAX_CE_ENTRIES 32 /* * Returns 0 if the caller should continue scanning, 1 if the scan must end * and -ve on error. */ static int rock_continue(struct rock_state *rs) { int ret = 1; int blocksize = 1 << rs->inode->i_blkbits; const int min_de_size = offsetof(struct rock_ridge, u); kfree(rs->buffer); rs->buffer = NULL; if ((unsigned)rs->cont_offset > blocksize - min_de_size || (unsigned)rs->cont_size > blocksize || (unsigned)(rs->cont_offset + rs->cont_size) > blocksize) { printk(KERN_NOTICE "rock: corrupted directory entry. " "extent=%d, offset=%d, size=%d\n", rs->cont_extent, rs->cont_offset, rs->cont_size); ret = -EIO; goto out; } if (rs->cont_extent) { struct buffer_head *bh; rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL); if (!rs->buffer) { ret = -ENOMEM; goto out; } ret = -EIO; if (++rs->cont_loops >= RR_MAX_CE_ENTRIES) goto out; bh = sb_bread(rs->inode->i_sb, rs->cont_extent); if (bh) { memcpy(rs->buffer, bh->b_data + rs->cont_offset, rs->cont_size); put_bh(bh); rs->chr = rs->buffer; rs->len = rs->cont_size; rs->cont_extent = 0; rs->cont_size = 0; rs->cont_offset = 0; return 0; } printk("Unable to read rock-ridge attributes\n"); } out: kfree(rs->buffer); rs->buffer = NULL; return ret; } /* * We think there's a record of type `sig' at rs->chr. Parse the signature * and make sure that there's really room for a record of that type. */ static int rock_check_overflow(struct rock_state *rs, int sig) { int len; switch (sig) { case SIG('S', 'P'): len = sizeof(struct SU_SP_s); break; case SIG('C', 'E'): len = sizeof(struct SU_CE_s); break; case SIG('E', 'R'): len = sizeof(struct SU_ER_s); break; case SIG('R', 'R'): len = sizeof(struct RR_RR_s); break; case SIG('P', 'X'): len = sizeof(struct RR_PX_s); break; case SIG('P', 'N'): len = sizeof(struct RR_PN_s); break; case SIG('S', 'L'): len = sizeof(struct RR_SL_s); break; case SIG('N', 'M'): len = sizeof(struct RR_NM_s); break; case SIG('C', 'L'): len = sizeof(struct RR_CL_s); break; case SIG('P', 'L'): len = sizeof(struct RR_PL_s); break; case SIG('T', 'F'): len = sizeof(struct RR_TF_s); break; case SIG('Z', 'F'): len = sizeof(struct RR_ZF_s); break; default: len = 0; break; } len += offsetof(struct rock_ridge, u); if (len > rs->len) { printk(KERN_NOTICE "rock: directory entry would overflow " "storage\n"); printk(KERN_NOTICE "rock: sig=0x%02x, size=%d, remaining=%d\n", sig, len, rs->len); return -EIO; } return 0; } /* * return length of name field; 0: not found, -1: to be ignored */ int get_rock_ridge_filename(struct iso_directory_record *de, char *retname, struct inode *inode) { struct rock_state rs; struct rock_ridge *rr; int sig; int retnamlen = 0; int truncate = 0; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; *retname = 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_NM) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('N', 'M'): if (truncate) break; if (rr->len < 5) break; /* * If the flags are 2 or 4, this indicates '.' or '..'. * We don't want to do anything with this, because it * screws up the code that calls us. We don't really * care anyways, since we can just use the non-RR * name. */ if (rr->u.NM.flags & 6) break; if (rr->u.NM.flags & ~1) { printk("Unsupported NM flag settings (%d)\n", rr->u.NM.flags); break; } if ((strlen(retname) + rr->len - 5) >= 254) { truncate = 1; break; } strncat(retname, rr->u.NM.name, rr->len - 5); retnamlen += rr->len - 5; break; case SIG('R', 'E'): kfree(rs.buffer); return -1; default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) return retnamlen; /* If 0, this file did not have a NM field */ out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } #define RR_REGARD_XA 1 #define RR_RELOC_DE 2 static int parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int flags) { int symlink_len = 0; int cnt, sig; unsigned int reloc_block; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (flags & RR_REGARD_XA) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): /* Invalid length of ER tag id? */ if (rr->u.ER.len_id + offsetof(struct rock_ridge, u.ER.data) > rr->len) goto out; ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG "ISO 9660 Extensions: "); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk("%c", rr->u.ER.data[p]); } printk("\n"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk("Symlink component flag " "not implemented\n"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING "Attempt to read inode for " "relocated directory\n"); goto out; case SIG('C', 'L'): if (flags & RR_RELOC_DE) { printk(KERN_ERR "ISOFS: Recursive directory relocation " "is not supported\n"); goto eio; } reloc_block = isonum_733(rr->u.CL.location); if (reloc_block == ISOFS_I(inode)->i_iget5_block && ISOFS_I(inode)->i_iget5_offset == 0) { printk(KERN_ERR "ISOFS: Directory relocation points to " "itself\n"); goto eio; } ISOFS_I(inode)->i_first_extent = reloc_block; reloc = isofs_iget_reloc(inode->i_sb, reloc_block, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING "isofs: " "Can't handle ZF block " "size of 2^%d\n", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING "isofs: Unknown ZF compression " "algorithm: %c%c\n", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } static char *get_symlink_chunk(char *rpnt, struct rock_ridge *rr, char *plimit) { int slen; int rootflag; struct SL_component *oldslp; struct SL_component *slp; slen = rr->len - 5; slp = &rr->u.SL.link; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: if (slp->len > plimit - rpnt) return NULL; memcpy(rpnt, slp->text, slp->len); rpnt += slp->len; break; case 2: if (rpnt >= plimit) return NULL; *rpnt++ = '.'; break; case 4: if (2 > plimit - rpnt) return NULL; *rpnt++ = '.'; *rpnt++ = '.'; break; case 8: if (rpnt >= plimit) return NULL; rootflag = 1; *rpnt++ = '/'; break; default: printk("Symlink component flag not implemented (%d)\n", slp->flags); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *)((char *)slp + slp->len + 2); if (slen < 2) { /* * If there is another SL record, and this component * record isn't continued, then add a slash. */ if ((!rootflag) && (rr->u.SL.flags & 1) && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } break; } /* * If this component record isn't continued, then append a '/'. */ if (!rootflag && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } } return rpnt; } int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode, int relocated) { int flags = relocated ? RR_RELOC_DE : 0; int result = parse_rock_ridge_inode_internal(de, inode, flags); /* * if rockridge flag was reset and we didn't look for attributes * behind eventual XA attributes, have a look there */ if ((ISOFS_SB(inode->i_sb)->s_rock_offset == -1) && (ISOFS_SB(inode->i_sb)->s_rock == 2)) { result = parse_rock_ridge_inode_internal(de, inode, flags | RR_REGARD_XA); } return result; } /* * readpage() for symlinks: reads symlink contents into the page and either * makes it uptodate and returns 0 or returns error (-EIO) */ static int rock_ridge_symlink_readpage(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct iso_inode_info *ei = ISOFS_I(inode); struct isofs_sb_info *sbi = ISOFS_SB(inode->i_sb); char *link = page_address(page); unsigned long bufsize = ISOFS_BUFFER_SIZE(inode); struct buffer_head *bh; char *rpnt = link; unsigned char *pnt; struct iso_directory_record *raw_de; unsigned long block, offset; int sig; struct rock_ridge *rr; struct rock_state rs; int ret; if (!sbi->s_rock) goto error; init_rock_state(&rs, inode); block = ei->i_iget5_block; bh = sb_bread(inode->i_sb, block); if (!bh) goto out_noread; offset = ei->i_iget5_offset; pnt = (unsigned char *)bh->b_data + offset; raw_de = (struct iso_directory_record *)pnt; /* * If we go past the end of the buffer, there is some sort of error. */ if (offset + *pnt > bufsize) goto out_bad_span; /* * Now test for possible Rock Ridge extensions which will override * some of these numbers in the inode structure. */ setup_rock_ridge(raw_de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto out; rs.chr += rr->len; rs.len -= rr->len; if (rs.len < 0) goto out; /* corrupted isofs */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_SL) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('S', 'L'): rpnt = get_symlink_chunk(rpnt, rr, link + (PAGE_SIZE - 1)); if (rpnt == NULL) goto out; break; case SIG('C', 'E'): /* This tells is if there is a continuation record */ rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret < 0) goto fail; if (rpnt == link) goto fail; brelse(bh); *rpnt = '\0'; SetPageUptodate(page); unlock_page(page); return 0; /* error exit from macro */ out: kfree(rs.buffer); goto fail; out_noread: printk("unable to read i-node block"); goto fail; out_bad_span: printk("symlink spans iso9660 blocks\n"); fail: brelse(bh); error: SetPageError(page); unlock_page(page); return -EIO; } const struct address_space_operations isofs_symlink_aops = { .readpage = rock_ridge_symlink_readpage };
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5073_0
crossvul-cpp_data_bad_187_0
/* ecc.c * * Copyright (C) 2006-2017 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /* in case user set HAVE_ECC there */ #include <wolfssl/wolfcrypt/settings.h> /* Possible ECC enable options: * HAVE_ECC: Overall control of ECC default: on * HAVE_ECC_ENCRYPT: ECC encrypt/decrypt w/AES and HKDF default: off * HAVE_ECC_SIGN: ECC sign default: on * HAVE_ECC_VERIFY: ECC verify default: on * HAVE_ECC_DHE: ECC build shared secret default: on * HAVE_ECC_CDH: ECC cofactor DH shared secret default: off * HAVE_ECC_KEY_IMPORT: ECC Key import default: on * HAVE_ECC_KEY_EXPORT: ECC Key export default: on * ECC_SHAMIR: Enables Shamir calc method default: on * HAVE_COMP_KEY: Enables compressed key default: off * WOLFSSL_VALIDATE_ECC_IMPORT: Validate ECC key on import default: off * WOLFSSL_VALIDATE_ECC_KEYGEN: Validate ECC key gen default: off * WOLFSSL_CUSTOM_CURVES: Allow non-standard curves. default: off * Includes the curve "a" variable in calculation * ECC_DUMP_OID: Enables dump of OID encoding and sum default: off * ECC_CACHE_CURVE: Enables cache of curve info to improve perofrmance default: off * FP_ECC: ECC Fixed Point Cache default: off * USE_ECC_B_PARAM: Enable ECC curve B param default: off (on for HAVE_COMP_KEY) */ /* ECC Curve Types: * NO_ECC_SECP Disables SECP curves default: off (not defined) * HAVE_ECC_SECPR2 Enables SECP R2 curves default: off * HAVE_ECC_SECPR3 Enables SECP R3 curves default: off * HAVE_ECC_BRAINPOOL Enables Brainpool curves default: off * HAVE_ECC_KOBLITZ Enables Koblitz curves default: off */ /* ECC Curve Sizes: * ECC_USER_CURVES: Allows custom combination of key sizes below * HAVE_ALL_CURVES: Enable all key sizes (on unless ECC_USER_CURVES is defined) * HAVE_ECC112: 112 bit key * HAVE_ECC128: 128 bit key * HAVE_ECC160: 160 bit key * HAVE_ECC192: 192 bit key * HAVE_ECC224: 224 bit key * HAVE_ECC239: 239 bit key * NO_ECC256: Disables 256 bit key (on by default) * HAVE_ECC320: 320 bit key * HAVE_ECC384: 384 bit key * HAVE_ECC512: 512 bit key * HAVE_ECC521: 521 bit key */ #ifdef HAVE_ECC /* Make sure custom curves is enabled for Brainpool or Koblitz curve types */ #if (defined(HAVE_ECC_BRAINPOOL) || defined(HAVE_ECC_KOBLITZ)) &&\ !defined(WOLFSSL_CUSTOM_CURVES) #error Brainpool and Koblitz curves requires WOLFSSL_CUSTOM_CURVES #endif /* Make sure ASN is enabled for ECC sign/verify */ #if (defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY)) && defined(NO_ASN) #error ASN must be enabled for ECC sign/verify #endif #if defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API #pragma code_seg(".fipsA$e2") #pragma const_seg(".fipsB$e2") #endif #endif #include <wolfssl/wolfcrypt/ecc.h> #include <wolfssl/wolfcrypt/asn.h> #include <wolfssl/wolfcrypt/error-crypt.h> #include <wolfssl/wolfcrypt/logging.h> #include <wolfssl/wolfcrypt/types.h> #ifdef WOLFSSL_HAVE_SP_ECC #include <wolfssl/wolfcrypt/sp.h> #endif #ifdef HAVE_ECC_ENCRYPT #include <wolfssl/wolfcrypt/hmac.h> #include <wolfssl/wolfcrypt/aes.h> #endif #ifdef HAVE_X963_KDF #include <wolfssl/wolfcrypt/hash.h> #endif #ifdef WOLF_CRYPTO_DEV #include <wolfssl/wolfcrypt/cryptodev.h> #endif #ifdef NO_INLINE #include <wolfssl/wolfcrypt/misc.h> #else #define WOLFSSL_MISC_INCLUDED #include <wolfcrypt/src/misc.c> #endif #if defined(FREESCALE_LTC_ECC) #include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h> #endif #ifdef WOLFSSL_SP_MATH #define GEN_MEM_ERR MP_MEM #elif defined(USE_FAST_MATH) #define GEN_MEM_ERR FP_MEM #else #define GEN_MEM_ERR MP_MEM #endif /* internal ECC states */ enum { ECC_STATE_NONE = 0, ECC_STATE_SHARED_SEC_GEN, ECC_STATE_SHARED_SEC_RES, ECC_STATE_SIGN_DO, ECC_STATE_SIGN_ENCODE, ECC_STATE_VERIFY_DECODE, ECC_STATE_VERIFY_DO, ECC_STATE_VERIFY_RES, }; /* map ptmul -> mulmod */ /* 256-bit curve on by default whether user curves or not */ #if defined(HAVE_ECC112) || defined(HAVE_ALL_CURVES) #define ECC112 #endif #if defined(HAVE_ECC128) || defined(HAVE_ALL_CURVES) #define ECC128 #endif #if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES) #define ECC160 #endif #if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES) #define ECC192 #endif #if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES) #define ECC224 #endif #if defined(HAVE_ECC239) || defined(HAVE_ALL_CURVES) #define ECC239 #endif #if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES) #define ECC256 #endif #if defined(HAVE_ECC320) || defined(HAVE_ALL_CURVES) #define ECC320 #endif #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES) #define ECC384 #endif #if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES) #define ECC512 #endif #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES) #define ECC521 #endif /* The encoded OID's for ECC curves */ #ifdef ECC112 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp112r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,6 #else 0x2B,0x81,0x04,0x00,0x06 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_secp112r2[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,7 #else 0x2B,0x81,0x04,0x00,0x07 #endif }; #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC112 */ #ifdef ECC128 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp128r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,28 #else 0x2B,0x81,0x04,0x00,0x1C #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_secp128r2[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,29 #else 0x2B,0x81,0x04,0x00,0x1D #endif }; #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC128 */ #ifdef ECC160 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp160r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,8 #else 0x2B,0x81,0x04,0x00,0x08 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_secp160r2[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,30 #else 0x2B,0x81,0x04,0x00,0x1E #endif }; #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp160k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,9 #else 0x2B,0x81,0x04,0x00,0x09 #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp160r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,1 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x01 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC160 */ #ifdef ECC192 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp192r1[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,1 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x01 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_prime192v2[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,2 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x02 #endif }; #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 static const ecc_oid_t ecc_oid_prime192v3[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,3 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x03 #endif }; #endif /* HAVE_ECC_SECPR3 */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp192k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,31 #else 0x2B,0x81,0x04,0x00,0x1F #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp192r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,3 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x03 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC192 */ #ifdef ECC224 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp224r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,33 #else 0x2B,0x81,0x04,0x00,0x21 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp224k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,32 #else 0x2B,0x81,0x04,0x00,0x20 #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp224r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,5 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x05 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC224 */ #ifdef ECC239 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_prime239v1[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,4 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x04 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_prime239v2[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,5 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x05 #endif }; #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 static const ecc_oid_t ecc_oid_prime239v3[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,6 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x06 #endif }; #endif /* HAVE_ECC_SECPR3 */ #endif /* ECC239 */ #ifdef ECC256 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp256r1[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,7 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp256k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,10 #else 0x2B,0x81,0x04,0x00,0x0A #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp256r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,7 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x07 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC256 */ #ifdef ECC320 #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp320r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,9 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x09 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC320 */ #ifdef ECC384 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp384r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,34 #else 0x2B,0x81,0x04,0x00,0x22 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp384r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,11 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0B #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC384 */ #ifdef ECC512 #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp512r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,13 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0D #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC512 */ #ifdef ECC521 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp521r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,35 #else 0x2B,0x81,0x04,0x00,0x23 #endif }; #endif /* !NO_ECC_SECP */ #endif /* ECC521 */ /* This holds the key settings. ***MUST*** be organized by size from smallest to largest. */ const ecc_set_type ecc_sets[] = { #ifdef ECC112 #ifndef NO_ECC_SECP { 14, /* size/bytes */ ECC_SECP112R1, /* ID */ "SECP112R1", /* curve name */ "DB7C2ABF62E35E668076BEAD208B", /* prime */ "DB7C2ABF62E35E668076BEAD2088", /* A */ "659EF8BA043916EEDE8911702B22", /* B */ "DB7C2ABF62E35E7628DFAC6561C5", /* order */ "9487239995A5EE76B55F9C2F098", /* Gx */ "A89CE5AF8724C0A23E0E0FF77500", /* Gy */ ecc_oid_secp112r1, /* oid/oidSz */ sizeof(ecc_oid_secp112r1) / sizeof(ecc_oid_t), ECC_SECP112R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 14, /* size/bytes */ ECC_SECP112R2, /* ID */ "SECP112R2", /* curve name */ "DB7C2ABF62E35E668076BEAD208B", /* prime */ "6127C24C05F38A0AAAF65C0EF02C", /* A */ "51DEF1815DB5ED74FCC34C85D709", /* B */ "36DF0AAFD8B8D7597CA10520D04B", /* order */ "4BA30AB5E892B4E1649DD0928643", /* Gx */ "ADCD46F5882E3747DEF36E956E97", /* Gy */ ecc_oid_secp112r2, /* oid/oidSz */ sizeof(ecc_oid_secp112r2) / sizeof(ecc_oid_t), ECC_SECP112R2_OID, /* oid sum */ 4, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC112 */ #ifdef ECC128 #ifndef NO_ECC_SECP { 16, /* size/bytes */ ECC_SECP128R1, /* ID */ "SECP128R1", /* curve name */ "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC", /* A */ "E87579C11079F43DD824993C2CEE5ED3", /* B */ "FFFFFFFE0000000075A30D1B9038A115", /* order */ "161FF7528B899B2D0C28607CA52C5B86", /* Gx */ "CF5AC8395BAFEB13C02DA292DDED7A83", /* Gy */ ecc_oid_secp128r1, /* oid/oidSz */ sizeof(ecc_oid_secp128r1) / sizeof(ecc_oid_t), ECC_SECP128R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 16, /* size/bytes */ ECC_SECP128R2, /* ID */ "SECP128R2", /* curve name */ "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "D6031998D1B3BBFEBF59CC9BBFF9AEE1", /* A */ "5EEEFCA380D02919DC2C6558BB6D8A5D", /* B */ "3FFFFFFF7FFFFFFFBE0024720613B5A3", /* order */ "7B6AA5D85E572983E6FB32A7CDEBC140", /* Gx */ "27B6916A894D3AEE7106FE805FC34B44", /* Gy */ ecc_oid_secp128r2, /* oid/oidSz */ sizeof(ecc_oid_secp128r2) / sizeof(ecc_oid_t), ECC_SECP128R2_OID, /* oid sum */ 4, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC128 */ #ifdef ECC160 #ifndef NO_ECC_SECP { 20, /* size/bytes */ ECC_SECP160R1, /* ID */ "SECP160R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC", /* A */ "1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45", /* B */ "100000000000000000001F4C8F927AED3CA752257",/* order */ "4A96B5688EF573284664698968C38BB913CBFC82", /* Gx */ "23A628553168947D59DCC912042351377AC5FB32", /* Gy */ ecc_oid_secp160r1, /* oid/oidSz */ sizeof(ecc_oid_secp160r1) / sizeof(ecc_oid_t), ECC_SECP160R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 20, /* size/bytes */ ECC_SECP160R2, /* ID */ "SECP160R2", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70", /* A */ "B4E134D3FB59EB8BAB57274904664D5AF50388BA", /* B */ "100000000000000000000351EE786A818F3A1A16B",/* order */ "52DCB034293A117E1F4FF11B30F7199D3144CE6D", /* Gx */ "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E", /* Gy */ ecc_oid_secp160r2, /* oid/oidSz */ sizeof(ecc_oid_secp160r2) / sizeof(ecc_oid_t), ECC_SECP160R2_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_KOBLITZ { 20, /* size/bytes */ ECC_SECP160K1, /* ID */ "SECP160K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */ "0000000000000000000000000000000000000000", /* A */ "0000000000000000000000000000000000000007", /* B */ "100000000000000000001B8FA16DFAB9ACA16B6B3",/* order */ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", /* Gx */ "938CF935318FDCED6BC28286531733C3F03C4FEE", /* Gy */ ecc_oid_secp160k1, /* oid/oidSz */ sizeof(ecc_oid_secp160k1) / sizeof(ecc_oid_t), ECC_SECP160K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 20, /* size/bytes */ ECC_BRAINPOOLP160R1, /* ID */ "BRAINPOOLP160R1", /* curve name */ "E95E4A5F737059DC60DFC7AD95B3D8139515620F", /* prime */ "340E7BE2A280EB74E2BE61BADA745D97E8F7C300", /* A */ "1E589A8595423412134FAA2DBDEC95C8D8675E58", /* B */ "E95E4A5F737059DC60DF5991D45029409E60FC09", /* order */ "BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC3", /* Gx */ "1667CB477A1A8EC338F94741669C976316DA6321", /* Gy */ ecc_oid_brainpoolp160r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp160r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP160R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC160 */ #ifdef ECC192 #ifndef NO_ECC_SECP { 24, /* size/bytes */ ECC_SECP192R1, /* ID */ "SECP192R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */ "64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831", /* order */ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", /* Gx */ "7192B95FFC8DA78631011ED6B24CDD573F977A11E794811", /* Gy */ ecc_oid_secp192r1, /* oid/oidSz */ sizeof(ecc_oid_secp192r1) / sizeof(ecc_oid_t), ECC_SECP192R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 24, /* size/bytes */ ECC_PRIME192V2, /* ID */ "PRIME192V2", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */ "CC22D6DFB95C6B25E49C0D6364A4E5980C393AA21668D953", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFE5FB1A724DC80418648D8DD31", /* order */ "EEA2BAE7E1497842F2DE7769CFE9C989C072AD696F48034A", /* Gx */ "6574D11D69B6EC7A672BB82A083DF2F2B0847DE970B2DE15", /* Gy */ ecc_oid_prime192v2, /* oid/oidSz */ sizeof(ecc_oid_prime192v2) / sizeof(ecc_oid_t), ECC_PRIME192V2_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 { 24, /* size/bytes */ ECC_PRIME192V3, /* ID */ "PRIME192V3", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */ "22123DC2395A05CAA7423DAECCC94760A7D462256BD56916", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFF7A62D031C83F4294F640EC13", /* order */ "7D29778100C65A1DA1783716588DCE2B8B4AEE8E228F1896", /* Gx */ "38A90F22637337334B49DCB66A6DC8F9978ACA7648A943B0", /* Gy */ ecc_oid_prime192v3, /* oid/oidSz */ sizeof(ecc_oid_prime192v3) / sizeof(ecc_oid_t), ECC_PRIME192V3_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR3 */ #ifdef HAVE_ECC_KOBLITZ { 24, /* size/bytes */ ECC_SECP192K1, /* ID */ "SECP192K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", /* prime */ "000000000000000000000000000000000000000000000000", /* A */ "000000000000000000000000000000000000000000000003", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", /* order */ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", /* Gx */ "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", /* Gy */ ecc_oid_secp192k1, /* oid/oidSz */ sizeof(ecc_oid_secp192k1) / sizeof(ecc_oid_t), ECC_SECP192K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 24, /* size/bytes */ ECC_BRAINPOOLP192R1, /* ID */ "BRAINPOOLP192R1", /* curve name */ "C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", /* prime */ "6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", /* A */ "469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", /* B */ "C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", /* order */ "C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD6", /* Gx */ "14B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F", /* Gy */ ecc_oid_brainpoolp192r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp192r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP192R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC192 */ #ifdef ECC224 #ifndef NO_ECC_SECP { 28, /* size/bytes */ ECC_SECP224R1, /* ID */ "SECP224R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", /* A */ "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", /* order */ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", /* Gx */ "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", /* Gy */ ecc_oid_secp224r1, /* oid/oidSz */ sizeof(ecc_oid_secp224r1) / sizeof(ecc_oid_t), ECC_SECP224R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ { 28, /* size/bytes */ ECC_SECP224K1, /* ID */ "SECP224K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", /* prime */ "00000000000000000000000000000000000000000000000000000000", /* A */ "00000000000000000000000000000000000000000000000000000005", /* B */ "10000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7",/* order */ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", /* Gx */ "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", /* Gy */ ecc_oid_secp224k1, /* oid/oidSz */ sizeof(ecc_oid_secp224k1) / sizeof(ecc_oid_t), ECC_SECP224K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 28, /* size/bytes */ ECC_BRAINPOOLP224R1, /* ID */ "BRAINPOOLP224R1", /* curve name */ "D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", /* prime */ "68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", /* A */ "2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", /* B */ "D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", /* order */ "0D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D", /* Gx */ "58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD", /* Gy */ ecc_oid_brainpoolp224r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp224r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP224R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC224 */ #ifdef ECC239 #ifndef NO_ECC_SECP { 30, /* size/bytes */ ECC_PRIME239V1, /* ID */ "PRIME239V1", /* curve name */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */ "6B016C3BDCF18941D0D654921475CA71A9DB2FB27D1D37796185C2942C0A", /* B */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF9E5E9A9F5D9071FBD1522688909D0B", /* order */ "0FFA963CDCA8816CCC33B8642BEDF905C3D358573D3F27FBBD3B3CB9AAAF", /* Gx */ "7DEBE8E4E90A5DAE6E4054CA530BA04654B36818CE226B39FCCB7B02F1AE", /* Gy */ ecc_oid_prime239v1, /* oid/oidSz */ sizeof(ecc_oid_prime239v1) / sizeof(ecc_oid_t), ECC_PRIME239V1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 30, /* size/bytes */ ECC_PRIME239V2, /* ID */ "PRIME239V2", /* curve name */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */ "617FAB6832576CBBFED50D99F0249C3FEE58B94BA0038C7AE84C8C832F2C", /* B */ "7FFFFFFFFFFFFFFFFFFFFFFF800000CFA7E8594377D414C03821BC582063", /* order */ "38AF09D98727705120C921BB5E9E26296A3CDCF2F35757A0EAFD87B830E7", /* Gx */ "5B0125E4DBEA0EC7206DA0FC01D9B081329FB555DE6EF460237DFF8BE4BA", /* Gy */ ecc_oid_prime239v2, /* oid/oidSz */ sizeof(ecc_oid_prime239v2) / sizeof(ecc_oid_t), ECC_PRIME239V2_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 { 30, /* size/bytes */ ECC_PRIME239V3, /* ID */ "PRIME239V3", /* curve name */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */ "255705FA2A306654B1F4CB03D6A750A30C250102D4988717D9BA15AB6D3E", /* B */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF975DEB41B3A6057C3C432146526551", /* order */ "6768AE8E18BB92CFCF005C949AA2C6D94853D0E660BBF854B1C9505FE95A", /* Gx */ "1607E6898F390C06BC1D552BAD226F3B6FCFE48B6E818499AF18E3ED6CF3", /* Gy */ ecc_oid_prime239v3, /* oid/oidSz */ sizeof(ecc_oid_prime239v3) / sizeof(ecc_oid_t), ECC_PRIME239V3_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR3 */ #endif /* ECC239 */ #ifdef ECC256 #ifndef NO_ECC_SECP { 32, /* size/bytes */ ECC_SECP256R1, /* ID */ "SECP256R1", /* curve name */ "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", /* A */ "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", /* B */ "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", /* order */ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", /* Gx */ "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", /* Gy */ ecc_oid_secp256r1, /* oid/oidSz */ sizeof(ecc_oid_secp256r1) / sizeof(ecc_oid_t), ECC_SECP256R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ { 32, /* size/bytes */ ECC_SECP256K1, /* ID */ "SECP256K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", /* prime */ "0000000000000000000000000000000000000000000000000000000000000000", /* A */ "0000000000000000000000000000000000000000000000000000000000000007", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", /* order */ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", /* Gx */ "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", /* Gy */ ecc_oid_secp256k1, /* oid/oidSz */ sizeof(ecc_oid_secp256k1) / sizeof(ecc_oid_t), ECC_SECP256K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 32, /* size/bytes */ ECC_BRAINPOOLP256R1, /* ID */ "BRAINPOOLP256R1", /* curve name */ "A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", /* prime */ "7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", /* A */ "26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", /* B */ "A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", /* order */ "8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262", /* Gx */ "547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997", /* Gy */ ecc_oid_brainpoolp256r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp256r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP256R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC256 */ #ifdef ECC320 #ifdef HAVE_ECC_BRAINPOOL { 40, /* size/bytes */ ECC_BRAINPOOLP320R1, /* ID */ "BRAINPOOLP320R1", /* curve name */ "D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", /* prime */ "3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", /* A */ "520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", /* B */ "D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", /* order */ "43BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E20611", /* Gx */ "14FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1", /* Gy */ ecc_oid_brainpoolp320r1, sizeof(ecc_oid_brainpoolp320r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_BRAINPOOLP320R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC320 */ #ifdef ECC384 #ifndef NO_ECC_SECP { 48, /* size/bytes */ ECC_SECP384R1, /* ID */ "SECP384R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", /* A */ "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", /* order */ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", /* Gx */ "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", /* Gy */ ecc_oid_secp384r1, sizeof(ecc_oid_secp384r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_SECP384R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_BRAINPOOL { 48, /* size/bytes */ ECC_BRAINPOOLP384R1, /* ID */ "BRAINPOOLP384R1", /* curve name */ "8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", /* prime */ "7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", /* A */ "04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", /* B */ "8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", /* order */ "1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E", /* Gx */ "8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315", /* Gy */ ecc_oid_brainpoolp384r1, sizeof(ecc_oid_brainpoolp384r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_BRAINPOOLP384R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC384 */ #ifdef ECC512 #ifdef HAVE_ECC_BRAINPOOL { 64, /* size/bytes */ ECC_BRAINPOOLP512R1, /* ID */ "BRAINPOOLP512R1", /* curve name */ "AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", /* prime */ "7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", /* A */ "3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", /* B */ "AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", /* order */ "81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822", /* Gx */ "7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892", /* Gy */ ecc_oid_brainpoolp512r1, sizeof(ecc_oid_brainpoolp512r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_BRAINPOOLP512R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC512 */ #ifdef ECC521 #ifndef NO_ECC_SECP { 66, /* size/bytes */ ECC_SECP521R1, /* ID */ "SECP521R1", /* curve name */ "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", /* A */ "51953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", /* B */ "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", /* order */ "C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", /* Gx */ "11839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", /* Gy */ ecc_oid_secp521r1, sizeof(ecc_oid_secp521r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_SECP521R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #endif /* ECC521 */ #if defined(WOLFSSL_CUSTOM_CURVES) && defined(ECC_CACHE_CURVE) /* place holder for custom curve index for cache */ { 1, /* non-zero */ ECC_CURVE_CUSTOM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0 }, #endif { 0, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0 } }; #define ECC_SET_COUNT (sizeof(ecc_sets)/sizeof(ecc_set_type)) #ifdef HAVE_OID_ENCODING /* encoded OID cache */ typedef struct { word32 oidSz; byte oid[ECC_MAX_OID_LEN]; } oid_cache_t; static oid_cache_t ecc_oid_cache[ECC_SET_COUNT]; #endif #ifdef HAVE_COMP_KEY static int wc_ecc_export_x963_compressed(ecc_key*, byte* out, word32* outLen); #endif #ifdef WOLFSSL_ATECC508A typedef void* ecc_curve_spec; #else #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH) static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a, mp_int* prime, mp_int* order); #endif int mp_jacobi(mp_int* a, mp_int* n, int* c); int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret); /* Curve Specs */ typedef struct ecc_curve_spec { const ecc_set_type* dp; mp_int* prime; mp_int* Af; #ifdef USE_ECC_B_PARAM mp_int* Bf; #endif mp_int* order; mp_int* Gx; mp_int* Gy; #ifdef ECC_CACHE_CURVE mp_int prime_lcl; mp_int Af_lcl; #ifdef USE_ECC_B_PARAM mp_int Bf_lcl; #endif mp_int order_lcl; mp_int Gx_lcl; mp_int Gy_lcl; #else mp_int* spec_ints; word32 spec_count; word32 spec_use; #endif byte load_mask; } ecc_curve_spec; enum ecc_curve_load_mask { ECC_CURVE_FIELD_NONE = 0x00, ECC_CURVE_FIELD_PRIME = 0x01, ECC_CURVE_FIELD_AF = 0x02, #ifdef USE_ECC_B_PARAM ECC_CURVE_FIELD_BF = 0x04, #endif ECC_CURVE_FIELD_ORDER = 0x08, ECC_CURVE_FIELD_GX = 0x10, ECC_CURVE_FIELD_GY = 0x20, #ifdef USE_ECC_B_PARAM ECC_CURVE_FIELD_ALL = 0x3F, ECC_CURVE_FIELD_COUNT = 6, #else ECC_CURVE_FIELD_ALL = 0x3B, ECC_CURVE_FIELD_COUNT = 5, #endif }; #ifdef ECC_CACHE_CURVE /* cache (mp_int) of the curve parameters */ static ecc_curve_spec* ecc_curve_spec_cache[ECC_SET_COUNT]; #ifndef SINGLE_THREADED static wolfSSL_Mutex ecc_curve_cache_mutex; #endif #define DECLARE_CURVE_SPECS(intcount) ecc_curve_spec* curve = NULL; #else #define DECLARE_CURVE_SPECS(intcount) \ mp_int spec_ints[(intcount)]; \ ecc_curve_spec curve_lcl; \ ecc_curve_spec* curve = &curve_lcl; \ XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \ curve->spec_ints = spec_ints; \ curve->spec_count = intcount; #endif /* ECC_CACHE_CURVE */ static void _wc_ecc_curve_free(ecc_curve_spec* curve) { if (curve == NULL) { return; } if (curve->load_mask & ECC_CURVE_FIELD_PRIME) mp_clear(curve->prime); if (curve->load_mask & ECC_CURVE_FIELD_AF) mp_clear(curve->Af); #ifdef USE_ECC_B_PARAM if (curve->load_mask & ECC_CURVE_FIELD_BF) mp_clear(curve->Bf); #endif if (curve->load_mask & ECC_CURVE_FIELD_ORDER) mp_clear(curve->order); if (curve->load_mask & ECC_CURVE_FIELD_GX) mp_clear(curve->Gx); if (curve->load_mask & ECC_CURVE_FIELD_GY) mp_clear(curve->Gy); curve->load_mask = 0; } static void wc_ecc_curve_free(ecc_curve_spec* curve) { /* don't free cached curves */ #ifndef ECC_CACHE_CURVE _wc_ecc_curve_free(curve); #endif (void)curve; } static int wc_ecc_curve_load_item(const char* src, mp_int** dst, ecc_curve_spec* curve, byte mask) { int err; #ifndef ECC_CACHE_CURVE /* get mp_int from temp */ if (curve->spec_use >= curve->spec_count) { WOLFSSL_MSG("Invalid DECLARE_CURVE_SPECS count"); return ECC_BAD_ARG_E; } *dst = &curve->spec_ints[curve->spec_use++]; #endif err = mp_init(*dst); if (err == MP_OKAY) { curve->load_mask |= mask; err = mp_read_radix(*dst, src, MP_RADIX_HEX); #ifdef HAVE_WOLF_BIGINT if (err == MP_OKAY) err = wc_mp_to_bigint(*dst, &(*dst)->raw); #endif } return err; } static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve, byte load_mask) { int ret = 0, x; ecc_curve_spec* curve; byte load_items = 0; /* mask of items to load */ if (dp == NULL || pCurve == NULL) return BAD_FUNC_ARG; #ifdef ECC_CACHE_CURVE x = wc_ecc_get_curve_idx(dp->id); if (x == ECC_CURVE_INVALID) return ECC_BAD_ARG_E; #if !defined(SINGLE_THREADED) ret = wc_LockMutex(&ecc_curve_cache_mutex); if (ret != 0) { return ret; } #endif /* make sure cache has been allocated */ if (ecc_curve_spec_cache[x] == NULL) { ecc_curve_spec_cache[x] = (ecc_curve_spec*)XMALLOC( sizeof(ecc_curve_spec), NULL, DYNAMIC_TYPE_ECC); if (ecc_curve_spec_cache[x] == NULL) { #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) wc_UnLockMutex(&ecc_curve_cache_mutex); #endif return MEMORY_E; } XMEMSET(ecc_curve_spec_cache[x], 0, sizeof(ecc_curve_spec)); } /* set curve pointer to cache */ *pCurve = ecc_curve_spec_cache[x]; #endif /* ECC_CACHE_CURVE */ curve = *pCurve; /* make sure the curve is initialized */ if (curve->dp != dp) { curve->load_mask = 0; #ifdef ECC_CACHE_CURVE curve->prime = &curve->prime_lcl; curve->Af = &curve->Af_lcl; #ifdef USE_ECC_B_PARAM curve->Bf = &curve->Bf_lcl; #endif curve->order = &curve->order_lcl; curve->Gx = &curve->Gx_lcl; curve->Gy = &curve->Gy_lcl; #endif } curve->dp = dp; /* set dp info */ /* determine items to load */ load_items = (~curve->load_mask & load_mask); curve->load_mask |= load_items; /* load items */ x = 0; if (load_items & ECC_CURVE_FIELD_PRIME) x += wc_ecc_curve_load_item(dp->prime, &curve->prime, curve, ECC_CURVE_FIELD_PRIME); if (load_items & ECC_CURVE_FIELD_AF) x += wc_ecc_curve_load_item(dp->Af, &curve->Af, curve, ECC_CURVE_FIELD_AF); #ifdef USE_ECC_B_PARAM if (load_items & ECC_CURVE_FIELD_BF) x += wc_ecc_curve_load_item(dp->Bf, &curve->Bf, curve, ECC_CURVE_FIELD_BF); #endif if (load_items & ECC_CURVE_FIELD_ORDER) x += wc_ecc_curve_load_item(dp->order, &curve->order, curve, ECC_CURVE_FIELD_ORDER); if (load_items & ECC_CURVE_FIELD_GX) x += wc_ecc_curve_load_item(dp->Gx, &curve->Gx, curve, ECC_CURVE_FIELD_GX); if (load_items & ECC_CURVE_FIELD_GY) x += wc_ecc_curve_load_item(dp->Gy, &curve->Gy, curve, ECC_CURVE_FIELD_GY); /* check for error */ if (x != 0) { wc_ecc_curve_free(curve); ret = MP_READ_E; } #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) wc_UnLockMutex(&ecc_curve_cache_mutex); #endif return ret; } #ifdef ECC_CACHE_CURVE int wc_ecc_curve_cache_init(void) { int ret = 0; #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) ret = wc_InitMutex(&ecc_curve_cache_mutex); #endif return ret; } void wc_ecc_curve_cache_free(void) { int x; /* free all ECC curve caches */ for (x = 0; x < (int)ECC_SET_COUNT; x++) { if (ecc_curve_spec_cache[x]) { _wc_ecc_curve_free(ecc_curve_spec_cache[x]); XFREE(ecc_curve_spec_cache[x], NULL, DYNAMIC_TYPE_ECC); ecc_curve_spec_cache[x] = NULL; } } #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) wc_FreeMutex(&ecc_curve_cache_mutex); #endif } #endif /* ECC_CACHE_CURVE */ #endif /* WOLFSSL_ATECC508A */ /* Retrieve the curve name for the ECC curve id. * * curve_id The id of the curve. * returns the name stored from the curve if available, otherwise NULL. */ const char* wc_ecc_get_name(int curve_id) { int curve_idx = wc_ecc_get_curve_idx(curve_id); if (curve_idx == ECC_CURVE_INVALID) return NULL; return ecc_sets[curve_idx].name; } int wc_ecc_set_curve(ecc_key* key, int keysize, int curve_id) { if (keysize <= 0 && curve_id < 0) { return BAD_FUNC_ARG; } if (keysize > ECC_MAXSIZE) { return ECC_BAD_ARG_E; } /* handle custom case */ if (key->idx != ECC_CUSTOM_IDX) { int x; /* default values */ key->idx = 0; key->dp = NULL; /* find ecc_set based on curve_id or key size */ for (x = 0; ecc_sets[x].size != 0; x++) { if (curve_id > ECC_CURVE_DEF) { if (curve_id == ecc_sets[x].id) break; } else if (keysize <= ecc_sets[x].size) { break; } } if (ecc_sets[x].size == 0) { WOLFSSL_MSG("ECC Curve not found"); return ECC_CURVE_OID_E; } key->idx = x; key->dp = &ecc_sets[x]; } return 0; } #ifdef ALT_ECC_SIZE static void alt_fp_init(fp_int* a) { a->size = FP_SIZE_ECC; fp_zero(a); } #endif /* ALT_ECC_SIZE */ #ifndef WOLFSSL_ATECC508A #if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_PUBLIC_ECC_ADD_DBL) /** Add two ECC points P The point to add Q The point to add R [out] The destination of the double a ECC curve parameter a modulus The modulus of the field the ECC curve is in mp The "b" value from montgomery_setup() return MP_OKAY on success */ int ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R, mp_int* a, mp_int* modulus, mp_digit mp) { #ifndef WOLFSSL_SP_MATH mp_int t1, t2; #ifdef ALT_ECC_SIZE mp_int rx, ry, rz; #endif mp_int *x, *y, *z; int err; if (P == NULL || Q == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } /* if Q == R then swap P and Q, so we don't require a local x,y,z */ if (Q == R) { ecc_point* tPt = P; P = Q; Q = tPt; } if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return err; } /* should we dbl instead? */ if (err == MP_OKAY) err = mp_sub(modulus, Q->y, &t1); if (err == MP_OKAY) { if ( (mp_cmp(P->x, Q->x) == MP_EQ) && (get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) && (mp_cmp(P->y, Q->y) == MP_EQ || mp_cmp(P->y, &t1) == MP_EQ)) { mp_clear(&t1); mp_clear(&t2); return ecc_projective_dbl_point(P, R, a, modulus, mp); } } if (err != MP_OKAY) { goto done; } /* If use ALT_ECC_SIZE we need to use local stack variable since ecc_point x,y,z is reduced size */ #ifdef ALT_ECC_SIZE /* Use local stack variable */ x = &rx; y = &ry; z = &rz; if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { goto done; } #else /* Use destination directly */ x = R->x; y = R->y; z = R->z; #endif if (err == MP_OKAY) err = mp_copy(P->x, x); if (err == MP_OKAY) err = mp_copy(P->y, y); if (err == MP_OKAY) err = mp_copy(P->z, z); /* if Z is one then these are no-operations */ if (err == MP_OKAY) { if (!mp_iszero(Q->z)) { /* T1 = Z' * Z' */ err = mp_sqr(Q->z, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* X = X * T1 */ if (err == MP_OKAY) err = mp_mul(&t1, x, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* T1 = Z' * T1 */ if (err == MP_OKAY) err = mp_mul(Q->z, &t1, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* Y = Y * T1 */ if (err == MP_OKAY) err = mp_mul(&t1, y, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); } } /* T1 = Z*Z */ if (err == MP_OKAY) err = mp_sqr(z, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* T2 = X' * T1 */ if (err == MP_OKAY) err = mp_mul(Q->x, &t1, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = Z * T1 */ if (err == MP_OKAY) err = mp_mul(z, &t1, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* T1 = Y' * T1 */ if (err == MP_OKAY) err = mp_mul(Q->y, &t1, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* Y = Y - T1 */ if (err == MP_OKAY) err = mp_sub(y, &t1, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } /* T1 = 2T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t1, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = Y + T1 */ if (err == MP_OKAY) err = mp_add(&t1, y, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* X = X - T2 */ if (err == MP_OKAY) err = mp_sub(x, &t2, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* T2 = 2T2 */ if (err == MP_OKAY) err = mp_add(&t2, &t2, &t2); if (err == MP_OKAY) { if (mp_cmp(&t2, modulus) != MP_LT) err = mp_sub(&t2, modulus, &t2); } /* T2 = X + T2 */ if (err == MP_OKAY) err = mp_add(&t2, x, &t2); if (err == MP_OKAY) { if (mp_cmp(&t2, modulus) != MP_LT) err = mp_sub(&t2, modulus, &t2); } if (err == MP_OKAY) { if (!mp_iszero(Q->z)) { /* Z = Z * Z' */ err = mp_mul(z, Q->z, z); if (err == MP_OKAY) err = mp_montgomery_reduce(z, modulus, mp); } } /* Z = Z * X */ if (err == MP_OKAY) err = mp_mul(z, x, z); if (err == MP_OKAY) err = mp_montgomery_reduce(z, modulus, mp); /* T1 = T1 * X */ if (err == MP_OKAY) err = mp_mul(&t1, x, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* X = X * X */ if (err == MP_OKAY) err = mp_sqr(x, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* T2 = T2 * x */ if (err == MP_OKAY) err = mp_mul(&t2, x, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = T1 * X */ if (err == MP_OKAY) err = mp_mul(&t1, x, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* X = Y*Y */ if (err == MP_OKAY) err = mp_sqr(y, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* X = X - T2 */ if (err == MP_OKAY) err = mp_sub(x, &t2, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* T2 = T2 - X */ if (err == MP_OKAY) err = mp_sub(&t2, x, &t2); if (err == MP_OKAY) { if (mp_isneg(&t2)) err = mp_add(&t2, modulus, &t2); } /* T2 = T2 - X */ if (err == MP_OKAY) err = mp_sub(&t2, x, &t2); if (err == MP_OKAY) { if (mp_isneg(&t2)) err = mp_add(&t2, modulus, &t2); } /* T2 = T2 * Y */ if (err == MP_OKAY) err = mp_mul(&t2, y, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* Y = T2 - T1 */ if (err == MP_OKAY) err = mp_sub(&t2, &t1, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } /* Y = Y/2 */ if (err == MP_OKAY) { if (mp_isodd(y) == MP_YES) err = mp_add(y, modulus, y); } if (err == MP_OKAY) err = mp_div_2(y, y); #ifdef ALT_ECC_SIZE if (err == MP_OKAY) err = mp_copy(x, R->x); if (err == MP_OKAY) err = mp_copy(y, R->y); if (err == MP_OKAY) err = mp_copy(z, R->z); #endif done: /* clean up */ mp_clear(&t1); mp_clear(&t2); return err; #else if (P == NULL || Q == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } (void)a; (void)mp; return sp_ecc_proj_add_point_256(P->x, P->y, P->z, Q->x, Q->y, Q->z, R->x, R->y, R->z); #endif } /* ### Point doubling in Jacobian coordinate system ### * * let us have a curve: y^2 = x^3 + a*x + b * in Jacobian coordinates it becomes: y^2 = x^3 + a*x*z^4 + b*z^6 * * The doubling of P = (Xp, Yp, Zp) is given by R = (Xr, Yr, Zr) where: * Xr = M^2 - 2*S * Yr = M * (S - Xr) - 8*T * Zr = 2 * Yp * Zp * * M = 3 * Xp^2 + a*Zp^4 * T = Yp^4 * S = 4 * Xp * Yp^2 * * SPECIAL CASE: when a == 3 we can compute M as * M = 3 * (Xp^2 - Zp^4) = 3 * (Xp + Zp^2) * (Xp - Zp^2) */ /** Double an ECC point P The point to double R [out] The destination of the double a ECC curve parameter a modulus The modulus of the field the ECC curve is in mp The "b" value from montgomery_setup() return MP_OKAY on success */ int ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, mp_int* modulus, mp_digit mp) { #ifndef WOLFSSL_SP_MATH mp_int t1, t2; #ifdef ALT_ECC_SIZE mp_int rx, ry, rz; #endif mp_int *x, *y, *z; int err; if (P == NULL || R == NULL || modulus == NULL) return ECC_BAD_ARG_E; if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return err; } /* If use ALT_ECC_SIZE we need to use local stack variable since ecc_point x,y,z is reduced size */ #ifdef ALT_ECC_SIZE /* Use local stack variable */ x = &rx; y = &ry; z = &rz; if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { mp_clear(&t1); mp_clear(&t2); return err; } #else /* Use destination directly */ x = R->x; y = R->y; z = R->z; #endif if (err == MP_OKAY) err = mp_copy(P->x, x); if (err == MP_OKAY) err = mp_copy(P->y, y); if (err == MP_OKAY) err = mp_copy(P->z, z); /* T1 = Z * Z */ if (err == MP_OKAY) err = mp_sqr(z, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* Z = Y * Z */ if (err == MP_OKAY) err = mp_mul(z, y, z); if (err == MP_OKAY) err = mp_montgomery_reduce(z, modulus, mp); /* Z = 2Z */ if (err == MP_OKAY) err = mp_add(z, z, z); if (err == MP_OKAY) { if (mp_cmp(z, modulus) != MP_LT) err = mp_sub(z, modulus, z); } /* Determine if curve "a" should be used in calc */ #ifdef WOLFSSL_CUSTOM_CURVES if (err == MP_OKAY) { /* Use a and prime to determine if a == 3 */ err = mp_submod(modulus, a, modulus, &t2); } if (err == MP_OKAY && mp_cmp_d(&t2, 3) != MP_EQ) { /* use "a" in calc */ /* T2 = T1 * T1 */ if (err == MP_OKAY) err = mp_sqr(&t1, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = T2 * a */ if (err == MP_OKAY) err = mp_mulmod(&t2, a, modulus, &t1); /* T2 = X * X */ if (err == MP_OKAY) err = mp_sqr(x, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = T2 + T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = T2 + T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = T2 + T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } } else #endif /* WOLFSSL_CUSTOM_CURVES */ { /* assumes "a" == 3 */ (void)a; /* T2 = X - T1 */ if (err == MP_OKAY) err = mp_sub(x, &t1, &t2); if (err == MP_OKAY) { if (mp_isneg(&t2)) err = mp_add(&t2, modulus, &t2); } /* T1 = X + T1 */ if (err == MP_OKAY) err = mp_add(&t1, x, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T2 = T1 * T2 */ if (err == MP_OKAY) err = mp_mul(&t1, &t2, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = 2T2 */ if (err == MP_OKAY) err = mp_add(&t2, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = T1 + T2 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } } /* Y = 2Y */ if (err == MP_OKAY) err = mp_add(y, y, y); if (err == MP_OKAY) { if (mp_cmp(y, modulus) != MP_LT) err = mp_sub(y, modulus, y); } /* Y = Y * Y */ if (err == MP_OKAY) err = mp_sqr(y, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); /* T2 = Y * Y */ if (err == MP_OKAY) err = mp_sqr(y, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T2 = T2/2 */ if (err == MP_OKAY) { if (mp_isodd(&t2) == MP_YES) err = mp_add(&t2, modulus, &t2); } if (err == MP_OKAY) err = mp_div_2(&t2, &t2); /* Y = Y * X */ if (err == MP_OKAY) err = mp_mul(y, x, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); /* X = T1 * T1 */ if (err == MP_OKAY) err = mp_sqr(&t1, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* X = X - Y */ if (err == MP_OKAY) err = mp_sub(x, y, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* X = X - Y */ if (err == MP_OKAY) err = mp_sub(x, y, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* Y = Y - X */ if (err == MP_OKAY) err = mp_sub(y, x, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } /* Y = Y * T1 */ if (err == MP_OKAY) err = mp_mul(y, &t1, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); /* Y = Y - T2 */ if (err == MP_OKAY) err = mp_sub(y, &t2, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } #ifdef ALT_ECC_SIZE if (err == MP_OKAY) err = mp_copy(x, R->x); if (err == MP_OKAY) err = mp_copy(y, R->y); if (err == MP_OKAY) err = mp_copy(z, R->z); #endif /* clean up */ mp_clear(&t1); mp_clear(&t2); return err; #else if (P == NULL || R == NULL || modulus == NULL) return ECC_BAD_ARG_E; (void)a; (void)mp; return sp_ecc_proj_dbl_point_256(P->x, P->y, P->z, R->x, R->y, R->z); #endif } /** Map a projective jacbobian point back to affine space P [in/out] The point to map modulus The modulus of the field the ECC curve is in mp The "b" value from montgomery_setup() return MP_OKAY on success */ int ecc_map(ecc_point* P, mp_int* modulus, mp_digit mp) { #ifndef WOLFSSL_SP_MATH mp_int t1, t2; #ifdef ALT_ECC_SIZE mp_int rx, ry, rz; #endif mp_int *x, *y, *z; int err; if (P == NULL || modulus == NULL) return ECC_BAD_ARG_E; /* special case for point at infinity */ if (mp_cmp_d(P->z, 0) == MP_EQ) { err = mp_set(P->x, 0); if (err == MP_OKAY) err = mp_set(P->y, 0); if (err == MP_OKAY) err = mp_set(P->z, 1); return err; } if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return MEMORY_E; } #ifdef ALT_ECC_SIZE /* Use local stack variable */ x = &rx; y = &ry; z = &rz; if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { goto done; } if (err == MP_OKAY) err = mp_copy(P->x, x); if (err == MP_OKAY) err = mp_copy(P->y, y); if (err == MP_OKAY) err = mp_copy(P->z, z); if (err != MP_OKAY) { goto done; } #else /* Use destination directly */ x = P->x; y = P->y; z = P->z; #endif /* first map z back to normal */ err = mp_montgomery_reduce(z, modulus, mp); /* get 1/z */ if (err == MP_OKAY) err = mp_invmod(z, modulus, &t1); /* get 1/z^2 and 1/z^3 */ if (err == MP_OKAY) err = mp_sqr(&t1, &t2); if (err == MP_OKAY) err = mp_mod(&t2, modulus, &t2); if (err == MP_OKAY) err = mp_mul(&t1, &t2, &t1); if (err == MP_OKAY) err = mp_mod(&t1, modulus, &t1); /* multiply against x/y */ if (err == MP_OKAY) err = mp_mul(x, &t2, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); if (err == MP_OKAY) err = mp_mul(y, &t1, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); if (err == MP_OKAY) err = mp_set(z, 1); #ifdef ALT_ECC_SIZE /* return result */ if (err == MP_OKAY) err = mp_copy(x, P->x); if (err == MP_OKAY) err = mp_copy(y, P->y); if (err == MP_OKAY) err = mp_copy(z, P->z); done: #endif /* clean up */ mp_clear(&t1); mp_clear(&t2); return err; #else if (P == NULL || modulus == NULL) return ECC_BAD_ARG_E; (void)mp; return sp_ecc_map_256(P->x, P->y, P->z); #endif } #endif /* !WOLFSSL_SP_MATH || WOLFSSL_PUBLIC_ECC_ADD_DBL */ #if !defined(FREESCALE_LTC_ECC) #if !defined(FP_ECC) || !defined(WOLFSSL_SP_MATH) /** Perform a point multiplication k The scalar to multiply by G The base point R [out] Destination for kG a ECC curve parameter a modulus The modulus of the field the ECC curve is in map Boolean whether to map back to affine or not (1==map, 0 == leave in projective) return MP_OKAY on success */ #ifdef FP_ECC static int normal_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map, void* heap) #else int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map, void* heap) #endif { #ifndef WOLFSSL_SP_MATH #ifndef ECC_TIMING_RESISTANT /* size of sliding window, don't change this! */ #define WINSIZE 4 #define M_POINTS 8 int first = 1, bitbuf = 0, bitcpy = 0, j; #else #define M_POINTS 3 #endif ecc_point *tG, *M[M_POINTS]; int i, err; mp_int mu; mp_digit mp; mp_digit buf; int bitcnt = 0, mode = 0, digidx = 0; if (k == NULL || G == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } /* init variables */ tG = NULL; XMEMSET(M, 0, sizeof(M)); /* init montgomery reduction */ if ((err = mp_montgomery_setup(modulus, &mp)) != MP_OKAY) { return err; } if ((err = mp_init(&mu)) != MP_OKAY) { return err; } if ((err = mp_montgomery_calc_normalization(&mu, modulus)) != MP_OKAY) { mp_clear(&mu); return err; } /* alloc ram for window temps */ for (i = 0; i < M_POINTS; i++) { M[i] = wc_ecc_new_point_h(heap); if (M[i] == NULL) { mp_clear(&mu); err = MEMORY_E; goto exit; } } /* make a copy of G in case R==G */ tG = wc_ecc_new_point_h(heap); if (tG == NULL) err = MEMORY_E; /* tG = G and convert to montgomery */ if (err == MP_OKAY) { if (mp_cmp_d(&mu, 1) == MP_EQ) { err = mp_copy(G->x, tG->x); if (err == MP_OKAY) err = mp_copy(G->y, tG->y); if (err == MP_OKAY) err = mp_copy(G->z, tG->z); } else { err = mp_mulmod(G->x, &mu, modulus, tG->x); if (err == MP_OKAY) err = mp_mulmod(G->y, &mu, modulus, tG->y); if (err == MP_OKAY) err = mp_mulmod(G->z, &mu, modulus, tG->z); } } /* done with mu */ mp_clear(&mu); #ifndef ECC_TIMING_RESISTANT /* calc the M tab, which holds kG for k==8..15 */ /* M[0] == 8G */ if (err == MP_OKAY) err = ecc_projective_dbl_point(tG, M[0], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp); /* now find (8+k)G for k=1..7 */ if (err == MP_OKAY) for (j = 9; j < 16; j++) { err = ecc_projective_add_point(M[j-9], tG, M[j-M_POINTS], a, modulus, mp); if (err != MP_OKAY) break; } /* setup sliding window */ if (err == MP_OKAY) { mode = 0; bitcnt = 1; buf = 0; digidx = get_digit_count(k) - 1; bitcpy = bitbuf = 0; first = 1; /* perform ops */ for (;;) { /* grab next digit as required */ if (--bitcnt == 0) { if (digidx == -1) { break; } buf = get_digit(k, digidx); bitcnt = (int) DIGIT_BIT; --digidx; } /* grab the next msb from the ltiplicand */ i = (int)(buf >> (DIGIT_BIT - 1)) & 1; buf <<= 1; /* skip leading zero bits */ if (mode == 0 && i == 0) continue; /* if the bit is zero and mode == 1 then we double */ if (mode == 1 && i == 0) { err = ecc_projective_dbl_point(R, R, a, modulus, mp); if (err != MP_OKAY) break; continue; } /* else we add it to the window */ bitbuf |= (i << (WINSIZE - ++bitcpy)); mode = 2; if (bitcpy == WINSIZE) { /* if this is the first window we do a simple copy */ if (first == 1) { /* R = kG [k = first window] */ err = mp_copy(M[bitbuf-M_POINTS]->x, R->x); if (err != MP_OKAY) break; err = mp_copy(M[bitbuf-M_POINTS]->y, R->y); if (err != MP_OKAY) break; err = mp_copy(M[bitbuf-M_POINTS]->z, R->z); first = 0; } else { /* normal window */ /* ok window is filled so double as required and add */ /* double first */ for (j = 0; j < WINSIZE; j++) { err = ecc_projective_dbl_point(R, R, a, modulus, mp); if (err != MP_OKAY) break; } if (err != MP_OKAY) break; /* out of first for(;;) */ /* then add, bitbuf will be 8..15 [8..2^WINSIZE] guaranteed */ err = ecc_projective_add_point(R, M[bitbuf-M_POINTS], R, a, modulus, mp); } if (err != MP_OKAY) break; /* empty window and reset */ bitcpy = bitbuf = 0; mode = 1; } } } /* if bits remain then double/add */ if (err == MP_OKAY) { if (mode == 2 && bitcpy > 0) { /* double then add */ for (j = 0; j < bitcpy; j++) { /* only double if we have had at least one add first */ if (first == 0) { err = ecc_projective_dbl_point(R, R, a, modulus, mp); if (err != MP_OKAY) break; } bitbuf <<= 1; if ((bitbuf & (1 << WINSIZE)) != 0) { if (first == 1) { /* first add, so copy */ err = mp_copy(tG->x, R->x); if (err != MP_OKAY) break; err = mp_copy(tG->y, R->y); if (err != MP_OKAY) break; err = mp_copy(tG->z, R->z); if (err != MP_OKAY) break; first = 0; } else { /* then add */ err = ecc_projective_add_point(R, tG, R, a, modulus, mp); if (err != MP_OKAY) break; } } } } } #undef WINSIZE #else /* ECC_TIMING_RESISTANT */ /* calc the M tab */ /* M[0] == G */ if (err == MP_OKAY) err = mp_copy(tG->x, M[0]->x); if (err == MP_OKAY) err = mp_copy(tG->y, M[0]->y); if (err == MP_OKAY) err = mp_copy(tG->z, M[0]->z); /* M[1] == 2G */ if (err == MP_OKAY) err = ecc_projective_dbl_point(tG, M[1], a, modulus, mp); /* setup sliding window */ mode = 0; bitcnt = 1; buf = 0; digidx = get_digit_count(k) - 1; /* perform ops */ if (err == MP_OKAY) { for (;;) { /* grab next digit as required */ if (--bitcnt == 0) { if (digidx == -1) { break; } buf = get_digit(k, digidx); bitcnt = (int)DIGIT_BIT; --digidx; } /* grab the next msb from the multiplicand */ i = (buf >> (DIGIT_BIT - 1)) & 1; buf <<= 1; if (mode == 0 && i == 0) { /* timing resistant - dummy operations */ if (err == MP_OKAY) err = ecc_projective_add_point(M[0], M[1], M[2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[1], M[2], a, modulus, mp); if (err == MP_OKAY) continue; } if (mode == 0 && i == 1) { mode = 1; /* timing resistant - dummy operations */ if (err == MP_OKAY) err = ecc_projective_add_point(M[0], M[1], M[2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[1], M[2], a, modulus, mp); if (err == MP_OKAY) continue; } if (err == MP_OKAY) err = ecc_projective_add_point(M[0], M[1], M[i^1], a, modulus, mp); #ifdef WC_NO_CACHE_RESISTANT if (err == MP_OKAY) err = ecc_projective_dbl_point(M[i], M[i], a, modulus, mp); #else /* instead of using M[i] for double, which leaks key bit to cache * monitor, use M[2] as temp, make sure address calc is constant, * keep M[0] and M[1] in cache */ if (err == MP_OKAY) err = mp_copy((mp_int*) ( ((wolfssl_word)M[0]->x & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->x & wc_off_on_addr[i])), M[2]->x); if (err == MP_OKAY) err = mp_copy((mp_int*) ( ((wolfssl_word)M[0]->y & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->y & wc_off_on_addr[i])), M[2]->y); if (err == MP_OKAY) err = mp_copy((mp_int*) ( ((wolfssl_word)M[0]->z & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->z & wc_off_on_addr[i])), M[2]->z); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[2], M[2], a, modulus, mp); /* copy M[2] back to M[i] */ if (err == MP_OKAY) err = mp_copy(M[2]->x, (mp_int*) ( ((wolfssl_word)M[0]->x & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->x & wc_off_on_addr[i])) ); if (err == MP_OKAY) err = mp_copy(M[2]->y, (mp_int*) ( ((wolfssl_word)M[0]->y & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->y & wc_off_on_addr[i])) ); if (err == MP_OKAY) err = mp_copy(M[2]->z, (mp_int*) ( ((wolfssl_word)M[0]->z & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->z & wc_off_on_addr[i])) ); if (err != MP_OKAY) break; #endif /* WC_NO_CACHE_RESISTANT */ } /* end for */ } /* copy result out */ if (err == MP_OKAY) err = mp_copy(M[0]->x, R->x); if (err == MP_OKAY) err = mp_copy(M[0]->y, R->y); if (err == MP_OKAY) err = mp_copy(M[0]->z, R->z); #endif /* ECC_TIMING_RESISTANT */ /* map R back from projective space */ if (err == MP_OKAY && map) err = ecc_map(R, modulus, mp); exit: /* done */ wc_ecc_del_point_h(tG, heap); for (i = 0; i < M_POINTS; i++) { wc_ecc_del_point_h(M[i], heap); } return err; #else if (k == NULL || G == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } (void)a; return sp_ecc_mulmod_256(k, G, R, map, heap); #endif } #endif /* !FP_ECC || !WOLFSSL_SP_MATH */ #endif /* !FREESCALE_LTC_ECC */ /** ECC Fixed Point mulmod global k The multiplicand G Base point to multiply R [out] Destination of product a ECC curve parameter a modulus The modulus for the curve map [boolean] If non-zero maps the point back to affine co-ordinates, otherwise it's left in jacobian-montgomery form return MP_OKAY if successful */ int wc_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map) { return wc_ecc_mulmod_ex(k, G, R, a, modulus, map, NULL); } #endif /* !WOLFSSL_ATECC508A */ /** * use a heap hint when creating new ecc_point * return an allocated point on success or NULL on failure */ ecc_point* wc_ecc_new_point_h(void* heap) { ecc_point* p; (void)heap; p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC); if (p == NULL) { return NULL; } XMEMSET(p, 0, sizeof(ecc_point)); #ifndef ALT_ECC_SIZE if (mp_init_multi(p->x, p->y, p->z, NULL, NULL, NULL) != MP_OKAY) { XFREE(p, heap, DYNAMIC_TYPE_ECC); return NULL; } #else p->x = (mp_int*)&p->xyz[0]; p->y = (mp_int*)&p->xyz[1]; p->z = (mp_int*)&p->xyz[2]; alt_fp_init(p->x); alt_fp_init(p->y); alt_fp_init(p->z); #endif return p; } /** Allocate a new ECC point return A newly allocated point or NULL on error */ ecc_point* wc_ecc_new_point(void) { return wc_ecc_new_point_h(NULL); } void wc_ecc_del_point_h(ecc_point* p, void* heap) { /* prevents free'ing null arguments */ if (p != NULL) { mp_clear(p->x); mp_clear(p->y); mp_clear(p->z); XFREE(p, heap, DYNAMIC_TYPE_ECC); } (void)heap; } /** Free an ECC point from memory p The point to free */ void wc_ecc_del_point(ecc_point* p) { wc_ecc_del_point_h(p, NULL); } /** Copy the value of a point to an other one p The point to copy r The created point */ int wc_ecc_copy_point(ecc_point* p, ecc_point *r) { int ret; /* prevents null arguments */ if (p == NULL || r == NULL) return ECC_BAD_ARG_E; ret = mp_copy(p->x, r->x); if (ret != MP_OKAY) return ret; ret = mp_copy(p->y, r->y); if (ret != MP_OKAY) return ret; ret = mp_copy(p->z, r->z); if (ret != MP_OKAY) return ret; return MP_OKAY; } /** Compare the value of a point with an other one a The point to compare b The other point to compare return MP_EQ if equal, MP_LT/MP_GT if not, < 0 in case of error */ int wc_ecc_cmp_point(ecc_point* a, ecc_point *b) { int ret; /* prevents null arguments */ if (a == NULL || b == NULL) return BAD_FUNC_ARG; ret = mp_cmp(a->x, b->x); if (ret != MP_EQ) return ret; ret = mp_cmp(a->y, b->y); if (ret != MP_EQ) return ret; ret = mp_cmp(a->z, b->z); if (ret != MP_EQ) return ret; return MP_EQ; } /** Returns whether an ECC idx is valid or not n The idx number to check return 1 if valid, 0 if not */ int wc_ecc_is_valid_idx(int n) { int x; for (x = 0; ecc_sets[x].size != 0; x++) ; /* -1 is a valid index --- indicating that the domain params were supplied by the user */ if ((n >= ECC_CUSTOM_IDX) && (n < x)) { return 1; } return 0; } int wc_ecc_get_curve_idx(int curve_id) { int curve_idx; for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) { if (curve_id == ecc_sets[curve_idx].id) break; } if (ecc_sets[curve_idx].size == 0) { return ECC_CURVE_INVALID; } return curve_idx; } int wc_ecc_get_curve_id(int curve_idx) { if (wc_ecc_is_valid_idx(curve_idx)) { return ecc_sets[curve_idx].id; } return ECC_CURVE_INVALID; } /* Returns the curve size that corresponds to a given ecc_curve_id identifier * * id curve id, from ecc_curve_id enum in ecc.h * return curve size, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_size_from_id(int curve_id) { int curve_idx = wc_ecc_get_curve_idx(curve_id); if (curve_idx == ECC_CURVE_INVALID) return ECC_BAD_ARG_E; return ecc_sets[curve_idx].size; } /* Returns the curve index that corresponds to a given curve name in * ecc_sets[] of ecc.c * * name curve name, from ecc_sets[].name in ecc.c * return curve index in ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_idx_from_name(const char* curveName) { int curve_idx; word32 len; if (curveName == NULL) return BAD_FUNC_ARG; len = (word32)XSTRLEN(curveName); for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) { if (ecc_sets[curve_idx].name && XSTRNCASECMP(ecc_sets[curve_idx].name, curveName, len) == 0) { break; } } if (ecc_sets[curve_idx].size == 0) { WOLFSSL_MSG("ecc_set curve name not found"); return ECC_CURVE_INVALID; } return curve_idx; } /* Returns the curve size that corresponds to a given curve name, * as listed in ecc_sets[] of ecc.c. * * name curve name, from ecc_sets[].name in ecc.c * return curve size, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_size_from_name(const char* curveName) { int curve_idx; if (curveName == NULL) return BAD_FUNC_ARG; curve_idx = wc_ecc_get_curve_idx_from_name(curveName); if (curve_idx < 0) return curve_idx; return ecc_sets[curve_idx].size; } /* Returns the curve id that corresponds to a given curve name, * as listed in ecc_sets[] of ecc.c. * * name curve name, from ecc_sets[].name in ecc.c * return curve id, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_id_from_name(const char* curveName) { int curve_idx; if (curveName == NULL) return BAD_FUNC_ARG; curve_idx = wc_ecc_get_curve_idx_from_name(curveName); if (curve_idx < 0) return curve_idx; return ecc_sets[curve_idx].id; } /* Compares a curve parameter (hex, from ecc_sets[]) to given input * parameter (byte array) for equality. * * Returns MP_EQ on success, negative on error */ static int wc_ecc_cmp_param(const char* curveParam, const byte* param, word32 paramSz) { int err = MP_OKAY; mp_int a, b; if (param == NULL || curveParam == NULL) return BAD_FUNC_ARG; if ((err = mp_init_multi(&a, &b, NULL, NULL, NULL, NULL)) != MP_OKAY) return err; if (err == MP_OKAY) err = mp_read_unsigned_bin(&a, param, paramSz); if (err == MP_OKAY) err = mp_read_radix(&b, curveParam, MP_RADIX_HEX); if (err == MP_OKAY) { if (mp_cmp(&a, &b) != MP_EQ) { err = -1; } else { err = MP_EQ; } } mp_clear(&a); mp_clear(&b); return err; } /* Returns the curve id in ecc_sets[] that corresponds to a given set of * curve parameters. * * fieldSize the field size in bits * prime prime of the finite field * primeSz size of prime in octets * Af first coefficient a of the curve * AfSz size of Af in octets * Bf second coefficient b of the curve * BfSz size of Bf in octets * order curve order * orderSz size of curve in octets * Gx affine x coordinate of base point * GxSz size of Gx in octets * Gy affine y coordinate of base point * GySz size of Gy in octets * cofactor curve cofactor * * return curve id, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_id_from_params(int fieldSize, const byte* prime, word32 primeSz, const byte* Af, word32 AfSz, const byte* Bf, word32 BfSz, const byte* order, word32 orderSz, const byte* Gx, word32 GxSz, const byte* Gy, word32 GySz, int cofactor) { int idx; int curveSz; if (prime == NULL || Af == NULL || Bf == NULL || order == NULL || Gx == NULL || Gy == NULL) return BAD_FUNC_ARG; curveSz = (fieldSize + 1) / 8; /* round up */ for (idx = 0; ecc_sets[idx].size != 0; idx++) { if (curveSz == ecc_sets[idx].size) { if ((wc_ecc_cmp_param(ecc_sets[idx].prime, prime, primeSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Af, Af, AfSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Bf, Bf, BfSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].order, order, orderSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Gx, Gx, GxSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Gy, Gy, GySz) == MP_EQ) && (cofactor == ecc_sets[idx].cofactor)) { break; } } } if (ecc_sets[idx].size == 0) return ECC_CURVE_INVALID; return ecc_sets[idx].id; } #ifdef WOLFSSL_ASYNC_CRYPT static INLINE int wc_ecc_alloc_mpint(ecc_key* key, mp_int** mp) { if (key == NULL || mp == NULL) return BAD_FUNC_ARG; if (*mp == NULL) { *mp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_BIGINT); if (*mp == NULL) { return MEMORY_E; } XMEMSET(*mp, 0, sizeof(mp_int)); } return 0; } static INLINE void wc_ecc_free_mpint(ecc_key* key, mp_int** mp) { if (key && mp && *mp) { mp_clear(*mp); XFREE(*mp, key->heap, DYNAMIC_TYPE_BIGINT); *mp = NULL; } } static int wc_ecc_alloc_async(ecc_key* key) { int err = wc_ecc_alloc_mpint(key, &key->r); if (err == 0) err = wc_ecc_alloc_mpint(key, &key->s); return err; } static void wc_ecc_free_async(ecc_key* key) { wc_ecc_free_mpint(key, &key->r); wc_ecc_free_mpint(key, &key->s); #ifdef HAVE_CAVIUM_V wc_ecc_free_mpint(key, &key->e); wc_ecc_free_mpint(key, &key->signK); #endif /* HAVE_CAVIUM_V */ } #endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef HAVE_ECC_DHE /** Create an ECC shared secret between two keys private_key The private ECC key (heap hint based off of private key) public_key The public key out [out] Destination of the shared secret Conforms to EC-DH from ANSI X9.63 outlen [in/out] The max size and resulting size of the shared secret return MP_OKAY if successful */ int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out, word32* outlen) { int err; if (private_key == NULL || public_key == NULL || out == NULL || outlen == NULL) { return BAD_FUNC_ARG; } #ifdef WOLF_CRYPTO_DEV if (private_key->devId != INVALID_DEVID) { err = wc_CryptoDev_Ecdh(private_key, public_key, out, outlen); if (err != NOT_COMPILED_IN) return err; } #endif /* type valid? */ if (private_key->type != ECC_PRIVATEKEY && private_key->type != ECC_PRIVATEKEY_ONLY) { return ECC_BAD_ARG_E; } /* Verify domain params supplied */ if (wc_ecc_is_valid_idx(private_key->idx) == 0 || wc_ecc_is_valid_idx(public_key->idx) == 0) { return ECC_BAD_ARG_E; } /* Verify curve id matches */ if (private_key->dp->id != public_key->dp->id) { return ECC_BAD_ARG_E; } #ifdef WOLFSSL_ATECC508A err = atcatls_ecdh(private_key->slot, public_key->pubkey_raw, out); if (err != ATCA_SUCCESS) { err = BAD_COND_E; } *outlen = private_key->dp->size; #else err = wc_ecc_shared_secret_ex(private_key, &public_key->pubkey, out, outlen); #endif /* WOLFSSL_ATECC508A */ return err; } #ifndef WOLFSSL_ATECC508A static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, byte* out, word32* outlen, ecc_curve_spec* curve) { int err; #ifndef WOLFSSL_SP_MATH ecc_point* result = NULL; word32 x = 0; #endif mp_int* k = &private_key->k; #ifdef HAVE_ECC_CDH mp_int k_lcl; /* if cofactor flag has been set */ if (private_key->flags & WC_ECC_FLAG_COFACTOR) { mp_digit cofactor = (mp_digit)private_key->dp->cofactor; /* only perform cofactor calc if not equal to 1 */ if (cofactor != 1) { k = &k_lcl; if (mp_init(k) != MP_OKAY) return MEMORY_E; /* multiply cofactor times private key "k" */ err = mp_mul_d(&private_key->k, cofactor, k); if (err != MP_OKAY) { mp_clear(k); return err; } } } #endif #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (private_key->idx != ECC_CUSTOM_IDX && ecc_sets[private_key->idx].id == ECC_SECP256R1) { err = sp_ecc_secret_gen_256(k, point, out, outlen, private_key->heap); } else #endif #endif #ifdef WOLFSSL_SP_MATH { err = WC_KEY_SIZE_E; (void)curve; } #else { /* make new point */ result = wc_ecc_new_point_h(private_key->heap); if (result == NULL) { #ifdef HAVE_ECC_CDH if (k == &k_lcl) mp_clear(k); #endif return MEMORY_E; } err = wc_ecc_mulmod_ex(k, point, result, curve->Af, curve->prime, 1, private_key->heap); if (err == MP_OKAY) { x = mp_unsigned_bin_size(curve->prime); if (*outlen < x) { err = BUFFER_E; } } if (err == MP_OKAY) { XMEMSET(out, 0, x); err = mp_to_unsigned_bin(result->x,out + (x - mp_unsigned_bin_size(result->x))); } *outlen = x; wc_ecc_del_point_h(result, private_key->heap); } #endif #ifdef HAVE_ECC_CDH if (k == &k_lcl) mp_clear(k); #endif return err; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, ecc_point* point, byte* out, word32 *outlen, ecc_curve_spec* curve) { int err; #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) #ifdef HAVE_CAVIUM_V /* verify the curve is supported by hardware */ if (NitroxEccIsCurveSupported(private_key)) #endif { word32 keySz = private_key->dp->size; /* sync public key x/y */ err = wc_mp_to_bigint_sz(&private_key->k, &private_key->k.raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(point->x, &point->x->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(point->y, &point->y->raw, keySz); #ifdef HAVE_CAVIUM_V /* allocate buffer for output */ if (err == MP_OKAY) err = wc_ecc_alloc_mpint(private_key, &private_key->e); if (err == MP_OKAY) err = wc_bigint_alloc(&private_key->e->raw, NitroxEccGetSize(private_key)*2); if (err == MP_OKAY) err = NitroxEcdh(private_key, &private_key->k.raw, &point->x->raw, &point->y->raw, private_key->e->raw.buf, &private_key->e->raw.len, &curve->prime->raw); #else if (err == MP_OKAY) err = wc_ecc_curve_load(private_key->dp, &curve, ECC_CURVE_FIELD_BF); if (err == MP_OKAY) err = IntelQaEcdh(&private_key->asyncDev, &private_key->k.raw, &point->x->raw, &point->y->raw, out, outlen, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, private_key->dp->cofactor); #endif return err; } #elif defined(WOLFSSL_ASYNC_CRYPT_TEST) if (wc_AsyncTestInit(&private_key->asyncDev, ASYNC_TEST_ECC_SHARED_SEC)) { WC_ASYNC_TEST* testDev = &private_key->asyncDev.test; testDev->eccSharedSec.private_key = private_key; testDev->eccSharedSec.public_point = point; testDev->eccSharedSec.out = out; testDev->eccSharedSec.outLen = outlen; return WC_PENDING_E; } #endif /* use sync in other cases */ err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen, curve); return err; } #endif /* WOLFSSL_ASYNC_CRYPT */ int wc_ecc_shared_secret_gen(ecc_key* private_key, ecc_point* point, byte* out, word32 *outlen) { int err; DECLARE_CURVE_SPECS(2) if (private_key == NULL || point == NULL || out == NULL || outlen == NULL) { return BAD_FUNC_ARG; } /* load curve info */ err = wc_ecc_curve_load(private_key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF)); if (err != MP_OKAY) return err; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { err = wc_ecc_shared_secret_gen_async(private_key, point, out, outlen, curve); } else #endif { err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen, curve); } wc_ecc_curve_free(curve); return err; } /** Create an ECC shared secret between private key and public point private_key The private ECC key (heap hint based on private key) point The point to use (public key) out [out] Destination of the shared secret Conforms to EC-DH from ANSI X9.63 outlen [in/out] The max size and resulting size of the shared secret return MP_OKAY if successful */ int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point, byte* out, word32 *outlen) { int err; if (private_key == NULL || point == NULL || out == NULL || outlen == NULL) { return BAD_FUNC_ARG; } /* type valid? */ if (private_key->type != ECC_PRIVATEKEY && private_key->type != ECC_PRIVATEKEY_ONLY) { return ECC_BAD_ARG_E; } /* Verify domain params supplied */ if (wc_ecc_is_valid_idx(private_key->idx) == 0) return ECC_BAD_ARG_E; switch(private_key->state) { case ECC_STATE_NONE: case ECC_STATE_SHARED_SEC_GEN: private_key->state = ECC_STATE_SHARED_SEC_GEN; err = wc_ecc_shared_secret_gen(private_key, point, out, outlen); if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_SHARED_SEC_RES: private_key->state = ECC_STATE_SHARED_SEC_RES; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #ifdef HAVE_CAVIUM_V /* verify the curve is supported by hardware */ if (NitroxEccIsCurveSupported(private_key)) { /* copy output */ *outlen = private_key->dp->size; XMEMCPY(out, private_key->e->raw.buf, *outlen); } #endif /* HAVE_CAVIUM_V */ } #endif /* WOLFSSL_ASYNC_CRYPT */ err = 0; break; default: err = BAD_STATE_E; } /* switch */ /* if async pending then return and skip done cleanup below */ if (err == WC_PENDING_E) { private_key->state++; return err; } /* cleanup */ #ifdef WOLFSSL_ASYNC_CRYPT wc_ecc_free_async(private_key); #endif private_key->state = ECC_STATE_NONE; return err; } #endif /* !WOLFSSL_ATECC508A */ #endif /* HAVE_ECC_DHE */ #ifndef WOLFSSL_ATECC508A /* return 1 if point is at infinity, 0 if not, < 0 on error */ int wc_ecc_point_is_at_infinity(ecc_point* p) { if (p == NULL) return BAD_FUNC_ARG; if (get_digit_count(p->x) == 0 && get_digit_count(p->y) == 0) return 1; return 0; } #ifndef WOLFSSL_SP_MATH /* generate random and ensure its greater than 0 and less than order */ static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) { int err; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_MAXSIZE_GEN]; #endif #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /*generate 8 extra bytes to mitigate bias from the modulo operation below*/ /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/ size += 8; /* make up random string */ err = wc_RNG_GenerateBlock(rng, buf, size); /* load random buffer data into k */ if (err == 0) err = mp_read_unsigned_bin(k, (byte*)buf, size); /* quick sanity check to make sure we're not dealing with a 0 key */ if (err == MP_OKAY) { if (mp_iszero(k) == MP_YES) err = MP_ZERO_E; } /* the key should be smaller than the order of base point */ if (err == MP_OKAY) { if (mp_cmp(k, order) != MP_LT) { err = mp_mod(k, order, k); } } ForceZero(buf, ECC_MAXSIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return err; } #endif #endif /* !WOLFSSL_ATECC508A */ static INLINE void wc_ecc_reset(ecc_key* key) { /* make sure required key variables are reset */ key->state = ECC_STATE_NONE; } /* create the public ECC key from a private key * * key an initialized private key to generate public part from * curveIn [in]curve for key, can be NULL * pubOut [out]ecc_point holding the public key, if NULL then public key part * is cached in key instead. * * Note this function is local to the file because of the argument type * ecc_curve_spec. Having this argument allows for not having to load the * curve type multiple times when generating a key with wc_ecc_make_key(). * * returns MP_OKAY on success */ static int wc_ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn, ecc_point* pubOut) { int err = MP_OKAY; #ifndef WOLFSSL_ATECC508A #ifndef WOLFSSL_SP_MATH ecc_point* base = NULL; #endif ecc_point* pub; DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT) #endif if (key == NULL) { return BAD_FUNC_ARG; } #ifndef WOLFSSL_ATECC508A /* if ecc_point passed in then use it as output for public key point */ if (pubOut != NULL) { pub = pubOut; } else { /* caching public key making it a ECC_PRIVATEKEY instead of ECC_PRIVATEKEY_ONLY */ pub = &key->pubkey; key->type = ECC_PRIVATEKEY_ONLY; } /* avoid loading the curve unless it is not passed in */ if (curveIn != NULL) { curve = curveIn; } else { /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); } if (err == MP_OKAY) { #ifndef ALT_ECC_SIZE err = mp_init_multi(pub->x, pub->y, pub->z, NULL, NULL, NULL); #else pub->x = (mp_int*)&pub->xyz[0]; pub->y = (mp_int*)&pub->xyz[1]; pub->z = (mp_int*)&pub->xyz[2]; alt_fp_init(pub->x); alt_fp_init(pub->y); alt_fp_init(pub->z); #endif } #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { if (err == MP_OKAY) err = sp_ecc_mulmod_base_256(&key->k, pub, 1, key->heap); } else #endif #endif #ifdef WOLFSSL_SP_MATH err = WC_KEY_SIZE_E; #else { if (err == MP_OKAY) { base = wc_ecc_new_point_h(key->heap); if (base == NULL) err = MEMORY_E; } /* read in the x/y for this key */ if (err == MP_OKAY) err = mp_copy(curve->Gx, base->x); if (err == MP_OKAY) err = mp_copy(curve->Gy, base->y); if (err == MP_OKAY) err = mp_set(base->z, 1); /* make the public key */ if (err == MP_OKAY) { err = wc_ecc_mulmod_ex(&key->k, base, pub, curve->Af, curve->prime, 1, key->heap); } wc_ecc_del_point_h(base, key->heap); } #endif #ifdef WOLFSSL_VALIDATE_ECC_KEYGEN /* validate the public key, order * pubkey = point at infinity */ if (err == MP_OKAY) err = ecc_check_pubkey_order(key, pub, curve->Af, curve->prime, curve->order); #endif /* WOLFSSL_VALIDATE_KEYGEN */ if (err != MP_OKAY) { /* clean up if failed */ #ifndef ALT_ECC_SIZE mp_clear(pub->x); mp_clear(pub->y); mp_clear(pub->z); #endif } /* free up local curve */ if (curveIn == NULL) { wc_ecc_curve_free(curve); } #endif /* WOLFSSL_ATECC508A */ /* change key state if public part is cached */ if (key->type == ECC_PRIVATEKEY_ONLY && pubOut == NULL) { key->type = ECC_PRIVATEKEY; } return err; } /* create the public ECC key from a private key * * key an initialized private key to generate public part from * pubOut [out]ecc_point holding the public key, if NULL then public key part * is cached in key instead. * * * returns MP_OKAY on success */ int wc_ecc_make_pub(ecc_key* key, ecc_point* pubOut) { WOLFSSL_ENTER("wc_ecc_make_pub"); return wc_ecc_make_pub_ex(key, NULL, pubOut); } int wc_ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id) { int err; #ifndef WOLFSSL_ATECC508A DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT) #endif if (key == NULL || rng == NULL) { return BAD_FUNC_ARG; } /* make sure required variables are reset */ wc_ecc_reset(key); err = wc_ecc_set_curve(key, keysize, curve_id); if (err != 0) { return err; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #ifdef HAVE_CAVIUM /* TODO: Not implemented */ #elif defined(HAVE_INTEL_QA) /* TODO: Not implemented */ #else if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_MAKE)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->eccMake.rng = rng; testDev->eccMake.key = key; testDev->eccMake.size = keysize; testDev->eccMake.curve_id = curve_id; return WC_PENDING_E; } #endif } #endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef WOLFSSL_ATECC508A key->type = ECC_PRIVATEKEY; err = atcatls_create_key(key->slot, key->pubkey_raw); if (err != ATCA_SUCCESS) { err = BAD_COND_E; } /* populate key->pubkey */ err = mp_read_unsigned_bin(key->pubkey.x, key->pubkey_raw, ECC_MAX_CRYPTO_HW_SIZE); if (err = MP_OKAY) err = mp_read_unsigned_bin(key->pubkey.y, key->pubkey_raw + ECC_MAX_CRYPTO_HW_SIZE, ECC_MAX_CRYPTO_HW_SIZE); #else #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { err = sp_ecc_make_key_256(rng, &key->k, &key->pubkey, key->heap); if (err == MP_OKAY) key->type = ECC_PRIVATEKEY; } else #endif #endif #ifdef WOLFSSL_SP_MATH err = WC_KEY_SIZE_E; #else { /* setup the key variables */ err = mp_init(&key->k); /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); /* generate k */ if (err == MP_OKAY) err = wc_ecc_gen_k(rng, key->dp->size, &key->k, curve->order); /* generate public key from k */ if (err == MP_OKAY) err = wc_ecc_make_pub_ex(key, curve, NULL); if (err == MP_OKAY) key->type = ECC_PRIVATEKEY; /* cleanup these on failure case only */ if (err != MP_OKAY) { /* clean up */ mp_forcezero(&key->k); } /* cleanup allocations */ wc_ecc_curve_free(curve); } #endif #endif /* WOLFSSL_ATECC508A */ return err; } #ifdef ECC_DUMP_OID /* Optional dump of encoded OID for adding new curves */ static int mOidDumpDone; static void wc_ecc_dump_oids(void) { int x; if (mOidDumpDone) { return; } /* find matching OID sum (based on encoded value) */ for (x = 0; ecc_sets[x].size != 0; x++) { int i; byte* oid; word32 oidSz, sum = 0; printf("ECC %s (%d):\n", ecc_sets[x].name, x); #ifdef HAVE_OID_ENCODING byte oidEnc[ECC_MAX_OID_LEN]; oid = oidEnc; oidSz = ECC_MAX_OID_LEN; printf("OID: "); for (i = 0; i < (int)ecc_sets[x].oidSz; i++) { printf("%d.", ecc_sets[x].oid[i]); } printf("\n"); EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz, oidEnc, &oidSz); #else oid = (byte*)ecc_sets[x].oid; oidSz = ecc_sets[x].oidSz; #endif printf("OID Encoded: "); for (i = 0; i < (int)oidSz; i++) { printf("0x%02X,", oid[i]); } printf("\n"); for (i = 0; i < (int)oidSz; i++) { sum += oid[i]; } printf("Sum: %d\n", sum); /* validate sum */ if (ecc_sets[x].oidSum != sum) { printf(" Sum %d Not Valid!\n", ecc_sets[x].oidSum); } } mOidDumpDone = 1; } #endif /* ECC_DUMP_OID */ /** Make a new ECC key rng An active RNG state keysize The keysize for the new key (in octets from 20 to 65 bytes) key [out] Destination of the newly created key return MP_OKAY if successful, upon error all allocated memory will be freed */ int wc_ecc_make_key(WC_RNG* rng, int keysize, ecc_key* key) { return wc_ecc_make_key_ex(rng, keysize, key, ECC_CURVE_DEF); } /* Setup dynamic pointers if using normal math for proper freeing */ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) { int ret = 0; if (key == NULL) { return BAD_FUNC_ARG; } #ifdef ECC_DUMP_OID wc_ecc_dump_oids(); #endif XMEMSET(key, 0, sizeof(ecc_key)); key->state = ECC_STATE_NONE; #if defined(PLUTON_CRYPTO_ECC) || defined(WOLF_CRYPTO_DEV) key->devId = devId; #else (void)devId; #endif #ifdef WOLFSSL_ATECC508A key->slot = atmel_ecc_alloc(); if (key->slot == ATECC_INVALID_SLOT) { return ECC_BAD_ARG_E; } #else #ifdef ALT_ECC_SIZE key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); ret = mp_init(&key->k); #else ret = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif /* ALT_ECC_SIZE */ if (ret != MP_OKAY) { return MEMORY_E; } #endif /* WOLFSSL_ATECC508A */ #ifdef WOLFSSL_HEAP_TEST key->heap = (void*)WOLFSSL_HEAP_TEST; #else key->heap = heap; #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) /* handle as async */ ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC, key->heap, devId); #endif return ret; } int wc_ecc_init(ecc_key* key) { return wc_ecc_init_ex(key, NULL, INVALID_DEVID); } int wc_ecc_set_flags(ecc_key* key, word32 flags) { if (key == NULL) { return BAD_FUNC_ARG; } key->flags |= flags; return 0; } #ifdef HAVE_ECC_SIGN #ifndef NO_ASN #if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) static int wc_ecc_sign_hash_hw(const byte* in, word32 inlen, mp_int* r, mp_int* s, byte* out, word32 *outlen, WC_RNG* rng, ecc_key* key) { int err; #ifdef PLUTON_CRYPTO_ECC if (key->devId != INVALID_DEVID) /* use hardware */ #endif { int keysize = key->dp->size; /* Check args */ if (keysize > ECC_MAX_CRYPTO_HW_SIZE || inlen != keysize || *outlen < keysize*2) { return ECC_BAD_ARG_E; } #if defined(WOLFSSL_ATECC508A) /* Sign: Result is 32-bytes of R then 32-bytes of S */ err = atcatls_sign(key->slot, in, out); if (err != ATCA_SUCCESS) { return BAD_COND_E; } #elif defined(PLUTON_CRYPTO_ECC) { /* perform ECC sign */ word32 raw_sig_size = *outlen; err = Crypto_EccSign(in, inlen, out, &raw_sig_size); if (err != CRYPTO_RES_SUCCESS || raw_sig_size != keysize*2){ return BAD_COND_E; } } #endif /* Load R and S */ err = mp_read_unsigned_bin(r, &out[0], keysize); if (err != MP_OKAY) { return err; } err = mp_read_unsigned_bin(s, &out[keysize], keysize); if (err != MP_OKAY) { return err; } /* Check for zeros */ if (mp_iszero(r) || mp_iszero(s)) { return MP_ZERO_E; } } #ifdef PLUTON_CRYPTO_ECC else { err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s); } #endif return err; } #endif /* WOLFSSL_ATECC508A || PLUTON_CRYPTO_ECC */ /** Sign a message digest in The message digest to sign inlen The length of the digest out [out] The destination for the signature outlen [in/out] The max size and resulting size of the signature key A private ECC key return MP_OKAY if successful */ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, WC_RNG* rng, ecc_key* key) { int err; mp_int *r = NULL, *s = NULL; #ifndef WOLFSSL_ASYNC_CRYPT mp_int r_lcl, s_lcl; #endif if (in == NULL || out == NULL || outlen == NULL || key == NULL || rng == NULL) { return ECC_BAD_ARG_E; } #ifdef WOLF_CRYPTO_DEV if (key->devId != INVALID_DEVID) { err = wc_CryptoDev_EccSign(in, inlen, out, outlen, rng, key); if (err != NOT_COMPILED_IN) return err; } #endif #ifdef WOLFSSL_ASYNC_CRYPT err = wc_ecc_alloc_async(key); if (err != 0) return err; r = key->r; s = key->s; #else r = &r_lcl; s = &s_lcl; #endif switch(key->state) { case ECC_STATE_NONE: case ECC_STATE_SIGN_DO: key->state = ECC_STATE_SIGN_DO; if ((err = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY){ break; } /* hardware crypto */ #if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) err = wc_ecc_sign_hash_hw(in, inlen, r, s, out, outlen, rng, key); #else err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s); #endif if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_SIGN_ENCODE: key->state = ECC_STATE_SIGN_ENCODE; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #ifdef HAVE_CAVIUM_V /* Nitrox requires r and s in sep buffer, so split it */ NitroxEccRsSplit(key, &r->raw, &s->raw); #endif #ifndef WOLFSSL_ASYNC_CRYPT_TEST /* only do this if not simulator, since it overwrites result */ wc_bigint_to_mp(&r->raw, r); wc_bigint_to_mp(&s->raw, s); #endif } #endif /* WOLFSSL_ASYNC_CRYPT */ /* encoded with DSA header */ err = StoreECC_DSA_Sig(out, outlen, r, s); /* done with R/S */ mp_clear(r); mp_clear(s); break; default: err = BAD_STATE_E; break; } /* if async pending then return and skip done cleanup below */ if (err == WC_PENDING_E) { key->state++; return err; } /* cleanup */ #ifdef WOLFSSL_ASYNC_CRYPT wc_ecc_free_async(key); #endif key->state = ECC_STATE_NONE; return err; } #endif /* !NO_ASN */ #ifndef WOLFSSL_ATECC508A /** Sign a message digest in The message digest to sign inlen The length of the digest key A private ECC key r [out] The destination for r component of the signature s [out] The destination for s component of the signature return MP_OKAY if successful */ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, ecc_key* key, mp_int *r, mp_int *s) { int err; #ifndef WOLFSSL_SP_MATH mp_int* e; #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) mp_int e_lcl; #endif #endif /* !WOLFSSL_SP_MATH */ DECLARE_CURVE_SPECS(1) if (in == NULL || r == NULL || s == NULL || key == NULL || rng == NULL) return ECC_BAD_ARG_E; /* is this a private key? */ if (key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY) { return ECC_BAD_ARG_E; } /* is the IDX valid ? */ if (wc_ecc_is_valid_idx(key->idx) != 1) { return ECC_BAD_ARG_E; } #ifdef WOLFSSL_SP_MATH if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->heap); else return WC_KEY_SIZE_E; #else #ifdef WOLFSSL_HAVE_SP_ECC #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC) #endif { #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->heap); #endif } #endif /* WOLFSSL_HAVE_SP_ECC */ #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_SIGN)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->eccSign.in = in; testDev->eccSign.inSz = inlen; testDev->eccSign.rng = rng; testDev->eccSign.key = key; testDev->eccSign.r = r; testDev->eccSign.s = s; return WC_PENDING_E; } } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) err = wc_ecc_alloc_mpint(key, &key->e); if (err != 0) return err; e = key->e; #else e = &e_lcl; #endif /* get the hash and load it as a bignum into 'e' */ /* init the bignums */ if ((err = mp_init(e)) != MP_OKAY) { return err; } /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER); /* load digest into e */ if (err == MP_OKAY) { /* we may need to truncate if hash is longer than key size */ word32 orderBits = mp_count_bits(curve->order); /* truncate down to byte size, may be all that's needed */ if ((WOLFSSL_BIT_SIZE * inlen) > orderBits) inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE; err = mp_read_unsigned_bin(e, (byte*)in, inlen); /* may still need bit truncation too */ if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits) mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); } /* make up a key and export the public copy */ if (err == MP_OKAY) { int loop_check = 0; ecc_key pubkey; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) #ifdef HAVE_CAVIUM_V if (NitroxEccIsCurveSupported(key)) #endif { word32 keySz = key->dp->size; mp_int* k; #ifdef HAVE_CAVIUM_V err = wc_ecc_alloc_mpint(key, &key->signK); if (err != 0) return err; k = key->signK; #else mp_int k_lcl; k = &k_lcl; #endif err = mp_init(k); /* make sure r and s are allocated */ #ifdef HAVE_CAVIUM_V /* Nitrox V needs single buffer for R and S */ if (err == MP_OKAY) err = wc_bigint_alloc(&key->r->raw, NitroxEccGetSize(key)*2); /* Nitrox V only needs Prime and Order */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_ORDER)); #else if (err == MP_OKAY) err = wc_bigint_alloc(&key->r->raw, key->dp->size); if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); #endif if (err == MP_OKAY) err = wc_bigint_alloc(&key->s->raw, key->dp->size); /* load e and k */ if (err == MP_OKAY) err = wc_mp_to_bigint_sz(e, &e->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz); if (err == MP_OKAY) err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(k, &k->raw, keySz); #ifdef HAVE_CAVIUM_V if (err == MP_OKAY) err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw, &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw); #else if (err == MP_OKAY) err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw, &k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, &curve->Gy->raw); #endif #ifndef HAVE_CAVIUM_V mp_clear(e); mp_clear(k); #endif wc_ecc_curve_free(curve); return err; } #endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */ } #endif /* WOLFSSL_ASYNC_CRYPT */ /* don't use async for key, since we don't support async return here */ if ((err = wc_ecc_init_ex(&pubkey, key->heap, INVALID_DEVID)) == MP_OKAY) { #ifdef WOLFSSL_CUSTOM_CURVES /* if custom curve, apply params to pubkey */ if (key->idx == ECC_CUSTOM_IDX) { err = wc_ecc_set_custom_curve(&pubkey, key->dp); } #endif for (; err == MP_OKAY;) { if (++loop_check > 64) { err = RNG_FAILURE_E; break; } err = wc_ecc_make_key_ex(rng, key->dp->size, &pubkey, key->dp->id); if (err != MP_OKAY) break; /* find r = x1 mod n */ err = mp_mod(pubkey.pubkey.x, curve->order, r); if (err != MP_OKAY) break; if (mp_iszero(r) == MP_YES) { #ifndef ALT_ECC_SIZE mp_clear(pubkey.pubkey.x); mp_clear(pubkey.pubkey.y); mp_clear(pubkey.pubkey.z); #endif mp_forcezero(&pubkey.k); } else { /* find s = (e + xr)/k */ err = mp_invmod(&pubkey.k, curve->order, &pubkey.k); if (err != MP_OKAY) break; /* s = xr */ err = mp_mulmod(&key->k, r, curve->order, s); if (err != MP_OKAY) break; /* s = e + xr */ err = mp_add(e, s, s); if (err != MP_OKAY) break; /* s = e + xr */ err = mp_mod(s, curve->order, s); if (err != MP_OKAY) break; /* s = (e + xr)/k */ err = mp_mulmod(s, &pubkey.k, curve->order, s); if (mp_iszero(s) == MP_NO) break; } } wc_ecc_free(&pubkey); } } mp_clear(e); wc_ecc_curve_free(curve); #endif /* WOLFSSL_SP_MATH */ return err; } #endif /* WOLFSSL_ATECC508A */ #endif /* HAVE_ECC_SIGN */ #ifdef WOLFSSL_CUSTOM_CURVES void wc_ecc_free_curve(const ecc_set_type* curve, void* heap) { if (curve->prime != NULL) XFREE((void*)curve->prime, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Af != NULL) XFREE((void*)curve->Af, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Bf != NULL) XFREE((void*)curve->Bf, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->order != NULL) XFREE((void*)curve->order, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Gx != NULL) XFREE((void*)curve->Gx, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Gy != NULL) XFREE((void*)curve->Gy, heap, DYNAMIC_TYPE_ECC_BUFFER); XFREE((void*)curve, heap, DYNAMIC_TYPE_ECC_BUFFER); (void)heap; } #endif /* WOLFSSL_CUSTOM_CURVES */ /** Free an ECC key from memory key The key you wish to free */ int wc_ecc_free(ecc_key* key) { if (key == NULL) { return 0; } #ifdef WOLFSSL_ASYNC_CRYPT #ifdef WC_ASYNC_ENABLE_ECC wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC); #endif wc_ecc_free_async(key); #endif #ifdef WOLFSSL_ATECC508A atmel_ecc_free(key->slot); key->slot = -1; #else mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); mp_forcezero(&key->k); #endif /* WOLFSSL_ATECC508A */ #ifdef WOLFSSL_CUSTOM_CURVES if (key->deallocSet && key->dp != NULL) wc_ecc_free_curve(key->dp, key->heap); #endif return 0; } #ifndef WOLFSSL_SP_MATH #ifdef ECC_SHAMIR /** Computes kA*A + kB*B = C using Shamir's Trick A First point to multiply kA What to multiple A by B Second point to multiply kB What to multiple B by C [out] Destination point (can overlap with A or B) a ECC curve parameter a modulus Modulus for curve return MP_OKAY on success */ #ifdef FP_ECC static int normal_ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point* B, mp_int* kB, ecc_point* C, mp_int* a, mp_int* modulus, void* heap) #else int ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point* B, mp_int* kB, ecc_point* C, mp_int* a, mp_int* modulus, void* heap) #endif { ecc_point* precomp[16]; unsigned bitbufA, bitbufB, lenA, lenB, len, nA, nB, nibble; unsigned char* tA; unsigned char* tB; int err = MP_OKAY, first, x, y; mp_digit mp = 0; /* argchks */ if (A == NULL || kA == NULL || B == NULL || kB == NULL || C == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } /* allocate memory */ tA = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER); if (tA == NULL) { return GEN_MEM_ERR; } tB = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER); if (tB == NULL) { XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER); return GEN_MEM_ERR; } /* init variables */ XMEMSET(tA, 0, ECC_BUFSIZE); XMEMSET(tB, 0, ECC_BUFSIZE); XMEMSET(precomp, 0, sizeof(precomp)); /* get sizes */ lenA = mp_unsigned_bin_size(kA); lenB = mp_unsigned_bin_size(kB); len = MAX(lenA, lenB); /* sanity check */ if ((lenA > ECC_BUFSIZE) || (lenB > ECC_BUFSIZE)) { err = BAD_FUNC_ARG; } if (err == MP_OKAY) { /* extract and justify kA */ err = mp_to_unsigned_bin(kA, (len - lenA) + tA); /* extract and justify kB */ if (err == MP_OKAY) err = mp_to_unsigned_bin(kB, (len - lenB) + tB); /* allocate the table */ if (err == MP_OKAY) { for (x = 0; x < 16; x++) { precomp[x] = wc_ecc_new_point_h(heap); if (precomp[x] == NULL) { err = GEN_MEM_ERR; break; } } } } if (err == MP_OKAY) /* init montgomery reduction */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { mp_int mu; err = mp_init(&mu); if (err == MP_OKAY) { err = mp_montgomery_calc_normalization(&mu, modulus); if (err == MP_OKAY) /* copy ones ... */ err = mp_mulmod(A->x, &mu, modulus, precomp[1]->x); if (err == MP_OKAY) err = mp_mulmod(A->y, &mu, modulus, precomp[1]->y); if (err == MP_OKAY) err = mp_mulmod(A->z, &mu, modulus, precomp[1]->z); if (err == MP_OKAY) err = mp_mulmod(B->x, &mu, modulus, precomp[1<<2]->x); if (err == MP_OKAY) err = mp_mulmod(B->y, &mu, modulus, precomp[1<<2]->y); if (err == MP_OKAY) err = mp_mulmod(B->z, &mu, modulus, precomp[1<<2]->z); /* done with mu */ mp_clear(&mu); } } if (err == MP_OKAY) /* precomp [i,0](A + B) table */ err = ecc_projective_dbl_point(precomp[1], precomp[2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_add_point(precomp[1], precomp[2], precomp[3], a, modulus, mp); if (err == MP_OKAY) /* precomp [0,i](A + B) table */ err = ecc_projective_dbl_point(precomp[1<<2], precomp[2<<2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_add_point(precomp[1<<2], precomp[2<<2], precomp[3<<2], a, modulus, mp); if (err == MP_OKAY) { /* precomp [i,j](A + B) table (i != 0, j != 0) */ for (x = 1; x < 4; x++) { for (y = 1; y < 4; y++) { if (err == MP_OKAY) err = ecc_projective_add_point(precomp[x], precomp[(y<<2)], precomp[x+(y<<2)], a, modulus, mp); } } } if (err == MP_OKAY) { nibble = 3; first = 1; bitbufA = tA[0]; bitbufB = tB[0]; /* for every byte of the multiplicands */ for (x = 0;; ) { /* grab a nibble */ if (++nibble == 4) { if (x == (int)len) break; bitbufA = tA[x]; bitbufB = tB[x]; nibble = 0; x++; } /* extract two bits from both, shift/update */ nA = (bitbufA >> 6) & 0x03; nB = (bitbufB >> 6) & 0x03; bitbufA = (bitbufA << 2) & 0xFF; bitbufB = (bitbufB << 2) & 0xFF; /* if both zero, if first, continue */ if ((nA == 0) && (nB == 0) && (first == 1)) { continue; } /* double twice, only if this isn't the first */ if (first == 0) { /* double twice */ if (err == MP_OKAY) err = ecc_projective_dbl_point(C, C, a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(C, C, a, modulus, mp); else break; } /* if not both zero */ if ((nA != 0) || (nB != 0)) { if (first == 1) { /* if first, copy from table */ first = 0; if (err == MP_OKAY) err = mp_copy(precomp[nA + (nB<<2)]->x, C->x); if (err == MP_OKAY) err = mp_copy(precomp[nA + (nB<<2)]->y, C->y); if (err == MP_OKAY) err = mp_copy(precomp[nA + (nB<<2)]->z, C->z); else break; } else { /* if not first, add from table */ if (err == MP_OKAY) err = ecc_projective_add_point(C, precomp[nA + (nB<<2)], C, a, modulus, mp); else break; } } } } /* reduce to affine */ if (err == MP_OKAY) err = ecc_map(C, modulus, mp); /* clean up */ for (x = 0; x < 16; x++) { wc_ecc_del_point_h(precomp[x], heap); } ForceZero(tA, ECC_BUFSIZE); ForceZero(tB, ECC_BUFSIZE); XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER); XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER); return err; } #endif /* ECC_SHAMIR */ #endif #ifdef HAVE_ECC_VERIFY #ifndef NO_ASN /* verify * * w = s^-1 mod n * u1 = xw * u2 = rw * X = u1*G + u2*Q * v = X_x1 mod n * accept if v == r */ /** Verify an ECC signature sig The signature to verify siglen The length of the signature (octets) hash The hash (message digest) that was signed hashlen The length of the hash (octets) res Result of signature, 1==valid, 0==invalid key The corresponding public ECC key return MP_OKAY if successful (even if the signature is not valid) */ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, word32 hashlen, int* res, ecc_key* key) { int err; mp_int *r = NULL, *s = NULL; #ifndef WOLFSSL_ASYNC_CRYPT mp_int r_lcl, s_lcl; #endif if (sig == NULL || hash == NULL || res == NULL || key == NULL) { return ECC_BAD_ARG_E; } #ifdef WOLF_CRYPTO_DEV if (key->devId != INVALID_DEVID) { err = wc_CryptoDev_EccVerify(sig, siglen, hash, hashlen, res, key); if (err != NOT_COMPILED_IN) return err; } #endif #ifdef WOLFSSL_ASYNC_CRYPT err = wc_ecc_alloc_async(key); if (err != 0) return err; r = key->r; s = key->s; #else r = &r_lcl; s = &s_lcl; #endif switch(key->state) { case ECC_STATE_NONE: case ECC_STATE_VERIFY_DECODE: key->state = ECC_STATE_VERIFY_DECODE; /* default to invalid signature */ *res = 0; /* Note, DecodeECC_DSA_Sig() calls mp_init() on r and s. * If either of those don't allocate correctly, none of * the rest of this function will execute, and everything * gets cleaned up at the end. */ /* decode DSA header */ err = DecodeECC_DSA_Sig(sig, siglen, r, s); if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_VERIFY_DO: key->state = ECC_STATE_VERIFY_DO; err = wc_ecc_verify_hash_ex(r, s, hash, hashlen, res, key); #ifndef WOLFSSL_ASYNC_CRYPT /* done with R/S */ mp_clear(r); mp_clear(s); #endif if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_VERIFY_RES: key->state = ECC_STATE_VERIFY_RES; err = 0; break; default: err = BAD_STATE_E; } /* if async pending then return and skip done cleanup below */ if (err == WC_PENDING_E) { key->state++; return err; } /* cleanup */ #ifdef WOLFSSL_ASYNC_CRYPT wc_ecc_free_async(key); #endif key->state = ECC_STATE_NONE; return err; } #endif /* !NO_ASN */ /** Verify an ECC signature r The signature R component to verify s The signature S component to verify hash The hash (message digest) that was signed hashlen The length of the hash (octets) res Result of signature, 1==valid, 0==invalid key The corresponding public ECC key return MP_OKAY if successful (even if the signature is not valid) */ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, word32 hashlen, int* res, ecc_key* key) { int err; #ifdef WOLFSSL_ATECC508A byte sigRS[ATECC_KEY_SIZE*2]; #elif !defined(WOLFSSL_SP_MATH) int did_init = 0; ecc_point *mG = NULL, *mQ = NULL; mp_int v; mp_int w; mp_int u1; mp_int u2; mp_int* e; #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) mp_int e_lcl; #endif DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT) #endif if (r == NULL || s == NULL || hash == NULL || res == NULL || key == NULL) return ECC_BAD_ARG_E; /* default to invalid signature */ *res = 0; /* is the IDX valid ? */ if (wc_ecc_is_valid_idx(key->idx) != 1) { return ECC_BAD_ARG_E; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_VERIFY)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->eccVerify.r = r; testDev->eccVerify.s = s; testDev->eccVerify.hash = hash; testDev->eccVerify.hashlen = hashlen; testDev->eccVerify.stat = res; testDev->eccVerify.key = key; return WC_PENDING_E; } } #endif #ifdef WOLFSSL_ATECC508A /* Extract R and S */ err = mp_to_unsigned_bin(r, &sigRS[0]); if (err != MP_OKAY) { return err; } err = mp_to_unsigned_bin(s, &sigRS[ATECC_KEY_SIZE]); if (err != MP_OKAY) { return err; } err = atcatls_verify(hash, sigRS, key->pubkey_raw, (bool*)res); if (err != ATCA_SUCCESS) { return BAD_COND_E; } #else /* checking if private key with no public part */ if (key->type == ECC_PRIVATEKEY_ONLY) { WOLFSSL_MSG("Verify called with private key, generating public part"); err = wc_ecc_make_pub_ex(key, NULL, NULL); if (err != MP_OKAY) { WOLFSSL_MSG("Unable to extract public key"); return err; } } #ifdef WOLFSSL_SP_MATH if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { return sp_ecc_verify_256(hash, hashlen, key->pubkey.x, key->pubkey.y, key->pubkey.z, r, s, res, key->heap); } else return WC_KEY_SIZE_E; #else #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC) #endif { if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) return sp_ecc_verify_256(hash, hashlen, key->pubkey.x, key->pubkey.y, key->pubkey.z,r, s, res, key->heap); } #endif #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) err = wc_ecc_alloc_mpint(key, &key->e); if (err != 0) return err; e = key->e; #else e = &e_lcl; #endif err = mp_init(e); if (err != MP_OKAY) return MEMORY_E; /* read in the specs for this curve */ err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); /* check for zero */ if (err == MP_OKAY) { if (mp_iszero(r) == MP_YES || mp_iszero(s) == MP_YES || mp_cmp(r, curve->order) != MP_LT || mp_cmp(s, curve->order) != MP_LT) { err = MP_ZERO_E; } } /* read hash */ if (err == MP_OKAY) { /* we may need to truncate if hash is longer than key size */ unsigned int orderBits = mp_count_bits(curve->order); /* truncate down to byte size, may be all that's needed */ if ( (WOLFSSL_BIT_SIZE * hashlen) > orderBits) hashlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE; err = mp_read_unsigned_bin(e, hash, hashlen); /* may still need bit truncation too */ if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * hashlen) > orderBits) mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); } /* check for async hardware acceleration */ #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) #ifdef HAVE_CAVIUM_V if (NitroxEccIsCurveSupported(key)) #endif { word32 keySz = key->dp->size; err = wc_mp_to_bigint_sz(e, &e->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(key->pubkey.x, &key->pubkey.x->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(key->pubkey.y, &key->pubkey.y->raw, keySz); if (err == MP_OKAY) #ifdef HAVE_CAVIUM_V err = NitroxEcdsaVerify(key, &e->raw, &key->pubkey.x->raw, &key->pubkey.y->raw, &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw, res); #else err = IntelQaEcdsaVerify(&key->asyncDev, &e->raw, &key->pubkey.x->raw, &key->pubkey.y->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, &curve->Gy->raw, res); #endif #ifndef HAVE_CAVIUM_V mp_clear(e); #endif wc_ecc_curve_free(curve); return err; } #endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */ } #endif /* WOLFSSL_ASYNC_CRYPT */ /* allocate ints */ if (err == MP_OKAY) { if ((err = mp_init_multi(&v, &w, &u1, &u2, NULL, NULL)) != MP_OKAY) { err = MEMORY_E; } did_init = 1; } /* allocate points */ if (err == MP_OKAY) { mG = wc_ecc_new_point_h(key->heap); mQ = wc_ecc_new_point_h(key->heap); if (mQ == NULL || mG == NULL) err = MEMORY_E; } /* w = s^-1 mod n */ if (err == MP_OKAY) err = mp_invmod(s, curve->order, &w); /* u1 = ew */ if (err == MP_OKAY) err = mp_mulmod(e, &w, curve->order, &u1); /* u2 = rw */ if (err == MP_OKAY) err = mp_mulmod(r, &w, curve->order, &u2); /* find mG and mQ */ if (err == MP_OKAY) err = mp_copy(curve->Gx, mG->x); if (err == MP_OKAY) err = mp_copy(curve->Gy, mG->y); if (err == MP_OKAY) err = mp_set(mG->z, 1); if (err == MP_OKAY) err = mp_copy(key->pubkey.x, mQ->x); if (err == MP_OKAY) err = mp_copy(key->pubkey.y, mQ->y); if (err == MP_OKAY) err = mp_copy(key->pubkey.z, mQ->z); #ifdef FREESCALE_LTC_ECC /* use PKHA to compute u1*mG + u2*mQ */ if (err == MP_OKAY) err = wc_ecc_mulmod_ex(&u1, mG, mG, curve->Af, curve->prime, 0, key->heap); if (err == MP_OKAY) err = wc_ecc_mulmod_ex(&u2, mQ, mQ, curve->Af, curve->prime, 0, key->heap); if (err == MP_OKAY) err = wc_ecc_point_add(mG, mQ, mG, curve->prime); #else #ifndef ECC_SHAMIR { mp_digit mp = 0; /* compute u1*mG + u2*mQ = mG */ if (err == MP_OKAY) { err = wc_ecc_mulmod_ex(&u1, mG, mG, curve->Af, curve->prime, 0, key->heap); } if (err == MP_OKAY) { err = wc_ecc_mulmod_ex(&u2, mQ, mQ, curve->Af, curve->prime, 0, key->heap); } /* find the montgomery mp */ if (err == MP_OKAY) err = mp_montgomery_setup(curve->prime, &mp); /* add them */ if (err == MP_OKAY) err = ecc_projective_add_point(mQ, mG, mG, curve->Af, curve->prime, mp); /* reduce */ if (err == MP_OKAY) err = ecc_map(mG, curve->prime, mp); } #else /* use Shamir's trick to compute u1*mG + u2*mQ using half the doubles */ if (err == MP_OKAY) { err = ecc_mul2add(mG, &u1, mQ, &u2, mG, curve->Af, curve->prime, key->heap); } #endif /* ECC_SHAMIR */ #endif /* FREESCALE_LTC_ECC */ /* v = X_x1 mod n */ if (err == MP_OKAY) err = mp_mod(mG->x, curve->order, &v); /* does v == r */ if (err == MP_OKAY) { if (mp_cmp(&v, r) == MP_EQ) *res = 1; } /* cleanup */ wc_ecc_del_point_h(mG, key->heap); wc_ecc_del_point_h(mQ, key->heap); mp_clear(e); if (did_init) { mp_clear(&v); mp_clear(&w); mp_clear(&u1); mp_clear(&u2); } wc_ecc_curve_free(curve); #endif /* WOLFSSL_SP_MATH */ #endif /* WOLFSSL_ATECC508A */ return err; } #endif /* HAVE_ECC_VERIFY */ #ifdef HAVE_ECC_KEY_IMPORT #ifndef WOLFSSL_ATECC508A /* import point from der */ int wc_ecc_import_point_der(byte* in, word32 inLen, const int curve_idx, ecc_point* point) { int err = 0; int compressed = 0; int keysize; byte pointType; if (in == NULL || point == NULL || (curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0)) return ECC_BAD_ARG_E; /* must be odd */ if ((inLen & 1) == 0) { return ECC_BAD_ARG_E; } /* init point */ #ifdef ALT_ECC_SIZE point->x = (mp_int*)&point->xyz[0]; point->y = (mp_int*)&point->xyz[1]; point->z = (mp_int*)&point->xyz[2]; alt_fp_init(point->x); alt_fp_init(point->y); alt_fp_init(point->z); #else err = mp_init_multi(point->x, point->y, point->z, NULL, NULL, NULL); #endif if (err != MP_OKAY) return MEMORY_E; /* check for point type (4, 2, or 3) */ pointType = in[0]; if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN && pointType != ECC_POINT_COMP_ODD) { err = ASN_PARSE_E; } if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) { #ifdef HAVE_COMP_KEY compressed = 1; #else err = NOT_COMPILED_IN; #endif } /* adjust to skip first byte */ inLen -= 1; in += 1; /* calculate key size based on inLen / 2 */ keysize = inLen>>1; #ifdef WOLFSSL_ATECC508A /* populate key->pubkey_raw */ XMEMCPY(key->pubkey_raw, (byte*)in, sizeof(key->pubkey_raw)); #endif /* read data */ if (err == MP_OKAY) err = mp_read_unsigned_bin(point->x, (byte*)in, keysize); #ifdef HAVE_COMP_KEY if (err == MP_OKAY && compressed == 1) { /* build y */ #ifndef WOLFSSL_SP_MATH int did_init = 0; mp_int t1, t2; DECLARE_CURVE_SPECS(3) if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY) err = MEMORY_E; else did_init = 1; /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(&ecc_sets[curve_idx], &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_BF)); /* compute x^3 */ if (err == MP_OKAY) err = mp_sqr(point->x, &t1); if (err == MP_OKAY) err = mp_mulmod(&t1, point->x, curve->prime, &t1); /* compute x^3 + a*x */ if (err == MP_OKAY) err = mp_mulmod(curve->Af, point->x, curve->prime, &t2); if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); /* compute x^3 + a*x + b */ if (err == MP_OKAY) err = mp_add(&t1, curve->Bf, &t1); /* compute sqrt(x^3 + a*x + b) */ if (err == MP_OKAY) err = mp_sqrtmod_prime(&t1, curve->prime, &t2); /* adjust y */ if (err == MP_OKAY) { if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) || (mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) { err = mp_mod(&t2, curve->prime, point->y); } else { err = mp_submod(curve->prime, &t2, curve->prime, point->y); } } if (did_init) { mp_clear(&t2); mp_clear(&t1); } wc_ecc_curve_free(curve); #else sp_ecc_uncompress_256(point->x, pointType, point->y); #endif } #endif if (err == MP_OKAY && compressed == 0) err = mp_read_unsigned_bin(point->y, (byte*)in + keysize, keysize); if (err == MP_OKAY) err = mp_set(point->z, 1); if (err != MP_OKAY) { mp_clear(point->x); mp_clear(point->y); mp_clear(point->z); } return err; } #endif /* !WOLFSSL_ATECC508A */ #endif /* HAVE_ECC_KEY_IMPORT */ #ifdef HAVE_ECC_KEY_EXPORT /* export point to der */ int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out, word32* outLen) { int ret = MP_OKAY; word32 numlen; #ifndef WOLFSSL_ATECC508A #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_BUFSIZE]; #endif #endif /* !WOLFSSL_ATECC508A */ if ((curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0)) return ECC_BAD_ARG_E; /* return length needed only */ if (point != NULL && out == NULL && outLen != NULL) { numlen = ecc_sets[curve_idx].size; *outLen = 1 + 2*numlen; return LENGTH_ONLY_E; } if (point == NULL || out == NULL || outLen == NULL) return ECC_BAD_ARG_E; numlen = ecc_sets[curve_idx].size; if (*outLen < (1 + 2*numlen)) { *outLen = 1 + 2*numlen; return BUFFER_E; } #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ ret = BAD_COND_E; #else /* store byte point type */ out[0] = ECC_POINT_UNCOMP; #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /* pad and store x */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->x, buf + (numlen - mp_unsigned_bin_size(point->x))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1, buf, numlen); /* pad and store y */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->y, buf + (numlen - mp_unsigned_bin_size(point->y))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1+numlen, buf, numlen); *outLen = 1 + 2*numlen; done: #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif #endif /* WOLFSSL_ATECC508A */ return ret; } /* export public ECC key in ANSI X9.63 format */ int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen) { int ret = MP_OKAY; word32 numlen; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_BUFSIZE]; #endif word32 pubxlen, pubylen; /* return length needed only */ if (key != NULL && out == NULL && outLen != NULL) { numlen = key->dp->size; *outLen = 1 + 2*numlen; return LENGTH_ONLY_E; } if (key == NULL || out == NULL || outLen == NULL) return ECC_BAD_ARG_E; if (key->type == ECC_PRIVATEKEY_ONLY) return ECC_PRIVATEONLY_E; if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numlen = key->dp->size; /* verify room in out buffer */ if (*outLen < (1 + 2*numlen)) { *outLen = 1 + 2*numlen; return BUFFER_E; } /* verify public key length is less than key size */ pubxlen = mp_unsigned_bin_size(key->pubkey.x); pubylen = mp_unsigned_bin_size(key->pubkey.y); if ((pubxlen > numlen) || (pubylen > numlen)) { WOLFSSL_MSG("Public key x/y invalid!"); return BUFFER_E; } /* store byte point type */ out[0] = ECC_POINT_UNCOMP; #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /* pad and store x */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(key->pubkey.x, buf + (numlen - pubxlen)); if (ret != MP_OKAY) goto done; XMEMCPY(out+1, buf, numlen); /* pad and store y */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(key->pubkey.y, buf + (numlen - pubylen)); if (ret != MP_OKAY) goto done; XMEMCPY(out+1+numlen, buf, numlen); *outLen = 1 + 2*numlen; done: #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return ret; } /* export public ECC key in ANSI X9.63 format, extended with * compression option */ int wc_ecc_export_x963_ex(ecc_key* key, byte* out, word32* outLen, int compressed) { if (compressed == 0) return wc_ecc_export_x963(key, out, outLen); #ifdef HAVE_COMP_KEY else return wc_ecc_export_x963_compressed(key, out, outLen); #else return NOT_COMPILED_IN; #endif } #endif /* HAVE_ECC_KEY_EXPORT */ #ifndef WOLFSSL_ATECC508A /* is ecc point on curve described by dp ? */ int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime) { #ifndef WOLFSSL_SP_MATH int err; mp_int t1, t2; if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return err; } /* compute y^2 */ if (err == MP_OKAY) err = mp_sqr(ecp->y, &t1); /* compute x^3 */ if (err == MP_OKAY) err = mp_sqr(ecp->x, &t2); if (err == MP_OKAY) err = mp_mod(&t2, prime, &t2); if (err == MP_OKAY) err = mp_mul(ecp->x, &t2, &t2); /* compute y^2 - x^3 */ if (err == MP_OKAY) err = mp_sub(&t1, &t2, &t1); /* Determine if curve "a" should be used in calc */ #ifdef WOLFSSL_CUSTOM_CURVES if (err == MP_OKAY) { /* Use a and prime to determine if a == 3 */ err = mp_set(&t2, 0); if (err == MP_OKAY) err = mp_submod(prime, a, prime, &t2); } if (err == MP_OKAY && mp_cmp_d(&t2, 3) != MP_EQ) { /* compute y^2 - x^3 + a*x */ if (err == MP_OKAY) err = mp_mulmod(&t2, ecp->x, prime, &t2); if (err == MP_OKAY) err = mp_addmod(&t1, &t2, prime, &t1); } else #endif /* WOLFSSL_CUSTOM_CURVES */ { /* assumes "a" == 3 */ (void)a; /* compute y^2 - x^3 + 3x */ if (err == MP_OKAY) err = mp_add(&t1, ecp->x, &t1); if (err == MP_OKAY) err = mp_add(&t1, ecp->x, &t1); if (err == MP_OKAY) err = mp_add(&t1, ecp->x, &t1); if (err == MP_OKAY) err = mp_mod(&t1, prime, &t1); } /* adjust range (0, prime) */ while (err == MP_OKAY && mp_isneg(&t1)) { err = mp_add(&t1, prime, &t1); } while (err == MP_OKAY && mp_cmp(&t1, prime) != MP_LT) { err = mp_sub(&t1, prime, &t1); } /* compare to b */ if (err == MP_OKAY) { if (mp_cmp(&t1, b) != MP_EQ) { err = MP_VAL; } else { err = MP_OKAY; } } mp_clear(&t1); mp_clear(&t2); return err; #else (void)a; (void)b; (void)prime; return sp_ecc_is_point_256(ecp->x, ecp->y); #endif } #ifndef WOLFSSL_SP_MATH /* validate privkey * generator == pubkey, 0 on success */ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) { int err = MP_OKAY; ecc_point* base = NULL; ecc_point* res = NULL; DECLARE_CURVE_SPECS(2) if (key == NULL) return BAD_FUNC_ARG; res = wc_ecc_new_point_h(key->heap); if (res == NULL) err = MEMORY_E; #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { if (err == MP_OKAY) err = sp_ecc_mulmod_base_256(&key->k, res, 1, key->heap); } else #endif #endif { base = wc_ecc_new_point_h(key->heap); if (base == NULL) err = MEMORY_E; if (err == MP_OKAY) { /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_GX | ECC_CURVE_FIELD_GY)); } /* set up base generator */ if (err == MP_OKAY) err = mp_copy(curve->Gx, base->x); if (err == MP_OKAY) err = mp_copy(curve->Gy, base->y); if (err == MP_OKAY) err = mp_set(base->z, 1); if (err == MP_OKAY) err = wc_ecc_mulmod_ex(&key->k, base, res, a, prime, 1, key->heap); } if (err == MP_OKAY) { /* compare result to public key */ if (mp_cmp(res->x, key->pubkey.x) != MP_EQ || mp_cmp(res->y, key->pubkey.y) != MP_EQ || mp_cmp(res->z, key->pubkey.z) != MP_EQ) { /* didn't match */ err = ECC_PRIV_KEY_E; } } wc_ecc_curve_free(curve); wc_ecc_del_point_h(res, key->heap); wc_ecc_del_point_h(base, key->heap); return err; } #endif #ifdef WOLFSSL_VALIDATE_ECC_IMPORT /* check privkey generator helper, creates prime needed */ static int ecc_check_privkey_gen_helper(ecc_key* key) { int err; #ifndef WOLFSSL_ATECC508A DECLARE_CURVE_SPECS(2) #endif if (key == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ err = BAD_COND_E; #else /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF)); if (err == MP_OKAY) err = ecc_check_privkey_gen(key, curve->Af, curve->prime); wc_ecc_curve_free(curve); #endif /* WOLFSSL_ATECC508A */ return err; } #endif /* WOLFSSL_VALIDATE_ECC_IMPORT */ #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH) /* validate order * pubkey = point at infinity, 0 on success */ static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a, mp_int* prime, mp_int* order) { ecc_point* inf = NULL; int err; if (key == NULL) return BAD_FUNC_ARG; inf = wc_ecc_new_point_h(key->heap); if (inf == NULL) err = MEMORY_E; else { #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { err = sp_ecc_mulmod_256(order, pubkey, inf, 1, key->heap); } else #endif #endif #ifndef WOLFSSL_SP_MATH err = wc_ecc_mulmod_ex(order, pubkey, inf, a, prime, 1, key->heap); if (err == MP_OKAY && !wc_ecc_point_is_at_infinity(inf)) err = ECC_INF_E; #else (void)a; (void)prime; err = WC_KEY_SIZE_E; #endif } wc_ecc_del_point_h(inf, key->heap); return err; } #endif #endif /* !WOLFSSL_ATECC508A */ /* perform sanity checks on ecc key validity, 0 on success */ int wc_ecc_check_key(ecc_key* key) { int err; #ifndef WOLFSSL_SP_MATH #ifndef WOLFSSL_ATECC508A mp_int* b; #ifdef USE_ECC_B_PARAM DECLARE_CURVE_SPECS(4) #else mp_int b_lcl; DECLARE_CURVE_SPECS(3) b = &b_lcl; XMEMSET(b, 0, sizeof(mp_int)); #endif #endif /* WOLFSSL_ATECC508A */ if (key == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_ATECC508A if (key->slot == ATECC_INVALID_SLOT) return ECC_BAD_ARG_E; err = 0; /* consider key check success on ECC508A */ #else /* pubkey point cannot be at infinity */ if (wc_ecc_point_is_at_infinity(&key->pubkey)) return ECC_INF_E; /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_ORDER #ifdef USE_ECC_B_PARAM | ECC_CURVE_FIELD_BF #endif )); #ifndef USE_ECC_B_PARAM /* load curve b parameter */ if (err == MP_OKAY) err = mp_init(b); if (err == MP_OKAY) err = mp_read_radix(b, key->dp->Bf, MP_RADIX_HEX); #else b = curve->Bf; #endif /* Qx must be in the range [0, p-1] */ if (mp_cmp(key->pubkey.x, curve->prime) != MP_LT) err = ECC_OUT_OF_RANGE_E; /* Qy must be in the range [0, p-1] */ if (mp_cmp(key->pubkey.y, curve->prime) != MP_LT) err = ECC_OUT_OF_RANGE_E; /* make sure point is actually on curve */ if (err == MP_OKAY) err = wc_ecc_is_point(&key->pubkey, curve->Af, b, curve->prime); /* pubkey * order must be at infinity */ if (err == MP_OKAY) err = ecc_check_pubkey_order(key, &key->pubkey, curve->Af, curve->prime, curve->order); /* private * base generator must equal pubkey */ if (err == MP_OKAY && key->type == ECC_PRIVATEKEY) err = ecc_check_privkey_gen(key, curve->Af, curve->prime); wc_ecc_curve_free(curve); #ifndef USE_ECC_B_PARAM mp_clear(b); #endif #endif /* WOLFSSL_ATECC508A */ #else if (key == NULL) return BAD_FUNC_ARG; /* pubkey point cannot be at infinity */ if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { err = sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y, &key->k, key->heap); } else err = WC_KEY_SIZE_E; #endif return err; } #ifdef HAVE_ECC_KEY_IMPORT /* import public ECC key in ANSI X9.63 format */ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, int curve_id) { int err = MP_OKAY; int compressed = 0; int keysize = 0; byte pointType; if (in == NULL || key == NULL) return BAD_FUNC_ARG; /* must be odd */ if ((inLen & 1) == 0) { return ECC_BAD_ARG_E; } /* make sure required variables are reset */ wc_ecc_reset(key); /* init key */ #ifdef ALT_ECC_SIZE key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); err = mp_init(&key->k); #else err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif if (err != MP_OKAY) return MEMORY_E; /* check for point type (4, 2, or 3) */ pointType = in[0]; if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN && pointType != ECC_POINT_COMP_ODD) { err = ASN_PARSE_E; } if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) { #ifdef HAVE_COMP_KEY compressed = 1; #else err = NOT_COMPILED_IN; #endif } /* adjust to skip first byte */ inLen -= 1; in += 1; if (err == MP_OKAY) { #ifdef HAVE_COMP_KEY /* adjust inLen if compressed */ if (compressed) inLen = inLen*2 + 1; /* used uncompressed len */ #endif /* determine key size */ keysize = (inLen>>1); err = wc_ecc_set_curve(key, keysize, curve_id); key->type = ECC_PUBLICKEY; } /* read data */ if (err == MP_OKAY) err = mp_read_unsigned_bin(key->pubkey.x, (byte*)in, keysize); #ifdef HAVE_COMP_KEY if (err == MP_OKAY && compressed == 1) { /* build y */ #ifndef WOLFSSL_SP_MATH mp_int t1, t2; int did_init = 0; DECLARE_CURVE_SPECS(3) if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY) err = MEMORY_E; else did_init = 1; /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_BF)); /* compute x^3 */ if (err == MP_OKAY) err = mp_sqr(key->pubkey.x, &t1); if (err == MP_OKAY) err = mp_mulmod(&t1, key->pubkey.x, curve->prime, &t1); /* compute x^3 + a*x */ if (err == MP_OKAY) err = mp_mulmod(curve->Af, key->pubkey.x, curve->prime, &t2); if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); /* compute x^3 + a*x + b */ if (err == MP_OKAY) err = mp_add(&t1, curve->Bf, &t1); /* compute sqrt(x^3 + a*x + b) */ if (err == MP_OKAY) err = mp_sqrtmod_prime(&t1, curve->prime, &t2); /* adjust y */ if (err == MP_OKAY) { if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) || (mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) { err = mp_mod(&t2, curve->prime, &t2); } else { err = mp_submod(curve->prime, &t2, curve->prime, &t2); } if (err == MP_OKAY) err = mp_copy(&t2, key->pubkey.y); } if (did_init) { mp_clear(&t2); mp_clear(&t1); } wc_ecc_curve_free(curve); #else sp_ecc_uncompress_256(key->pubkey.x, pointType, key->pubkey.y); #endif } #endif /* HAVE_COMP_KEY */ if (err == MP_OKAY && compressed == 0) err = mp_read_unsigned_bin(key->pubkey.y, (byte*)in + keysize, keysize); if (err == MP_OKAY) err = mp_set(key->pubkey.z, 1); #ifdef WOLFSSL_VALIDATE_ECC_IMPORT if (err == MP_OKAY) err = wc_ecc_check_key(key); #endif if (err != MP_OKAY) { mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); mp_clear(&key->k); } return err; } int wc_ecc_import_x963(const byte* in, word32 inLen, ecc_key* key) { return wc_ecc_import_x963_ex(in, inLen, key, ECC_CURVE_DEF); } #endif /* HAVE_ECC_KEY_IMPORT */ #ifdef HAVE_ECC_KEY_EXPORT /* export ecc private key only raw, outLen is in/out size return MP_OKAY on success */ int wc_ecc_export_private_only(ecc_key* key, byte* out, word32* outLen) { word32 numlen; if (key == NULL || out == NULL || outLen == NULL) { return BAD_FUNC_ARG; } if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numlen = key->dp->size; if (*outLen < numlen) { *outLen = numlen; return BUFFER_E; } *outLen = numlen; XMEMSET(out, 0, *outLen); #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ return BAD_COND_E; #else return mp_to_unsigned_bin(&key->k, out + (numlen - mp_unsigned_bin_size(&key->k))); #endif /* WOLFSSL_ATECC508A */ } /* export ecc key to component form, d is optional if only exporting public * return MP_OKAY on success */ static int wc_ecc_export_raw(ecc_key* key, byte* qx, word32* qxLen, byte* qy, word32* qyLen, byte* d, word32* dLen) { int err; byte exportPriv = 0; word32 numLen; if (key == NULL || qx == NULL || qxLen == NULL || qy == NULL || qyLen == NULL) { return BAD_FUNC_ARG; } if (key->type == ECC_PRIVATEKEY_ONLY) { return ECC_PRIVATEONLY_E; } if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numLen = key->dp->size; if (d != NULL) { if (dLen == NULL || key->type != ECC_PRIVATEKEY) return BAD_FUNC_ARG; exportPriv = 1; } /* check public buffer sizes */ if ((*qxLen < numLen) || (*qyLen < numLen)) { *qxLen = numLen; *qyLen = numLen; return BUFFER_E; } *qxLen = numLen; *qyLen = numLen; XMEMSET(qx, 0, *qxLen); XMEMSET(qy, 0, *qyLen); /* private d component */ if (exportPriv == 1) { /* check private buffer size */ if (*dLen < numLen) { *dLen = numLen; return BUFFER_E; } *dLen = numLen; XMEMSET(d, 0, *dLen); #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ return BAD_COND_E; #else /* private key, d */ err = mp_to_unsigned_bin(&key->k, d + (numLen - mp_unsigned_bin_size(&key->k))); if (err != MP_OKAY) return err; #endif /* WOLFSSL_ATECC508A */ } /* public x component */ err = mp_to_unsigned_bin(key->pubkey.x, qx + (numLen - mp_unsigned_bin_size(key->pubkey.x))); if (err != MP_OKAY) return err; /* public y component */ err = mp_to_unsigned_bin(key->pubkey.y, qy + (numLen - mp_unsigned_bin_size(key->pubkey.y))); if (err != MP_OKAY) return err; return 0; } /* export public key to raw elements including public (Qx,Qy) * return MP_OKAY on success, negative on error */ int wc_ecc_export_public_raw(ecc_key* key, byte* qx, word32* qxLen, byte* qy, word32* qyLen) { return wc_ecc_export_raw(key, qx, qxLen, qy, qyLen, NULL, NULL); } /* export ecc key to raw elements including public (Qx,Qy) and private (d) * return MP_OKAY on success, negative on error */ int wc_ecc_export_private_raw(ecc_key* key, byte* qx, word32* qxLen, byte* qy, word32* qyLen, byte* d, word32* dLen) { /* sanitize d and dLen, other args are checked later */ if (d == NULL || dLen == NULL) return BAD_FUNC_ARG; return wc_ecc_export_raw(key, qx, qxLen, qy, qyLen, d, dLen); } #endif /* HAVE_ECC_KEY_EXPORT */ #ifdef HAVE_ECC_KEY_IMPORT /* import private key, public part optional if (pub) passed as NULL */ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, const byte* pub, word32 pubSz, ecc_key* key, int curve_id) { int ret; word32 idx = 0; if (key == NULL || priv == NULL) return BAD_FUNC_ARG; /* public optional, NULL if only importing private */ if (pub != NULL) { ret = wc_ecc_import_x963_ex(pub, pubSz, key, curve_id); if (ret < 0) ret = wc_EccPublicKeyDecode(pub, &idx, key, pubSz); key->type = ECC_PRIVATEKEY; } else { /* make sure required variables are reset */ wc_ecc_reset(key); /* set key size */ ret = wc_ecc_set_curve(key, privSz, curve_id); key->type = ECC_PRIVATEKEY_ONLY; } if (ret != 0) return ret; #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ return BAD_COND_E; #else ret = mp_read_unsigned_bin(&key->k, priv, privSz); #endif /* WOLFSSL_ATECC508A */ #ifdef WOLFSSL_VALIDATE_ECC_IMPORT if ((pub != NULL) && (ret == MP_OKAY)) /* public key needed to perform key validation */ ret = ecc_check_privkey_gen_helper(key); #endif return ret; } /* ecc private key import, public key in ANSI X9.63 format, private raw */ int wc_ecc_import_private_key(const byte* priv, word32 privSz, const byte* pub, word32 pubSz, ecc_key* key) { return wc_ecc_import_private_key_ex(priv, privSz, pub, pubSz, key, ECC_CURVE_DEF); } #endif /* HAVE_ECC_KEY_IMPORT */ #ifndef NO_ASN /** Convert ECC R,S to signature r R component of signature s S component of signature out DER-encoded ECDSA signature outlen [in/out] output buffer size, output signature size return MP_OKAY on success */ int wc_ecc_rs_to_sig(const char* r, const char* s, byte* out, word32* outlen) { int err; mp_int rtmp; mp_int stmp; if (r == NULL || s == NULL || out == NULL || outlen == NULL) return ECC_BAD_ARG_E; err = mp_init_multi(&rtmp, &stmp, NULL, NULL, NULL, NULL); if (err != MP_OKAY) return err; err = mp_read_radix(&rtmp, r, MP_RADIX_HEX); if (err == MP_OKAY) err = mp_read_radix(&stmp, s, MP_RADIX_HEX); /* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */ if (err == MP_OKAY) err = StoreECC_DSA_Sig(out, outlen, &rtmp, &stmp); if (err == MP_OKAY) { if (mp_iszero(&rtmp) == MP_YES || mp_iszero(&stmp) == MP_YES) err = MP_ZERO_E; } mp_clear(&rtmp); mp_clear(&stmp); return err; } /** Convert ECC R,S raw unsigned bin to signature r R component of signature rSz R size s S component of signature sSz S size out DER-encoded ECDSA signature outlen [in/out] output buffer size, output signature size return MP_OKAY on success */ int wc_ecc_rs_raw_to_sig(const byte* r, word32 rSz, const byte* s, word32 sSz, byte* out, word32* outlen) { int err; mp_int rtmp; mp_int stmp; if (r == NULL || s == NULL || out == NULL || outlen == NULL) return ECC_BAD_ARG_E; err = mp_init_multi(&rtmp, &stmp, NULL, NULL, NULL, NULL); if (err != MP_OKAY) return err; err = mp_read_unsigned_bin(&rtmp, r, rSz); if (err == MP_OKAY) err = mp_read_unsigned_bin(&stmp, s, sSz); /* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */ if (err == MP_OKAY) err = StoreECC_DSA_Sig(out, outlen, &rtmp, &stmp); if (err == MP_OKAY) { if (mp_iszero(&rtmp) == MP_YES || mp_iszero(&stmp) == MP_YES) err = MP_ZERO_E; } mp_clear(&rtmp); mp_clear(&stmp); return err; } /** Convert ECC signature to R,S sig DER-encoded ECDSA signature sigLen length of signature in octets r R component of signature rLen [in/out] output "r" buffer size, output "r" size s S component of signature sLen [in/out] output "s" buffer size, output "s" size return MP_OKAY on success, negative on error */ int wc_ecc_sig_to_rs(const byte* sig, word32 sigLen, byte* r, word32* rLen, byte* s, word32* sLen) { int err; word32 x = 0; mp_int rtmp; mp_int stmp; if (sig == NULL || r == NULL || rLen == NULL || s == NULL || sLen == NULL) return ECC_BAD_ARG_E; err = DecodeECC_DSA_Sig(sig, sigLen, &rtmp, &stmp); /* extract r */ if (err == MP_OKAY) { x = mp_unsigned_bin_size(&rtmp); if (*rLen < x) err = BUFFER_E; if (err == MP_OKAY) { *rLen = x; err = mp_to_unsigned_bin(&rtmp, r); } } /* extract s */ if (err == MP_OKAY) { x = mp_unsigned_bin_size(&stmp); if (*sLen < x) err = BUFFER_E; if (err == MP_OKAY) { *sLen = x; err = mp_to_unsigned_bin(&stmp, s); } } mp_clear(&rtmp); mp_clear(&stmp); return err; } #endif /* !NO_ASN */ #ifdef HAVE_ECC_KEY_IMPORT static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, const char* qy, const char* d, int curve_id, int encType) { int err = MP_OKAY; /* if d is NULL, only import as public key using Qx,Qy */ if (key == NULL || qx == NULL || qy == NULL) { return BAD_FUNC_ARG; } /* make sure required variables are reset */ wc_ecc_reset(key); /* set curve type and index */ err = wc_ecc_set_curve(key, 0, curve_id); if (err != 0) { return err; } #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ err = BAD_COND_E; #else /* init key */ #ifdef ALT_ECC_SIZE key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); err = mp_init(&key->k); #else err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif if (err != MP_OKAY) return MEMORY_E; /* read Qx */ if (err == MP_OKAY) { if (encType == ECC_TYPE_HEX_STR) err = mp_read_radix(key->pubkey.x, qx, MP_RADIX_HEX); else err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx, key->dp->size); } /* read Qy */ if (err == MP_OKAY) { if (encType == ECC_TYPE_HEX_STR) err = mp_read_radix(key->pubkey.y, qy, MP_RADIX_HEX); else err = mp_read_unsigned_bin(key->pubkey.y, (const byte*)qy, key->dp->size); } if (err == MP_OKAY) err = mp_set(key->pubkey.z, 1); /* import private key */ if (err == MP_OKAY) { if (d != NULL) { key->type = ECC_PRIVATEKEY; if (encType == ECC_TYPE_HEX_STR) err = mp_read_radix(&key->k, d, MP_RADIX_HEX); else err = mp_read_unsigned_bin(&key->k, (const byte*)d, key->dp->size); } else { key->type = ECC_PUBLICKEY; } } #ifdef WOLFSSL_VALIDATE_ECC_IMPORT if (err == MP_OKAY) err = wc_ecc_check_key(key); #endif if (err != MP_OKAY) { mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); mp_clear(&key->k); } #endif /* WOLFSSL_ATECC508A */ return err; } /** Import raw ECC key key The destination ecc_key structure qx x component of the public key, as ASCII hex string qy y component of the public key, as ASCII hex string d private key, as ASCII hex string, optional if importing public key only dp Custom ecc_set_type return MP_OKAY on success */ int wc_ecc_import_raw_ex(ecc_key* key, const char* qx, const char* qy, const char* d, int curve_id) { return wc_ecc_import_raw_private(key, qx, qy, d, curve_id, ECC_TYPE_HEX_STR); } /* Import x, y and optional private (d) as unsigned binary */ int wc_ecc_import_unsigned(ecc_key* key, byte* qx, byte* qy, byte* d, int curve_id) { return wc_ecc_import_raw_private(key, (const char*)qx, (const char*)qy, (const char*)d, curve_id, ECC_TYPE_UNSIGNED_BIN); } /** Import raw ECC key key The destination ecc_key structure qx x component of the public key, as ASCII hex string qy y component of the public key, as ASCII hex string d private key, as ASCII hex string, optional if importing public key only curveName ECC curve name, from ecc_sets[] return MP_OKAY on success */ int wc_ecc_import_raw(ecc_key* key, const char* qx, const char* qy, const char* d, const char* curveName) { int err, x; /* if d is NULL, only import as public key using Qx,Qy */ if (key == NULL || qx == NULL || qy == NULL || curveName == NULL) { return BAD_FUNC_ARG; } /* set curve type and index */ for (x = 0; ecc_sets[x].size != 0; x++) { if (XSTRNCMP(ecc_sets[x].name, curveName, XSTRLEN(curveName)) == 0) { break; } } if (ecc_sets[x].size == 0) { WOLFSSL_MSG("ecc_set curve name not found"); err = ASN_PARSE_E; } else { return wc_ecc_import_raw_private(key, qx, qy, d, ecc_sets[x].id, ECC_TYPE_HEX_STR); } return err; } #endif /* HAVE_ECC_KEY_IMPORT */ /* key size in octets */ int wc_ecc_size(ecc_key* key) { if (key == NULL) return 0; return key->dp->size; } int wc_ecc_sig_size_calc(int sz) { return (sz * 2) + SIG_HEADER_SZ + ECC_MAX_PAD_SZ; } /* worst case estimate, check actual return from wc_ecc_sign_hash for actual value of signature size in octets */ int wc_ecc_sig_size(ecc_key* key) { int sz = wc_ecc_size(key); if (sz <= 0) return sz; return wc_ecc_sig_size_calc(sz); } #ifdef FP_ECC /* fixed point ECC cache */ /* number of entries in the cache */ #ifndef FP_ENTRIES #define FP_ENTRIES 15 #endif /* number of bits in LUT */ #ifndef FP_LUT #define FP_LUT 8U #endif #ifdef ECC_SHAMIR /* Sharmir requires a bigger LUT, TAO */ #if (FP_LUT > 12) || (FP_LUT < 4) #error FP_LUT must be between 4 and 12 inclusively #endif #else #if (FP_LUT > 12) || (FP_LUT < 2) #error FP_LUT must be between 2 and 12 inclusively #endif #endif #ifndef WOLFSSL_SP_MATH /** Our FP cache */ typedef struct { ecc_point* g; /* cached COPY of base point */ ecc_point* LUT[1U<<FP_LUT]; /* fixed point lookup */ mp_int mu; /* copy of the montgomery constant */ int lru_count; /* amount of times this entry has been used */ int lock; /* flag to indicate cache eviction */ /* permitted (0) or not (1) */ } fp_cache_t; /* if HAVE_THREAD_LS this cache is per thread, no locking needed */ static THREAD_LS_T fp_cache_t fp_cache[FP_ENTRIES]; #ifndef HAVE_THREAD_LS static volatile int initMutex = 0; /* prevent multiple mutex inits */ static wolfSSL_Mutex ecc_fp_lock; #endif /* HAVE_THREAD_LS */ /* simple table to help direct the generation of the LUT */ static const struct { int ham, terma, termb; } lut_orders[] = { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 0, 0 }, { 2, 1, 2 }, { 1, 0, 0 }, { 2, 1, 4 }, { 2, 2, 4 }, { 3, 3, 4 }, { 1, 0, 0 }, { 2, 1, 8 }, { 2, 2, 8 }, { 3, 3, 8 }, { 2, 4, 8 }, { 3, 5, 8 }, { 3, 6, 8 }, { 4, 7, 8 }, { 1, 0, 0 }, { 2, 1, 16 }, { 2, 2, 16 }, { 3, 3, 16 }, { 2, 4, 16 }, { 3, 5, 16 }, { 3, 6, 16 }, { 4, 7, 16 }, { 2, 8, 16 }, { 3, 9, 16 }, { 3, 10, 16 }, { 4, 11, 16 }, { 3, 12, 16 }, { 4, 13, 16 }, { 4, 14, 16 }, { 5, 15, 16 }, { 1, 0, 0 }, { 2, 1, 32 }, { 2, 2, 32 }, { 3, 3, 32 }, { 2, 4, 32 }, { 3, 5, 32 }, { 3, 6, 32 }, { 4, 7, 32 }, { 2, 8, 32 }, { 3, 9, 32 }, { 3, 10, 32 }, { 4, 11, 32 }, { 3, 12, 32 }, { 4, 13, 32 }, { 4, 14, 32 }, { 5, 15, 32 }, { 2, 16, 32 }, { 3, 17, 32 }, { 3, 18, 32 }, { 4, 19, 32 }, { 3, 20, 32 }, { 4, 21, 32 }, { 4, 22, 32 }, { 5, 23, 32 }, { 3, 24, 32 }, { 4, 25, 32 }, { 4, 26, 32 }, { 5, 27, 32 }, { 4, 28, 32 }, { 5, 29, 32 }, { 5, 30, 32 }, { 6, 31, 32 }, #if FP_LUT > 6 { 1, 0, 0 }, { 2, 1, 64 }, { 2, 2, 64 }, { 3, 3, 64 }, { 2, 4, 64 }, { 3, 5, 64 }, { 3, 6, 64 }, { 4, 7, 64 }, { 2, 8, 64 }, { 3, 9, 64 }, { 3, 10, 64 }, { 4, 11, 64 }, { 3, 12, 64 }, { 4, 13, 64 }, { 4, 14, 64 }, { 5, 15, 64 }, { 2, 16, 64 }, { 3, 17, 64 }, { 3, 18, 64 }, { 4, 19, 64 }, { 3, 20, 64 }, { 4, 21, 64 }, { 4, 22, 64 }, { 5, 23, 64 }, { 3, 24, 64 }, { 4, 25, 64 }, { 4, 26, 64 }, { 5, 27, 64 }, { 4, 28, 64 }, { 5, 29, 64 }, { 5, 30, 64 }, { 6, 31, 64 }, { 2, 32, 64 }, { 3, 33, 64 }, { 3, 34, 64 }, { 4, 35, 64 }, { 3, 36, 64 }, { 4, 37, 64 }, { 4, 38, 64 }, { 5, 39, 64 }, { 3, 40, 64 }, { 4, 41, 64 }, { 4, 42, 64 }, { 5, 43, 64 }, { 4, 44, 64 }, { 5, 45, 64 }, { 5, 46, 64 }, { 6, 47, 64 }, { 3, 48, 64 }, { 4, 49, 64 }, { 4, 50, 64 }, { 5, 51, 64 }, { 4, 52, 64 }, { 5, 53, 64 }, { 5, 54, 64 }, { 6, 55, 64 }, { 4, 56, 64 }, { 5, 57, 64 }, { 5, 58, 64 }, { 6, 59, 64 }, { 5, 60, 64 }, { 6, 61, 64 }, { 6, 62, 64 }, { 7, 63, 64 }, #if FP_LUT > 7 { 1, 0, 0 }, { 2, 1, 128 }, { 2, 2, 128 }, { 3, 3, 128 }, { 2, 4, 128 }, { 3, 5, 128 }, { 3, 6, 128 }, { 4, 7, 128 }, { 2, 8, 128 }, { 3, 9, 128 }, { 3, 10, 128 }, { 4, 11, 128 }, { 3, 12, 128 }, { 4, 13, 128 }, { 4, 14, 128 }, { 5, 15, 128 }, { 2, 16, 128 }, { 3, 17, 128 }, { 3, 18, 128 }, { 4, 19, 128 }, { 3, 20, 128 }, { 4, 21, 128 }, { 4, 22, 128 }, { 5, 23, 128 }, { 3, 24, 128 }, { 4, 25, 128 }, { 4, 26, 128 }, { 5, 27, 128 }, { 4, 28, 128 }, { 5, 29, 128 }, { 5, 30, 128 }, { 6, 31, 128 }, { 2, 32, 128 }, { 3, 33, 128 }, { 3, 34, 128 }, { 4, 35, 128 }, { 3, 36, 128 }, { 4, 37, 128 }, { 4, 38, 128 }, { 5, 39, 128 }, { 3, 40, 128 }, { 4, 41, 128 }, { 4, 42, 128 }, { 5, 43, 128 }, { 4, 44, 128 }, { 5, 45, 128 }, { 5, 46, 128 }, { 6, 47, 128 }, { 3, 48, 128 }, { 4, 49, 128 }, { 4, 50, 128 }, { 5, 51, 128 }, { 4, 52, 128 }, { 5, 53, 128 }, { 5, 54, 128 }, { 6, 55, 128 }, { 4, 56, 128 }, { 5, 57, 128 }, { 5, 58, 128 }, { 6, 59, 128 }, { 5, 60, 128 }, { 6, 61, 128 }, { 6, 62, 128 }, { 7, 63, 128 }, { 2, 64, 128 }, { 3, 65, 128 }, { 3, 66, 128 }, { 4, 67, 128 }, { 3, 68, 128 }, { 4, 69, 128 }, { 4, 70, 128 }, { 5, 71, 128 }, { 3, 72, 128 }, { 4, 73, 128 }, { 4, 74, 128 }, { 5, 75, 128 }, { 4, 76, 128 }, { 5, 77, 128 }, { 5, 78, 128 }, { 6, 79, 128 }, { 3, 80, 128 }, { 4, 81, 128 }, { 4, 82, 128 }, { 5, 83, 128 }, { 4, 84, 128 }, { 5, 85, 128 }, { 5, 86, 128 }, { 6, 87, 128 }, { 4, 88, 128 }, { 5, 89, 128 }, { 5, 90, 128 }, { 6, 91, 128 }, { 5, 92, 128 }, { 6, 93, 128 }, { 6, 94, 128 }, { 7, 95, 128 }, { 3, 96, 128 }, { 4, 97, 128 }, { 4, 98, 128 }, { 5, 99, 128 }, { 4, 100, 128 }, { 5, 101, 128 }, { 5, 102, 128 }, { 6, 103, 128 }, { 4, 104, 128 }, { 5, 105, 128 }, { 5, 106, 128 }, { 6, 107, 128 }, { 5, 108, 128 }, { 6, 109, 128 }, { 6, 110, 128 }, { 7, 111, 128 }, { 4, 112, 128 }, { 5, 113, 128 }, { 5, 114, 128 }, { 6, 115, 128 }, { 5, 116, 128 }, { 6, 117, 128 }, { 6, 118, 128 }, { 7, 119, 128 }, { 5, 120, 128 }, { 6, 121, 128 }, { 6, 122, 128 }, { 7, 123, 128 }, { 6, 124, 128 }, { 7, 125, 128 }, { 7, 126, 128 }, { 8, 127, 128 }, #if FP_LUT > 8 { 1, 0, 0 }, { 2, 1, 256 }, { 2, 2, 256 }, { 3, 3, 256 }, { 2, 4, 256 }, { 3, 5, 256 }, { 3, 6, 256 }, { 4, 7, 256 }, { 2, 8, 256 }, { 3, 9, 256 }, { 3, 10, 256 }, { 4, 11, 256 }, { 3, 12, 256 }, { 4, 13, 256 }, { 4, 14, 256 }, { 5, 15, 256 }, { 2, 16, 256 }, { 3, 17, 256 }, { 3, 18, 256 }, { 4, 19, 256 }, { 3, 20, 256 }, { 4, 21, 256 }, { 4, 22, 256 }, { 5, 23, 256 }, { 3, 24, 256 }, { 4, 25, 256 }, { 4, 26, 256 }, { 5, 27, 256 }, { 4, 28, 256 }, { 5, 29, 256 }, { 5, 30, 256 }, { 6, 31, 256 }, { 2, 32, 256 }, { 3, 33, 256 }, { 3, 34, 256 }, { 4, 35, 256 }, { 3, 36, 256 }, { 4, 37, 256 }, { 4, 38, 256 }, { 5, 39, 256 }, { 3, 40, 256 }, { 4, 41, 256 }, { 4, 42, 256 }, { 5, 43, 256 }, { 4, 44, 256 }, { 5, 45, 256 }, { 5, 46, 256 }, { 6, 47, 256 }, { 3, 48, 256 }, { 4, 49, 256 }, { 4, 50, 256 }, { 5, 51, 256 }, { 4, 52, 256 }, { 5, 53, 256 }, { 5, 54, 256 }, { 6, 55, 256 }, { 4, 56, 256 }, { 5, 57, 256 }, { 5, 58, 256 }, { 6, 59, 256 }, { 5, 60, 256 }, { 6, 61, 256 }, { 6, 62, 256 }, { 7, 63, 256 }, { 2, 64, 256 }, { 3, 65, 256 }, { 3, 66, 256 }, { 4, 67, 256 }, { 3, 68, 256 }, { 4, 69, 256 }, { 4, 70, 256 }, { 5, 71, 256 }, { 3, 72, 256 }, { 4, 73, 256 }, { 4, 74, 256 }, { 5, 75, 256 }, { 4, 76, 256 }, { 5, 77, 256 }, { 5, 78, 256 }, { 6, 79, 256 }, { 3, 80, 256 }, { 4, 81, 256 }, { 4, 82, 256 }, { 5, 83, 256 }, { 4, 84, 256 }, { 5, 85, 256 }, { 5, 86, 256 }, { 6, 87, 256 }, { 4, 88, 256 }, { 5, 89, 256 }, { 5, 90, 256 }, { 6, 91, 256 }, { 5, 92, 256 }, { 6, 93, 256 }, { 6, 94, 256 }, { 7, 95, 256 }, { 3, 96, 256 }, { 4, 97, 256 }, { 4, 98, 256 }, { 5, 99, 256 }, { 4, 100, 256 }, { 5, 101, 256 }, { 5, 102, 256 }, { 6, 103, 256 }, { 4, 104, 256 }, { 5, 105, 256 }, { 5, 106, 256 }, { 6, 107, 256 }, { 5, 108, 256 }, { 6, 109, 256 }, { 6, 110, 256 }, { 7, 111, 256 }, { 4, 112, 256 }, { 5, 113, 256 }, { 5, 114, 256 }, { 6, 115, 256 }, { 5, 116, 256 }, { 6, 117, 256 }, { 6, 118, 256 }, { 7, 119, 256 }, { 5, 120, 256 }, { 6, 121, 256 }, { 6, 122, 256 }, { 7, 123, 256 }, { 6, 124, 256 }, { 7, 125, 256 }, { 7, 126, 256 }, { 8, 127, 256 }, { 2, 128, 256 }, { 3, 129, 256 }, { 3, 130, 256 }, { 4, 131, 256 }, { 3, 132, 256 }, { 4, 133, 256 }, { 4, 134, 256 }, { 5, 135, 256 }, { 3, 136, 256 }, { 4, 137, 256 }, { 4, 138, 256 }, { 5, 139, 256 }, { 4, 140, 256 }, { 5, 141, 256 }, { 5, 142, 256 }, { 6, 143, 256 }, { 3, 144, 256 }, { 4, 145, 256 }, { 4, 146, 256 }, { 5, 147, 256 }, { 4, 148, 256 }, { 5, 149, 256 }, { 5, 150, 256 }, { 6, 151, 256 }, { 4, 152, 256 }, { 5, 153, 256 }, { 5, 154, 256 }, { 6, 155, 256 }, { 5, 156, 256 }, { 6, 157, 256 }, { 6, 158, 256 }, { 7, 159, 256 }, { 3, 160, 256 }, { 4, 161, 256 }, { 4, 162, 256 }, { 5, 163, 256 }, { 4, 164, 256 }, { 5, 165, 256 }, { 5, 166, 256 }, { 6, 167, 256 }, { 4, 168, 256 }, { 5, 169, 256 }, { 5, 170, 256 }, { 6, 171, 256 }, { 5, 172, 256 }, { 6, 173, 256 }, { 6, 174, 256 }, { 7, 175, 256 }, { 4, 176, 256 }, { 5, 177, 256 }, { 5, 178, 256 }, { 6, 179, 256 }, { 5, 180, 256 }, { 6, 181, 256 }, { 6, 182, 256 }, { 7, 183, 256 }, { 5, 184, 256 }, { 6, 185, 256 }, { 6, 186, 256 }, { 7, 187, 256 }, { 6, 188, 256 }, { 7, 189, 256 }, { 7, 190, 256 }, { 8, 191, 256 }, { 3, 192, 256 }, { 4, 193, 256 }, { 4, 194, 256 }, { 5, 195, 256 }, { 4, 196, 256 }, { 5, 197, 256 }, { 5, 198, 256 }, { 6, 199, 256 }, { 4, 200, 256 }, { 5, 201, 256 }, { 5, 202, 256 }, { 6, 203, 256 }, { 5, 204, 256 }, { 6, 205, 256 }, { 6, 206, 256 }, { 7, 207, 256 }, { 4, 208, 256 }, { 5, 209, 256 }, { 5, 210, 256 }, { 6, 211, 256 }, { 5, 212, 256 }, { 6, 213, 256 }, { 6, 214, 256 }, { 7, 215, 256 }, { 5, 216, 256 }, { 6, 217, 256 }, { 6, 218, 256 }, { 7, 219, 256 }, { 6, 220, 256 }, { 7, 221, 256 }, { 7, 222, 256 }, { 8, 223, 256 }, { 4, 224, 256 }, { 5, 225, 256 }, { 5, 226, 256 }, { 6, 227, 256 }, { 5, 228, 256 }, { 6, 229, 256 }, { 6, 230, 256 }, { 7, 231, 256 }, { 5, 232, 256 }, { 6, 233, 256 }, { 6, 234, 256 }, { 7, 235, 256 }, { 6, 236, 256 }, { 7, 237, 256 }, { 7, 238, 256 }, { 8, 239, 256 }, { 5, 240, 256 }, { 6, 241, 256 }, { 6, 242, 256 }, { 7, 243, 256 }, { 6, 244, 256 }, { 7, 245, 256 }, { 7, 246, 256 }, { 8, 247, 256 }, { 6, 248, 256 }, { 7, 249, 256 }, { 7, 250, 256 }, { 8, 251, 256 }, { 7, 252, 256 }, { 8, 253, 256 }, { 8, 254, 256 }, { 9, 255, 256 }, #if FP_LUT > 9 { 1, 0, 0 }, { 2, 1, 512 }, { 2, 2, 512 }, { 3, 3, 512 }, { 2, 4, 512 }, { 3, 5, 512 }, { 3, 6, 512 }, { 4, 7, 512 }, { 2, 8, 512 }, { 3, 9, 512 }, { 3, 10, 512 }, { 4, 11, 512 }, { 3, 12, 512 }, { 4, 13, 512 }, { 4, 14, 512 }, { 5, 15, 512 }, { 2, 16, 512 }, { 3, 17, 512 }, { 3, 18, 512 }, { 4, 19, 512 }, { 3, 20, 512 }, { 4, 21, 512 }, { 4, 22, 512 }, { 5, 23, 512 }, { 3, 24, 512 }, { 4, 25, 512 }, { 4, 26, 512 }, { 5, 27, 512 }, { 4, 28, 512 }, { 5, 29, 512 }, { 5, 30, 512 }, { 6, 31, 512 }, { 2, 32, 512 }, { 3, 33, 512 }, { 3, 34, 512 }, { 4, 35, 512 }, { 3, 36, 512 }, { 4, 37, 512 }, { 4, 38, 512 }, { 5, 39, 512 }, { 3, 40, 512 }, { 4, 41, 512 }, { 4, 42, 512 }, { 5, 43, 512 }, { 4, 44, 512 }, { 5, 45, 512 }, { 5, 46, 512 }, { 6, 47, 512 }, { 3, 48, 512 }, { 4, 49, 512 }, { 4, 50, 512 }, { 5, 51, 512 }, { 4, 52, 512 }, { 5, 53, 512 }, { 5, 54, 512 }, { 6, 55, 512 }, { 4, 56, 512 }, { 5, 57, 512 }, { 5, 58, 512 }, { 6, 59, 512 }, { 5, 60, 512 }, { 6, 61, 512 }, { 6, 62, 512 }, { 7, 63, 512 }, { 2, 64, 512 }, { 3, 65, 512 }, { 3, 66, 512 }, { 4, 67, 512 }, { 3, 68, 512 }, { 4, 69, 512 }, { 4, 70, 512 }, { 5, 71, 512 }, { 3, 72, 512 }, { 4, 73, 512 }, { 4, 74, 512 }, { 5, 75, 512 }, { 4, 76, 512 }, { 5, 77, 512 }, { 5, 78, 512 }, { 6, 79, 512 }, { 3, 80, 512 }, { 4, 81, 512 }, { 4, 82, 512 }, { 5, 83, 512 }, { 4, 84, 512 }, { 5, 85, 512 }, { 5, 86, 512 }, { 6, 87, 512 }, { 4, 88, 512 }, { 5, 89, 512 }, { 5, 90, 512 }, { 6, 91, 512 }, { 5, 92, 512 }, { 6, 93, 512 }, { 6, 94, 512 }, { 7, 95, 512 }, { 3, 96, 512 }, { 4, 97, 512 }, { 4, 98, 512 }, { 5, 99, 512 }, { 4, 100, 512 }, { 5, 101, 512 }, { 5, 102, 512 }, { 6, 103, 512 }, { 4, 104, 512 }, { 5, 105, 512 }, { 5, 106, 512 }, { 6, 107, 512 }, { 5, 108, 512 }, { 6, 109, 512 }, { 6, 110, 512 }, { 7, 111, 512 }, { 4, 112, 512 }, { 5, 113, 512 }, { 5, 114, 512 }, { 6, 115, 512 }, { 5, 116, 512 }, { 6, 117, 512 }, { 6, 118, 512 }, { 7, 119, 512 }, { 5, 120, 512 }, { 6, 121, 512 }, { 6, 122, 512 }, { 7, 123, 512 }, { 6, 124, 512 }, { 7, 125, 512 }, { 7, 126, 512 }, { 8, 127, 512 }, { 2, 128, 512 }, { 3, 129, 512 }, { 3, 130, 512 }, { 4, 131, 512 }, { 3, 132, 512 }, { 4, 133, 512 }, { 4, 134, 512 }, { 5, 135, 512 }, { 3, 136, 512 }, { 4, 137, 512 }, { 4, 138, 512 }, { 5, 139, 512 }, { 4, 140, 512 }, { 5, 141, 512 }, { 5, 142, 512 }, { 6, 143, 512 }, { 3, 144, 512 }, { 4, 145, 512 }, { 4, 146, 512 }, { 5, 147, 512 }, { 4, 148, 512 }, { 5, 149, 512 }, { 5, 150, 512 }, { 6, 151, 512 }, { 4, 152, 512 }, { 5, 153, 512 }, { 5, 154, 512 }, { 6, 155, 512 }, { 5, 156, 512 }, { 6, 157, 512 }, { 6, 158, 512 }, { 7, 159, 512 }, { 3, 160, 512 }, { 4, 161, 512 }, { 4, 162, 512 }, { 5, 163, 512 }, { 4, 164, 512 }, { 5, 165, 512 }, { 5, 166, 512 }, { 6, 167, 512 }, { 4, 168, 512 }, { 5, 169, 512 }, { 5, 170, 512 }, { 6, 171, 512 }, { 5, 172, 512 }, { 6, 173, 512 }, { 6, 174, 512 }, { 7, 175, 512 }, { 4, 176, 512 }, { 5, 177, 512 }, { 5, 178, 512 }, { 6, 179, 512 }, { 5, 180, 512 }, { 6, 181, 512 }, { 6, 182, 512 }, { 7, 183, 512 }, { 5, 184, 512 }, { 6, 185, 512 }, { 6, 186, 512 }, { 7, 187, 512 }, { 6, 188, 512 }, { 7, 189, 512 }, { 7, 190, 512 }, { 8, 191, 512 }, { 3, 192, 512 }, { 4, 193, 512 }, { 4, 194, 512 }, { 5, 195, 512 }, { 4, 196, 512 }, { 5, 197, 512 }, { 5, 198, 512 }, { 6, 199, 512 }, { 4, 200, 512 }, { 5, 201, 512 }, { 5, 202, 512 }, { 6, 203, 512 }, { 5, 204, 512 }, { 6, 205, 512 }, { 6, 206, 512 }, { 7, 207, 512 }, { 4, 208, 512 }, { 5, 209, 512 }, { 5, 210, 512 }, { 6, 211, 512 }, { 5, 212, 512 }, { 6, 213, 512 }, { 6, 214, 512 }, { 7, 215, 512 }, { 5, 216, 512 }, { 6, 217, 512 }, { 6, 218, 512 }, { 7, 219, 512 }, { 6, 220, 512 }, { 7, 221, 512 }, { 7, 222, 512 }, { 8, 223, 512 }, { 4, 224, 512 }, { 5, 225, 512 }, { 5, 226, 512 }, { 6, 227, 512 }, { 5, 228, 512 }, { 6, 229, 512 }, { 6, 230, 512 }, { 7, 231, 512 }, { 5, 232, 512 }, { 6, 233, 512 }, { 6, 234, 512 }, { 7, 235, 512 }, { 6, 236, 512 }, { 7, 237, 512 }, { 7, 238, 512 }, { 8, 239, 512 }, { 5, 240, 512 }, { 6, 241, 512 }, { 6, 242, 512 }, { 7, 243, 512 }, { 6, 244, 512 }, { 7, 245, 512 }, { 7, 246, 512 }, { 8, 247, 512 }, { 6, 248, 512 }, { 7, 249, 512 }, { 7, 250, 512 }, { 8, 251, 512 }, { 7, 252, 512 }, { 8, 253, 512 }, { 8, 254, 512 }, { 9, 255, 512 }, { 2, 256, 512 }, { 3, 257, 512 }, { 3, 258, 512 }, { 4, 259, 512 }, { 3, 260, 512 }, { 4, 261, 512 }, { 4, 262, 512 }, { 5, 263, 512 }, { 3, 264, 512 }, { 4, 265, 512 }, { 4, 266, 512 }, { 5, 267, 512 }, { 4, 268, 512 }, { 5, 269, 512 }, { 5, 270, 512 }, { 6, 271, 512 }, { 3, 272, 512 }, { 4, 273, 512 }, { 4, 274, 512 }, { 5, 275, 512 }, { 4, 276, 512 }, { 5, 277, 512 }, { 5, 278, 512 }, { 6, 279, 512 }, { 4, 280, 512 }, { 5, 281, 512 }, { 5, 282, 512 }, { 6, 283, 512 }, { 5, 284, 512 }, { 6, 285, 512 }, { 6, 286, 512 }, { 7, 287, 512 }, { 3, 288, 512 }, { 4, 289, 512 }, { 4, 290, 512 }, { 5, 291, 512 }, { 4, 292, 512 }, { 5, 293, 512 }, { 5, 294, 512 }, { 6, 295, 512 }, { 4, 296, 512 }, { 5, 297, 512 }, { 5, 298, 512 }, { 6, 299, 512 }, { 5, 300, 512 }, { 6, 301, 512 }, { 6, 302, 512 }, { 7, 303, 512 }, { 4, 304, 512 }, { 5, 305, 512 }, { 5, 306, 512 }, { 6, 307, 512 }, { 5, 308, 512 }, { 6, 309, 512 }, { 6, 310, 512 }, { 7, 311, 512 }, { 5, 312, 512 }, { 6, 313, 512 }, { 6, 314, 512 }, { 7, 315, 512 }, { 6, 316, 512 }, { 7, 317, 512 }, { 7, 318, 512 }, { 8, 319, 512 }, { 3, 320, 512 }, { 4, 321, 512 }, { 4, 322, 512 }, { 5, 323, 512 }, { 4, 324, 512 }, { 5, 325, 512 }, { 5, 326, 512 }, { 6, 327, 512 }, { 4, 328, 512 }, { 5, 329, 512 }, { 5, 330, 512 }, { 6, 331, 512 }, { 5, 332, 512 }, { 6, 333, 512 }, { 6, 334, 512 }, { 7, 335, 512 }, { 4, 336, 512 }, { 5, 337, 512 }, { 5, 338, 512 }, { 6, 339, 512 }, { 5, 340, 512 }, { 6, 341, 512 }, { 6, 342, 512 }, { 7, 343, 512 }, { 5, 344, 512 }, { 6, 345, 512 }, { 6, 346, 512 }, { 7, 347, 512 }, { 6, 348, 512 }, { 7, 349, 512 }, { 7, 350, 512 }, { 8, 351, 512 }, { 4, 352, 512 }, { 5, 353, 512 }, { 5, 354, 512 }, { 6, 355, 512 }, { 5, 356, 512 }, { 6, 357, 512 }, { 6, 358, 512 }, { 7, 359, 512 }, { 5, 360, 512 }, { 6, 361, 512 }, { 6, 362, 512 }, { 7, 363, 512 }, { 6, 364, 512 }, { 7, 365, 512 }, { 7, 366, 512 }, { 8, 367, 512 }, { 5, 368, 512 }, { 6, 369, 512 }, { 6, 370, 512 }, { 7, 371, 512 }, { 6, 372, 512 }, { 7, 373, 512 }, { 7, 374, 512 }, { 8, 375, 512 }, { 6, 376, 512 }, { 7, 377, 512 }, { 7, 378, 512 }, { 8, 379, 512 }, { 7, 380, 512 }, { 8, 381, 512 }, { 8, 382, 512 }, { 9, 383, 512 }, { 3, 384, 512 }, { 4, 385, 512 }, { 4, 386, 512 }, { 5, 387, 512 }, { 4, 388, 512 }, { 5, 389, 512 }, { 5, 390, 512 }, { 6, 391, 512 }, { 4, 392, 512 }, { 5, 393, 512 }, { 5, 394, 512 }, { 6, 395, 512 }, { 5, 396, 512 }, { 6, 397, 512 }, { 6, 398, 512 }, { 7, 399, 512 }, { 4, 400, 512 }, { 5, 401, 512 }, { 5, 402, 512 }, { 6, 403, 512 }, { 5, 404, 512 }, { 6, 405, 512 }, { 6, 406, 512 }, { 7, 407, 512 }, { 5, 408, 512 }, { 6, 409, 512 }, { 6, 410, 512 }, { 7, 411, 512 }, { 6, 412, 512 }, { 7, 413, 512 }, { 7, 414, 512 }, { 8, 415, 512 }, { 4, 416, 512 }, { 5, 417, 512 }, { 5, 418, 512 }, { 6, 419, 512 }, { 5, 420, 512 }, { 6, 421, 512 }, { 6, 422, 512 }, { 7, 423, 512 }, { 5, 424, 512 }, { 6, 425, 512 }, { 6, 426, 512 }, { 7, 427, 512 }, { 6, 428, 512 }, { 7, 429, 512 }, { 7, 430, 512 }, { 8, 431, 512 }, { 5, 432, 512 }, { 6, 433, 512 }, { 6, 434, 512 }, { 7, 435, 512 }, { 6, 436, 512 }, { 7, 437, 512 }, { 7, 438, 512 }, { 8, 439, 512 }, { 6, 440, 512 }, { 7, 441, 512 }, { 7, 442, 512 }, { 8, 443, 512 }, { 7, 444, 512 }, { 8, 445, 512 }, { 8, 446, 512 }, { 9, 447, 512 }, { 4, 448, 512 }, { 5, 449, 512 }, { 5, 450, 512 }, { 6, 451, 512 }, { 5, 452, 512 }, { 6, 453, 512 }, { 6, 454, 512 }, { 7, 455, 512 }, { 5, 456, 512 }, { 6, 457, 512 }, { 6, 458, 512 }, { 7, 459, 512 }, { 6, 460, 512 }, { 7, 461, 512 }, { 7, 462, 512 }, { 8, 463, 512 }, { 5, 464, 512 }, { 6, 465, 512 }, { 6, 466, 512 }, { 7, 467, 512 }, { 6, 468, 512 }, { 7, 469, 512 }, { 7, 470, 512 }, { 8, 471, 512 }, { 6, 472, 512 }, { 7, 473, 512 }, { 7, 474, 512 }, { 8, 475, 512 }, { 7, 476, 512 }, { 8, 477, 512 }, { 8, 478, 512 }, { 9, 479, 512 }, { 5, 480, 512 }, { 6, 481, 512 }, { 6, 482, 512 }, { 7, 483, 512 }, { 6, 484, 512 }, { 7, 485, 512 }, { 7, 486, 512 }, { 8, 487, 512 }, { 6, 488, 512 }, { 7, 489, 512 }, { 7, 490, 512 }, { 8, 491, 512 }, { 7, 492, 512 }, { 8, 493, 512 }, { 8, 494, 512 }, { 9, 495, 512 }, { 6, 496, 512 }, { 7, 497, 512 }, { 7, 498, 512 }, { 8, 499, 512 }, { 7, 500, 512 }, { 8, 501, 512 }, { 8, 502, 512 }, { 9, 503, 512 }, { 7, 504, 512 }, { 8, 505, 512 }, { 8, 506, 512 }, { 9, 507, 512 }, { 8, 508, 512 }, { 9, 509, 512 }, { 9, 510, 512 }, { 10, 511, 512 }, #if FP_LUT > 10 { 1, 0, 0 }, { 2, 1, 1024 }, { 2, 2, 1024 }, { 3, 3, 1024 }, { 2, 4, 1024 }, { 3, 5, 1024 }, { 3, 6, 1024 }, { 4, 7, 1024 }, { 2, 8, 1024 }, { 3, 9, 1024 }, { 3, 10, 1024 }, { 4, 11, 1024 }, { 3, 12, 1024 }, { 4, 13, 1024 }, { 4, 14, 1024 }, { 5, 15, 1024 }, { 2, 16, 1024 }, { 3, 17, 1024 }, { 3, 18, 1024 }, { 4, 19, 1024 }, { 3, 20, 1024 }, { 4, 21, 1024 }, { 4, 22, 1024 }, { 5, 23, 1024 }, { 3, 24, 1024 }, { 4, 25, 1024 }, { 4, 26, 1024 }, { 5, 27, 1024 }, { 4, 28, 1024 }, { 5, 29, 1024 }, { 5, 30, 1024 }, { 6, 31, 1024 }, { 2, 32, 1024 }, { 3, 33, 1024 }, { 3, 34, 1024 }, { 4, 35, 1024 }, { 3, 36, 1024 }, { 4, 37, 1024 }, { 4, 38, 1024 }, { 5, 39, 1024 }, { 3, 40, 1024 }, { 4, 41, 1024 }, { 4, 42, 1024 }, { 5, 43, 1024 }, { 4, 44, 1024 }, { 5, 45, 1024 }, { 5, 46, 1024 }, { 6, 47, 1024 }, { 3, 48, 1024 }, { 4, 49, 1024 }, { 4, 50, 1024 }, { 5, 51, 1024 }, { 4, 52, 1024 }, { 5, 53, 1024 }, { 5, 54, 1024 }, { 6, 55, 1024 }, { 4, 56, 1024 }, { 5, 57, 1024 }, { 5, 58, 1024 }, { 6, 59, 1024 }, { 5, 60, 1024 }, { 6, 61, 1024 }, { 6, 62, 1024 }, { 7, 63, 1024 }, { 2, 64, 1024 }, { 3, 65, 1024 }, { 3, 66, 1024 }, { 4, 67, 1024 }, { 3, 68, 1024 }, { 4, 69, 1024 }, { 4, 70, 1024 }, { 5, 71, 1024 }, { 3, 72, 1024 }, { 4, 73, 1024 }, { 4, 74, 1024 }, { 5, 75, 1024 }, { 4, 76, 1024 }, { 5, 77, 1024 }, { 5, 78, 1024 }, { 6, 79, 1024 }, { 3, 80, 1024 }, { 4, 81, 1024 }, { 4, 82, 1024 }, { 5, 83, 1024 }, { 4, 84, 1024 }, { 5, 85, 1024 }, { 5, 86, 1024 }, { 6, 87, 1024 }, { 4, 88, 1024 }, { 5, 89, 1024 }, { 5, 90, 1024 }, { 6, 91, 1024 }, { 5, 92, 1024 }, { 6, 93, 1024 }, { 6, 94, 1024 }, { 7, 95, 1024 }, { 3, 96, 1024 }, { 4, 97, 1024 }, { 4, 98, 1024 }, { 5, 99, 1024 }, { 4, 100, 1024 }, { 5, 101, 1024 }, { 5, 102, 1024 }, { 6, 103, 1024 }, { 4, 104, 1024 }, { 5, 105, 1024 }, { 5, 106, 1024 }, { 6, 107, 1024 }, { 5, 108, 1024 }, { 6, 109, 1024 }, { 6, 110, 1024 }, { 7, 111, 1024 }, { 4, 112, 1024 }, { 5, 113, 1024 }, { 5, 114, 1024 }, { 6, 115, 1024 }, { 5, 116, 1024 }, { 6, 117, 1024 }, { 6, 118, 1024 }, { 7, 119, 1024 }, { 5, 120, 1024 }, { 6, 121, 1024 }, { 6, 122, 1024 }, { 7, 123, 1024 }, { 6, 124, 1024 }, { 7, 125, 1024 }, { 7, 126, 1024 }, { 8, 127, 1024 }, { 2, 128, 1024 }, { 3, 129, 1024 }, { 3, 130, 1024 }, { 4, 131, 1024 }, { 3, 132, 1024 }, { 4, 133, 1024 }, { 4, 134, 1024 }, { 5, 135, 1024 }, { 3, 136, 1024 }, { 4, 137, 1024 }, { 4, 138, 1024 }, { 5, 139, 1024 }, { 4, 140, 1024 }, { 5, 141, 1024 }, { 5, 142, 1024 }, { 6, 143, 1024 }, { 3, 144, 1024 }, { 4, 145, 1024 }, { 4, 146, 1024 }, { 5, 147, 1024 }, { 4, 148, 1024 }, { 5, 149, 1024 }, { 5, 150, 1024 }, { 6, 151, 1024 }, { 4, 152, 1024 }, { 5, 153, 1024 }, { 5, 154, 1024 }, { 6, 155, 1024 }, { 5, 156, 1024 }, { 6, 157, 1024 }, { 6, 158, 1024 }, { 7, 159, 1024 }, { 3, 160, 1024 }, { 4, 161, 1024 }, { 4, 162, 1024 }, { 5, 163, 1024 }, { 4, 164, 1024 }, { 5, 165, 1024 }, { 5, 166, 1024 }, { 6, 167, 1024 }, { 4, 168, 1024 }, { 5, 169, 1024 }, { 5, 170, 1024 }, { 6, 171, 1024 }, { 5, 172, 1024 }, { 6, 173, 1024 }, { 6, 174, 1024 }, { 7, 175, 1024 }, { 4, 176, 1024 }, { 5, 177, 1024 }, { 5, 178, 1024 }, { 6, 179, 1024 }, { 5, 180, 1024 }, { 6, 181, 1024 }, { 6, 182, 1024 }, { 7, 183, 1024 }, { 5, 184, 1024 }, { 6, 185, 1024 }, { 6, 186, 1024 }, { 7, 187, 1024 }, { 6, 188, 1024 }, { 7, 189, 1024 }, { 7, 190, 1024 }, { 8, 191, 1024 }, { 3, 192, 1024 }, { 4, 193, 1024 }, { 4, 194, 1024 }, { 5, 195, 1024 }, { 4, 196, 1024 }, { 5, 197, 1024 }, { 5, 198, 1024 }, { 6, 199, 1024 }, { 4, 200, 1024 }, { 5, 201, 1024 }, { 5, 202, 1024 }, { 6, 203, 1024 }, { 5, 204, 1024 }, { 6, 205, 1024 }, { 6, 206, 1024 }, { 7, 207, 1024 }, { 4, 208, 1024 }, { 5, 209, 1024 }, { 5, 210, 1024 }, { 6, 211, 1024 }, { 5, 212, 1024 }, { 6, 213, 1024 }, { 6, 214, 1024 }, { 7, 215, 1024 }, { 5, 216, 1024 }, { 6, 217, 1024 }, { 6, 218, 1024 }, { 7, 219, 1024 }, { 6, 220, 1024 }, { 7, 221, 1024 }, { 7, 222, 1024 }, { 8, 223, 1024 }, { 4, 224, 1024 }, { 5, 225, 1024 }, { 5, 226, 1024 }, { 6, 227, 1024 }, { 5, 228, 1024 }, { 6, 229, 1024 }, { 6, 230, 1024 }, { 7, 231, 1024 }, { 5, 232, 1024 }, { 6, 233, 1024 }, { 6, 234, 1024 }, { 7, 235, 1024 }, { 6, 236, 1024 }, { 7, 237, 1024 }, { 7, 238, 1024 }, { 8, 239, 1024 }, { 5, 240, 1024 }, { 6, 241, 1024 }, { 6, 242, 1024 }, { 7, 243, 1024 }, { 6, 244, 1024 }, { 7, 245, 1024 }, { 7, 246, 1024 }, { 8, 247, 1024 }, { 6, 248, 1024 }, { 7, 249, 1024 }, { 7, 250, 1024 }, { 8, 251, 1024 }, { 7, 252, 1024 }, { 8, 253, 1024 }, { 8, 254, 1024 }, { 9, 255, 1024 }, { 2, 256, 1024 }, { 3, 257, 1024 }, { 3, 258, 1024 }, { 4, 259, 1024 }, { 3, 260, 1024 }, { 4, 261, 1024 }, { 4, 262, 1024 }, { 5, 263, 1024 }, { 3, 264, 1024 }, { 4, 265, 1024 }, { 4, 266, 1024 }, { 5, 267, 1024 }, { 4, 268, 1024 }, { 5, 269, 1024 }, { 5, 270, 1024 }, { 6, 271, 1024 }, { 3, 272, 1024 }, { 4, 273, 1024 }, { 4, 274, 1024 }, { 5, 275, 1024 }, { 4, 276, 1024 }, { 5, 277, 1024 }, { 5, 278, 1024 }, { 6, 279, 1024 }, { 4, 280, 1024 }, { 5, 281, 1024 }, { 5, 282, 1024 }, { 6, 283, 1024 }, { 5, 284, 1024 }, { 6, 285, 1024 }, { 6, 286, 1024 }, { 7, 287, 1024 }, { 3, 288, 1024 }, { 4, 289, 1024 }, { 4, 290, 1024 }, { 5, 291, 1024 }, { 4, 292, 1024 }, { 5, 293, 1024 }, { 5, 294, 1024 }, { 6, 295, 1024 }, { 4, 296, 1024 }, { 5, 297, 1024 }, { 5, 298, 1024 }, { 6, 299, 1024 }, { 5, 300, 1024 }, { 6, 301, 1024 }, { 6, 302, 1024 }, { 7, 303, 1024 }, { 4, 304, 1024 }, { 5, 305, 1024 }, { 5, 306, 1024 }, { 6, 307, 1024 }, { 5, 308, 1024 }, { 6, 309, 1024 }, { 6, 310, 1024 }, { 7, 311, 1024 }, { 5, 312, 1024 }, { 6, 313, 1024 }, { 6, 314, 1024 }, { 7, 315, 1024 }, { 6, 316, 1024 }, { 7, 317, 1024 }, { 7, 318, 1024 }, { 8, 319, 1024 }, { 3, 320, 1024 }, { 4, 321, 1024 }, { 4, 322, 1024 }, { 5, 323, 1024 }, { 4, 324, 1024 }, { 5, 325, 1024 }, { 5, 326, 1024 }, { 6, 327, 1024 }, { 4, 328, 1024 }, { 5, 329, 1024 }, { 5, 330, 1024 }, { 6, 331, 1024 }, { 5, 332, 1024 }, { 6, 333, 1024 }, { 6, 334, 1024 }, { 7, 335, 1024 }, { 4, 336, 1024 }, { 5, 337, 1024 }, { 5, 338, 1024 }, { 6, 339, 1024 }, { 5, 340, 1024 }, { 6, 341, 1024 }, { 6, 342, 1024 }, { 7, 343, 1024 }, { 5, 344, 1024 }, { 6, 345, 1024 }, { 6, 346, 1024 }, { 7, 347, 1024 }, { 6, 348, 1024 }, { 7, 349, 1024 }, { 7, 350, 1024 }, { 8, 351, 1024 }, { 4, 352, 1024 }, { 5, 353, 1024 }, { 5, 354, 1024 }, { 6, 355, 1024 }, { 5, 356, 1024 }, { 6, 357, 1024 }, { 6, 358, 1024 }, { 7, 359, 1024 }, { 5, 360, 1024 }, { 6, 361, 1024 }, { 6, 362, 1024 }, { 7, 363, 1024 }, { 6, 364, 1024 }, { 7, 365, 1024 }, { 7, 366, 1024 }, { 8, 367, 1024 }, { 5, 368, 1024 }, { 6, 369, 1024 }, { 6, 370, 1024 }, { 7, 371, 1024 }, { 6, 372, 1024 }, { 7, 373, 1024 }, { 7, 374, 1024 }, { 8, 375, 1024 }, { 6, 376, 1024 }, { 7, 377, 1024 }, { 7, 378, 1024 }, { 8, 379, 1024 }, { 7, 380, 1024 }, { 8, 381, 1024 }, { 8, 382, 1024 }, { 9, 383, 1024 }, { 3, 384, 1024 }, { 4, 385, 1024 }, { 4, 386, 1024 }, { 5, 387, 1024 }, { 4, 388, 1024 }, { 5, 389, 1024 }, { 5, 390, 1024 }, { 6, 391, 1024 }, { 4, 392, 1024 }, { 5, 393, 1024 }, { 5, 394, 1024 }, { 6, 395, 1024 }, { 5, 396, 1024 }, { 6, 397, 1024 }, { 6, 398, 1024 }, { 7, 399, 1024 }, { 4, 400, 1024 }, { 5, 401, 1024 }, { 5, 402, 1024 }, { 6, 403, 1024 }, { 5, 404, 1024 }, { 6, 405, 1024 }, { 6, 406, 1024 }, { 7, 407, 1024 }, { 5, 408, 1024 }, { 6, 409, 1024 }, { 6, 410, 1024 }, { 7, 411, 1024 }, { 6, 412, 1024 }, { 7, 413, 1024 }, { 7, 414, 1024 }, { 8, 415, 1024 }, { 4, 416, 1024 }, { 5, 417, 1024 }, { 5, 418, 1024 }, { 6, 419, 1024 }, { 5, 420, 1024 }, { 6, 421, 1024 }, { 6, 422, 1024 }, { 7, 423, 1024 }, { 5, 424, 1024 }, { 6, 425, 1024 }, { 6, 426, 1024 }, { 7, 427, 1024 }, { 6, 428, 1024 }, { 7, 429, 1024 }, { 7, 430, 1024 }, { 8, 431, 1024 }, { 5, 432, 1024 }, { 6, 433, 1024 }, { 6, 434, 1024 }, { 7, 435, 1024 }, { 6, 436, 1024 }, { 7, 437, 1024 }, { 7, 438, 1024 }, { 8, 439, 1024 }, { 6, 440, 1024 }, { 7, 441, 1024 }, { 7, 442, 1024 }, { 8, 443, 1024 }, { 7, 444, 1024 }, { 8, 445, 1024 }, { 8, 446, 1024 }, { 9, 447, 1024 }, { 4, 448, 1024 }, { 5, 449, 1024 }, { 5, 450, 1024 }, { 6, 451, 1024 }, { 5, 452, 1024 }, { 6, 453, 1024 }, { 6, 454, 1024 }, { 7, 455, 1024 }, { 5, 456, 1024 }, { 6, 457, 1024 }, { 6, 458, 1024 }, { 7, 459, 1024 }, { 6, 460, 1024 }, { 7, 461, 1024 }, { 7, 462, 1024 }, { 8, 463, 1024 }, { 5, 464, 1024 }, { 6, 465, 1024 }, { 6, 466, 1024 }, { 7, 467, 1024 }, { 6, 468, 1024 }, { 7, 469, 1024 }, { 7, 470, 1024 }, { 8, 471, 1024 }, { 6, 472, 1024 }, { 7, 473, 1024 }, { 7, 474, 1024 }, { 8, 475, 1024 }, { 7, 476, 1024 }, { 8, 477, 1024 }, { 8, 478, 1024 }, { 9, 479, 1024 }, { 5, 480, 1024 }, { 6, 481, 1024 }, { 6, 482, 1024 }, { 7, 483, 1024 }, { 6, 484, 1024 }, { 7, 485, 1024 }, { 7, 486, 1024 }, { 8, 487, 1024 }, { 6, 488, 1024 }, { 7, 489, 1024 }, { 7, 490, 1024 }, { 8, 491, 1024 }, { 7, 492, 1024 }, { 8, 493, 1024 }, { 8, 494, 1024 }, { 9, 495, 1024 }, { 6, 496, 1024 }, { 7, 497, 1024 }, { 7, 498, 1024 }, { 8, 499, 1024 }, { 7, 500, 1024 }, { 8, 501, 1024 }, { 8, 502, 1024 }, { 9, 503, 1024 }, { 7, 504, 1024 }, { 8, 505, 1024 }, { 8, 506, 1024 }, { 9, 507, 1024 }, { 8, 508, 1024 }, { 9, 509, 1024 }, { 9, 510, 1024 }, { 10, 511, 1024 }, { 2, 512, 1024 }, { 3, 513, 1024 }, { 3, 514, 1024 }, { 4, 515, 1024 }, { 3, 516, 1024 }, { 4, 517, 1024 }, { 4, 518, 1024 }, { 5, 519, 1024 }, { 3, 520, 1024 }, { 4, 521, 1024 }, { 4, 522, 1024 }, { 5, 523, 1024 }, { 4, 524, 1024 }, { 5, 525, 1024 }, { 5, 526, 1024 }, { 6, 527, 1024 }, { 3, 528, 1024 }, { 4, 529, 1024 }, { 4, 530, 1024 }, { 5, 531, 1024 }, { 4, 532, 1024 }, { 5, 533, 1024 }, { 5, 534, 1024 }, { 6, 535, 1024 }, { 4, 536, 1024 }, { 5, 537, 1024 }, { 5, 538, 1024 }, { 6, 539, 1024 }, { 5, 540, 1024 }, { 6, 541, 1024 }, { 6, 542, 1024 }, { 7, 543, 1024 }, { 3, 544, 1024 }, { 4, 545, 1024 }, { 4, 546, 1024 }, { 5, 547, 1024 }, { 4, 548, 1024 }, { 5, 549, 1024 }, { 5, 550, 1024 }, { 6, 551, 1024 }, { 4, 552, 1024 }, { 5, 553, 1024 }, { 5, 554, 1024 }, { 6, 555, 1024 }, { 5, 556, 1024 }, { 6, 557, 1024 }, { 6, 558, 1024 }, { 7, 559, 1024 }, { 4, 560, 1024 }, { 5, 561, 1024 }, { 5, 562, 1024 }, { 6, 563, 1024 }, { 5, 564, 1024 }, { 6, 565, 1024 }, { 6, 566, 1024 }, { 7, 567, 1024 }, { 5, 568, 1024 }, { 6, 569, 1024 }, { 6, 570, 1024 }, { 7, 571, 1024 }, { 6, 572, 1024 }, { 7, 573, 1024 }, { 7, 574, 1024 }, { 8, 575, 1024 }, { 3, 576, 1024 }, { 4, 577, 1024 }, { 4, 578, 1024 }, { 5, 579, 1024 }, { 4, 580, 1024 }, { 5, 581, 1024 }, { 5, 582, 1024 }, { 6, 583, 1024 }, { 4, 584, 1024 }, { 5, 585, 1024 }, { 5, 586, 1024 }, { 6, 587, 1024 }, { 5, 588, 1024 }, { 6, 589, 1024 }, { 6, 590, 1024 }, { 7, 591, 1024 }, { 4, 592, 1024 }, { 5, 593, 1024 }, { 5, 594, 1024 }, { 6, 595, 1024 }, { 5, 596, 1024 }, { 6, 597, 1024 }, { 6, 598, 1024 }, { 7, 599, 1024 }, { 5, 600, 1024 }, { 6, 601, 1024 }, { 6, 602, 1024 }, { 7, 603, 1024 }, { 6, 604, 1024 }, { 7, 605, 1024 }, { 7, 606, 1024 }, { 8, 607, 1024 }, { 4, 608, 1024 }, { 5, 609, 1024 }, { 5, 610, 1024 }, { 6, 611, 1024 }, { 5, 612, 1024 }, { 6, 613, 1024 }, { 6, 614, 1024 }, { 7, 615, 1024 }, { 5, 616, 1024 }, { 6, 617, 1024 }, { 6, 618, 1024 }, { 7, 619, 1024 }, { 6, 620, 1024 }, { 7, 621, 1024 }, { 7, 622, 1024 }, { 8, 623, 1024 }, { 5, 624, 1024 }, { 6, 625, 1024 }, { 6, 626, 1024 }, { 7, 627, 1024 }, { 6, 628, 1024 }, { 7, 629, 1024 }, { 7, 630, 1024 }, { 8, 631, 1024 }, { 6, 632, 1024 }, { 7, 633, 1024 }, { 7, 634, 1024 }, { 8, 635, 1024 }, { 7, 636, 1024 }, { 8, 637, 1024 }, { 8, 638, 1024 }, { 9, 639, 1024 }, { 3, 640, 1024 }, { 4, 641, 1024 }, { 4, 642, 1024 }, { 5, 643, 1024 }, { 4, 644, 1024 }, { 5, 645, 1024 }, { 5, 646, 1024 }, { 6, 647, 1024 }, { 4, 648, 1024 }, { 5, 649, 1024 }, { 5, 650, 1024 }, { 6, 651, 1024 }, { 5, 652, 1024 }, { 6, 653, 1024 }, { 6, 654, 1024 }, { 7, 655, 1024 }, { 4, 656, 1024 }, { 5, 657, 1024 }, { 5, 658, 1024 }, { 6, 659, 1024 }, { 5, 660, 1024 }, { 6, 661, 1024 }, { 6, 662, 1024 }, { 7, 663, 1024 }, { 5, 664, 1024 }, { 6, 665, 1024 }, { 6, 666, 1024 }, { 7, 667, 1024 }, { 6, 668, 1024 }, { 7, 669, 1024 }, { 7, 670, 1024 }, { 8, 671, 1024 }, { 4, 672, 1024 }, { 5, 673, 1024 }, { 5, 674, 1024 }, { 6, 675, 1024 }, { 5, 676, 1024 }, { 6, 677, 1024 }, { 6, 678, 1024 }, { 7, 679, 1024 }, { 5, 680, 1024 }, { 6, 681, 1024 }, { 6, 682, 1024 }, { 7, 683, 1024 }, { 6, 684, 1024 }, { 7, 685, 1024 }, { 7, 686, 1024 }, { 8, 687, 1024 }, { 5, 688, 1024 }, { 6, 689, 1024 }, { 6, 690, 1024 }, { 7, 691, 1024 }, { 6, 692, 1024 }, { 7, 693, 1024 }, { 7, 694, 1024 }, { 8, 695, 1024 }, { 6, 696, 1024 }, { 7, 697, 1024 }, { 7, 698, 1024 }, { 8, 699, 1024 }, { 7, 700, 1024 }, { 8, 701, 1024 }, { 8, 702, 1024 }, { 9, 703, 1024 }, { 4, 704, 1024 }, { 5, 705, 1024 }, { 5, 706, 1024 }, { 6, 707, 1024 }, { 5, 708, 1024 }, { 6, 709, 1024 }, { 6, 710, 1024 }, { 7, 711, 1024 }, { 5, 712, 1024 }, { 6, 713, 1024 }, { 6, 714, 1024 }, { 7, 715, 1024 }, { 6, 716, 1024 }, { 7, 717, 1024 }, { 7, 718, 1024 }, { 8, 719, 1024 }, { 5, 720, 1024 }, { 6, 721, 1024 }, { 6, 722, 1024 }, { 7, 723, 1024 }, { 6, 724, 1024 }, { 7, 725, 1024 }, { 7, 726, 1024 }, { 8, 727, 1024 }, { 6, 728, 1024 }, { 7, 729, 1024 }, { 7, 730, 1024 }, { 8, 731, 1024 }, { 7, 732, 1024 }, { 8, 733, 1024 }, { 8, 734, 1024 }, { 9, 735, 1024 }, { 5, 736, 1024 }, { 6, 737, 1024 }, { 6, 738, 1024 }, { 7, 739, 1024 }, { 6, 740, 1024 }, { 7, 741, 1024 }, { 7, 742, 1024 }, { 8, 743, 1024 }, { 6, 744, 1024 }, { 7, 745, 1024 }, { 7, 746, 1024 }, { 8, 747, 1024 }, { 7, 748, 1024 }, { 8, 749, 1024 }, { 8, 750, 1024 }, { 9, 751, 1024 }, { 6, 752, 1024 }, { 7, 753, 1024 }, { 7, 754, 1024 }, { 8, 755, 1024 }, { 7, 756, 1024 }, { 8, 757, 1024 }, { 8, 758, 1024 }, { 9, 759, 1024 }, { 7, 760, 1024 }, { 8, 761, 1024 }, { 8, 762, 1024 }, { 9, 763, 1024 }, { 8, 764, 1024 }, { 9, 765, 1024 }, { 9, 766, 1024 }, { 10, 767, 1024 }, { 3, 768, 1024 }, { 4, 769, 1024 }, { 4, 770, 1024 }, { 5, 771, 1024 }, { 4, 772, 1024 }, { 5, 773, 1024 }, { 5, 774, 1024 }, { 6, 775, 1024 }, { 4, 776, 1024 }, { 5, 777, 1024 }, { 5, 778, 1024 }, { 6, 779, 1024 }, { 5, 780, 1024 }, { 6, 781, 1024 }, { 6, 782, 1024 }, { 7, 783, 1024 }, { 4, 784, 1024 }, { 5, 785, 1024 }, { 5, 786, 1024 }, { 6, 787, 1024 }, { 5, 788, 1024 }, { 6, 789, 1024 }, { 6, 790, 1024 }, { 7, 791, 1024 }, { 5, 792, 1024 }, { 6, 793, 1024 }, { 6, 794, 1024 }, { 7, 795, 1024 }, { 6, 796, 1024 }, { 7, 797, 1024 }, { 7, 798, 1024 }, { 8, 799, 1024 }, { 4, 800, 1024 }, { 5, 801, 1024 }, { 5, 802, 1024 }, { 6, 803, 1024 }, { 5, 804, 1024 }, { 6, 805, 1024 }, { 6, 806, 1024 }, { 7, 807, 1024 }, { 5, 808, 1024 }, { 6, 809, 1024 }, { 6, 810, 1024 }, { 7, 811, 1024 }, { 6, 812, 1024 }, { 7, 813, 1024 }, { 7, 814, 1024 }, { 8, 815, 1024 }, { 5, 816, 1024 }, { 6, 817, 1024 }, { 6, 818, 1024 }, { 7, 819, 1024 }, { 6, 820, 1024 }, { 7, 821, 1024 }, { 7, 822, 1024 }, { 8, 823, 1024 }, { 6, 824, 1024 }, { 7, 825, 1024 }, { 7, 826, 1024 }, { 8, 827, 1024 }, { 7, 828, 1024 }, { 8, 829, 1024 }, { 8, 830, 1024 }, { 9, 831, 1024 }, { 4, 832, 1024 }, { 5, 833, 1024 }, { 5, 834, 1024 }, { 6, 835, 1024 }, { 5, 836, 1024 }, { 6, 837, 1024 }, { 6, 838, 1024 }, { 7, 839, 1024 }, { 5, 840, 1024 }, { 6, 841, 1024 }, { 6, 842, 1024 }, { 7, 843, 1024 }, { 6, 844, 1024 }, { 7, 845, 1024 }, { 7, 846, 1024 }, { 8, 847, 1024 }, { 5, 848, 1024 }, { 6, 849, 1024 }, { 6, 850, 1024 }, { 7, 851, 1024 }, { 6, 852, 1024 }, { 7, 853, 1024 }, { 7, 854, 1024 }, { 8, 855, 1024 }, { 6, 856, 1024 }, { 7, 857, 1024 }, { 7, 858, 1024 }, { 8, 859, 1024 }, { 7, 860, 1024 }, { 8, 861, 1024 }, { 8, 862, 1024 }, { 9, 863, 1024 }, { 5, 864, 1024 }, { 6, 865, 1024 }, { 6, 866, 1024 }, { 7, 867, 1024 }, { 6, 868, 1024 }, { 7, 869, 1024 }, { 7, 870, 1024 }, { 8, 871, 1024 }, { 6, 872, 1024 }, { 7, 873, 1024 }, { 7, 874, 1024 }, { 8, 875, 1024 }, { 7, 876, 1024 }, { 8, 877, 1024 }, { 8, 878, 1024 }, { 9, 879, 1024 }, { 6, 880, 1024 }, { 7, 881, 1024 }, { 7, 882, 1024 }, { 8, 883, 1024 }, { 7, 884, 1024 }, { 8, 885, 1024 }, { 8, 886, 1024 }, { 9, 887, 1024 }, { 7, 888, 1024 }, { 8, 889, 1024 }, { 8, 890, 1024 }, { 9, 891, 1024 }, { 8, 892, 1024 }, { 9, 893, 1024 }, { 9, 894, 1024 }, { 10, 895, 1024 }, { 4, 896, 1024 }, { 5, 897, 1024 }, { 5, 898, 1024 }, { 6, 899, 1024 }, { 5, 900, 1024 }, { 6, 901, 1024 }, { 6, 902, 1024 }, { 7, 903, 1024 }, { 5, 904, 1024 }, { 6, 905, 1024 }, { 6, 906, 1024 }, { 7, 907, 1024 }, { 6, 908, 1024 }, { 7, 909, 1024 }, { 7, 910, 1024 }, { 8, 911, 1024 }, { 5, 912, 1024 }, { 6, 913, 1024 }, { 6, 914, 1024 }, { 7, 915, 1024 }, { 6, 916, 1024 }, { 7, 917, 1024 }, { 7, 918, 1024 }, { 8, 919, 1024 }, { 6, 920, 1024 }, { 7, 921, 1024 }, { 7, 922, 1024 }, { 8, 923, 1024 }, { 7, 924, 1024 }, { 8, 925, 1024 }, { 8, 926, 1024 }, { 9, 927, 1024 }, { 5, 928, 1024 }, { 6, 929, 1024 }, { 6, 930, 1024 }, { 7, 931, 1024 }, { 6, 932, 1024 }, { 7, 933, 1024 }, { 7, 934, 1024 }, { 8, 935, 1024 }, { 6, 936, 1024 }, { 7, 937, 1024 }, { 7, 938, 1024 }, { 8, 939, 1024 }, { 7, 940, 1024 }, { 8, 941, 1024 }, { 8, 942, 1024 }, { 9, 943, 1024 }, { 6, 944, 1024 }, { 7, 945, 1024 }, { 7, 946, 1024 }, { 8, 947, 1024 }, { 7, 948, 1024 }, { 8, 949, 1024 }, { 8, 950, 1024 }, { 9, 951, 1024 }, { 7, 952, 1024 }, { 8, 953, 1024 }, { 8, 954, 1024 }, { 9, 955, 1024 }, { 8, 956, 1024 }, { 9, 957, 1024 }, { 9, 958, 1024 }, { 10, 959, 1024 }, { 5, 960, 1024 }, { 6, 961, 1024 }, { 6, 962, 1024 }, { 7, 963, 1024 }, { 6, 964, 1024 }, { 7, 965, 1024 }, { 7, 966, 1024 }, { 8, 967, 1024 }, { 6, 968, 1024 }, { 7, 969, 1024 }, { 7, 970, 1024 }, { 8, 971, 1024 }, { 7, 972, 1024 }, { 8, 973, 1024 }, { 8, 974, 1024 }, { 9, 975, 1024 }, { 6, 976, 1024 }, { 7, 977, 1024 }, { 7, 978, 1024 }, { 8, 979, 1024 }, { 7, 980, 1024 }, { 8, 981, 1024 }, { 8, 982, 1024 }, { 9, 983, 1024 }, { 7, 984, 1024 }, { 8, 985, 1024 }, { 8, 986, 1024 }, { 9, 987, 1024 }, { 8, 988, 1024 }, { 9, 989, 1024 }, { 9, 990, 1024 }, { 10, 991, 1024 }, { 6, 992, 1024 }, { 7, 993, 1024 }, { 7, 994, 1024 }, { 8, 995, 1024 }, { 7, 996, 1024 }, { 8, 997, 1024 }, { 8, 998, 1024 }, { 9, 999, 1024 }, { 7, 1000, 1024 }, { 8, 1001, 1024 }, { 8, 1002, 1024 }, { 9, 1003, 1024 }, { 8, 1004, 1024 }, { 9, 1005, 1024 }, { 9, 1006, 1024 }, { 10, 1007, 1024 }, { 7, 1008, 1024 }, { 8, 1009, 1024 }, { 8, 1010, 1024 }, { 9, 1011, 1024 }, { 8, 1012, 1024 }, { 9, 1013, 1024 }, { 9, 1014, 1024 }, { 10, 1015, 1024 }, { 8, 1016, 1024 }, { 9, 1017, 1024 }, { 9, 1018, 1024 }, { 10, 1019, 1024 }, { 9, 1020, 1024 }, { 10, 1021, 1024 }, { 10, 1022, 1024 }, { 11, 1023, 1024 }, #if FP_LUT > 11 { 1, 0, 0 }, { 2, 1, 2048 }, { 2, 2, 2048 }, { 3, 3, 2048 }, { 2, 4, 2048 }, { 3, 5, 2048 }, { 3, 6, 2048 }, { 4, 7, 2048 }, { 2, 8, 2048 }, { 3, 9, 2048 }, { 3, 10, 2048 }, { 4, 11, 2048 }, { 3, 12, 2048 }, { 4, 13, 2048 }, { 4, 14, 2048 }, { 5, 15, 2048 }, { 2, 16, 2048 }, { 3, 17, 2048 }, { 3, 18, 2048 }, { 4, 19, 2048 }, { 3, 20, 2048 }, { 4, 21, 2048 }, { 4, 22, 2048 }, { 5, 23, 2048 }, { 3, 24, 2048 }, { 4, 25, 2048 }, { 4, 26, 2048 }, { 5, 27, 2048 }, { 4, 28, 2048 }, { 5, 29, 2048 }, { 5, 30, 2048 }, { 6, 31, 2048 }, { 2, 32, 2048 }, { 3, 33, 2048 }, { 3, 34, 2048 }, { 4, 35, 2048 }, { 3, 36, 2048 }, { 4, 37, 2048 }, { 4, 38, 2048 }, { 5, 39, 2048 }, { 3, 40, 2048 }, { 4, 41, 2048 }, { 4, 42, 2048 }, { 5, 43, 2048 }, { 4, 44, 2048 }, { 5, 45, 2048 }, { 5, 46, 2048 }, { 6, 47, 2048 }, { 3, 48, 2048 }, { 4, 49, 2048 }, { 4, 50, 2048 }, { 5, 51, 2048 }, { 4, 52, 2048 }, { 5, 53, 2048 }, { 5, 54, 2048 }, { 6, 55, 2048 }, { 4, 56, 2048 }, { 5, 57, 2048 }, { 5, 58, 2048 }, { 6, 59, 2048 }, { 5, 60, 2048 }, { 6, 61, 2048 }, { 6, 62, 2048 }, { 7, 63, 2048 }, { 2, 64, 2048 }, { 3, 65, 2048 }, { 3, 66, 2048 }, { 4, 67, 2048 }, { 3, 68, 2048 }, { 4, 69, 2048 }, { 4, 70, 2048 }, { 5, 71, 2048 }, { 3, 72, 2048 }, { 4, 73, 2048 }, { 4, 74, 2048 }, { 5, 75, 2048 }, { 4, 76, 2048 }, { 5, 77, 2048 }, { 5, 78, 2048 }, { 6, 79, 2048 }, { 3, 80, 2048 }, { 4, 81, 2048 }, { 4, 82, 2048 }, { 5, 83, 2048 }, { 4, 84, 2048 }, { 5, 85, 2048 }, { 5, 86, 2048 }, { 6, 87, 2048 }, { 4, 88, 2048 }, { 5, 89, 2048 }, { 5, 90, 2048 }, { 6, 91, 2048 }, { 5, 92, 2048 }, { 6, 93, 2048 }, { 6, 94, 2048 }, { 7, 95, 2048 }, { 3, 96, 2048 }, { 4, 97, 2048 }, { 4, 98, 2048 }, { 5, 99, 2048 }, { 4, 100, 2048 }, { 5, 101, 2048 }, { 5, 102, 2048 }, { 6, 103, 2048 }, { 4, 104, 2048 }, { 5, 105, 2048 }, { 5, 106, 2048 }, { 6, 107, 2048 }, { 5, 108, 2048 }, { 6, 109, 2048 }, { 6, 110, 2048 }, { 7, 111, 2048 }, { 4, 112, 2048 }, { 5, 113, 2048 }, { 5, 114, 2048 }, { 6, 115, 2048 }, { 5, 116, 2048 }, { 6, 117, 2048 }, { 6, 118, 2048 }, { 7, 119, 2048 }, { 5, 120, 2048 }, { 6, 121, 2048 }, { 6, 122, 2048 }, { 7, 123, 2048 }, { 6, 124, 2048 }, { 7, 125, 2048 }, { 7, 126, 2048 }, { 8, 127, 2048 }, { 2, 128, 2048 }, { 3, 129, 2048 }, { 3, 130, 2048 }, { 4, 131, 2048 }, { 3, 132, 2048 }, { 4, 133, 2048 }, { 4, 134, 2048 }, { 5, 135, 2048 }, { 3, 136, 2048 }, { 4, 137, 2048 }, { 4, 138, 2048 }, { 5, 139, 2048 }, { 4, 140, 2048 }, { 5, 141, 2048 }, { 5, 142, 2048 }, { 6, 143, 2048 }, { 3, 144, 2048 }, { 4, 145, 2048 }, { 4, 146, 2048 }, { 5, 147, 2048 }, { 4, 148, 2048 }, { 5, 149, 2048 }, { 5, 150, 2048 }, { 6, 151, 2048 }, { 4, 152, 2048 }, { 5, 153, 2048 }, { 5, 154, 2048 }, { 6, 155, 2048 }, { 5, 156, 2048 }, { 6, 157, 2048 }, { 6, 158, 2048 }, { 7, 159, 2048 }, { 3, 160, 2048 }, { 4, 161, 2048 }, { 4, 162, 2048 }, { 5, 163, 2048 }, { 4, 164, 2048 }, { 5, 165, 2048 }, { 5, 166, 2048 }, { 6, 167, 2048 }, { 4, 168, 2048 }, { 5, 169, 2048 }, { 5, 170, 2048 }, { 6, 171, 2048 }, { 5, 172, 2048 }, { 6, 173, 2048 }, { 6, 174, 2048 }, { 7, 175, 2048 }, { 4, 176, 2048 }, { 5, 177, 2048 }, { 5, 178, 2048 }, { 6, 179, 2048 }, { 5, 180, 2048 }, { 6, 181, 2048 }, { 6, 182, 2048 }, { 7, 183, 2048 }, { 5, 184, 2048 }, { 6, 185, 2048 }, { 6, 186, 2048 }, { 7, 187, 2048 }, { 6, 188, 2048 }, { 7, 189, 2048 }, { 7, 190, 2048 }, { 8, 191, 2048 }, { 3, 192, 2048 }, { 4, 193, 2048 }, { 4, 194, 2048 }, { 5, 195, 2048 }, { 4, 196, 2048 }, { 5, 197, 2048 }, { 5, 198, 2048 }, { 6, 199, 2048 }, { 4, 200, 2048 }, { 5, 201, 2048 }, { 5, 202, 2048 }, { 6, 203, 2048 }, { 5, 204, 2048 }, { 6, 205, 2048 }, { 6, 206, 2048 }, { 7, 207, 2048 }, { 4, 208, 2048 }, { 5, 209, 2048 }, { 5, 210, 2048 }, { 6, 211, 2048 }, { 5, 212, 2048 }, { 6, 213, 2048 }, { 6, 214, 2048 }, { 7, 215, 2048 }, { 5, 216, 2048 }, { 6, 217, 2048 }, { 6, 218, 2048 }, { 7, 219, 2048 }, { 6, 220, 2048 }, { 7, 221, 2048 }, { 7, 222, 2048 }, { 8, 223, 2048 }, { 4, 224, 2048 }, { 5, 225, 2048 }, { 5, 226, 2048 }, { 6, 227, 2048 }, { 5, 228, 2048 }, { 6, 229, 2048 }, { 6, 230, 2048 }, { 7, 231, 2048 }, { 5, 232, 2048 }, { 6, 233, 2048 }, { 6, 234, 2048 }, { 7, 235, 2048 }, { 6, 236, 2048 }, { 7, 237, 2048 }, { 7, 238, 2048 }, { 8, 239, 2048 }, { 5, 240, 2048 }, { 6, 241, 2048 }, { 6, 242, 2048 }, { 7, 243, 2048 }, { 6, 244, 2048 }, { 7, 245, 2048 }, { 7, 246, 2048 }, { 8, 247, 2048 }, { 6, 248, 2048 }, { 7, 249, 2048 }, { 7, 250, 2048 }, { 8, 251, 2048 }, { 7, 252, 2048 }, { 8, 253, 2048 }, { 8, 254, 2048 }, { 9, 255, 2048 }, { 2, 256, 2048 }, { 3, 257, 2048 }, { 3, 258, 2048 }, { 4, 259, 2048 }, { 3, 260, 2048 }, { 4, 261, 2048 }, { 4, 262, 2048 }, { 5, 263, 2048 }, { 3, 264, 2048 }, { 4, 265, 2048 }, { 4, 266, 2048 }, { 5, 267, 2048 }, { 4, 268, 2048 }, { 5, 269, 2048 }, { 5, 270, 2048 }, { 6, 271, 2048 }, { 3, 272, 2048 }, { 4, 273, 2048 }, { 4, 274, 2048 }, { 5, 275, 2048 }, { 4, 276, 2048 }, { 5, 277, 2048 }, { 5, 278, 2048 }, { 6, 279, 2048 }, { 4, 280, 2048 }, { 5, 281, 2048 }, { 5, 282, 2048 }, { 6, 283, 2048 }, { 5, 284, 2048 }, { 6, 285, 2048 }, { 6, 286, 2048 }, { 7, 287, 2048 }, { 3, 288, 2048 }, { 4, 289, 2048 }, { 4, 290, 2048 }, { 5, 291, 2048 }, { 4, 292, 2048 }, { 5, 293, 2048 }, { 5, 294, 2048 }, { 6, 295, 2048 }, { 4, 296, 2048 }, { 5, 297, 2048 }, { 5, 298, 2048 }, { 6, 299, 2048 }, { 5, 300, 2048 }, { 6, 301, 2048 }, { 6, 302, 2048 }, { 7, 303, 2048 }, { 4, 304, 2048 }, { 5, 305, 2048 }, { 5, 306, 2048 }, { 6, 307, 2048 }, { 5, 308, 2048 }, { 6, 309, 2048 }, { 6, 310, 2048 }, { 7, 311, 2048 }, { 5, 312, 2048 }, { 6, 313, 2048 }, { 6, 314, 2048 }, { 7, 315, 2048 }, { 6, 316, 2048 }, { 7, 317, 2048 }, { 7, 318, 2048 }, { 8, 319, 2048 }, { 3, 320, 2048 }, { 4, 321, 2048 }, { 4, 322, 2048 }, { 5, 323, 2048 }, { 4, 324, 2048 }, { 5, 325, 2048 }, { 5, 326, 2048 }, { 6, 327, 2048 }, { 4, 328, 2048 }, { 5, 329, 2048 }, { 5, 330, 2048 }, { 6, 331, 2048 }, { 5, 332, 2048 }, { 6, 333, 2048 }, { 6, 334, 2048 }, { 7, 335, 2048 }, { 4, 336, 2048 }, { 5, 337, 2048 }, { 5, 338, 2048 }, { 6, 339, 2048 }, { 5, 340, 2048 }, { 6, 341, 2048 }, { 6, 342, 2048 }, { 7, 343, 2048 }, { 5, 344, 2048 }, { 6, 345, 2048 }, { 6, 346, 2048 }, { 7, 347, 2048 }, { 6, 348, 2048 }, { 7, 349, 2048 }, { 7, 350, 2048 }, { 8, 351, 2048 }, { 4, 352, 2048 }, { 5, 353, 2048 }, { 5, 354, 2048 }, { 6, 355, 2048 }, { 5, 356, 2048 }, { 6, 357, 2048 }, { 6, 358, 2048 }, { 7, 359, 2048 }, { 5, 360, 2048 }, { 6, 361, 2048 }, { 6, 362, 2048 }, { 7, 363, 2048 }, { 6, 364, 2048 }, { 7, 365, 2048 }, { 7, 366, 2048 }, { 8, 367, 2048 }, { 5, 368, 2048 }, { 6, 369, 2048 }, { 6, 370, 2048 }, { 7, 371, 2048 }, { 6, 372, 2048 }, { 7, 373, 2048 }, { 7, 374, 2048 }, { 8, 375, 2048 }, { 6, 376, 2048 }, { 7, 377, 2048 }, { 7, 378, 2048 }, { 8, 379, 2048 }, { 7, 380, 2048 }, { 8, 381, 2048 }, { 8, 382, 2048 }, { 9, 383, 2048 }, { 3, 384, 2048 }, { 4, 385, 2048 }, { 4, 386, 2048 }, { 5, 387, 2048 }, { 4, 388, 2048 }, { 5, 389, 2048 }, { 5, 390, 2048 }, { 6, 391, 2048 }, { 4, 392, 2048 }, { 5, 393, 2048 }, { 5, 394, 2048 }, { 6, 395, 2048 }, { 5, 396, 2048 }, { 6, 397, 2048 }, { 6, 398, 2048 }, { 7, 399, 2048 }, { 4, 400, 2048 }, { 5, 401, 2048 }, { 5, 402, 2048 }, { 6, 403, 2048 }, { 5, 404, 2048 }, { 6, 405, 2048 }, { 6, 406, 2048 }, { 7, 407, 2048 }, { 5, 408, 2048 }, { 6, 409, 2048 }, { 6, 410, 2048 }, { 7, 411, 2048 }, { 6, 412, 2048 }, { 7, 413, 2048 }, { 7, 414, 2048 }, { 8, 415, 2048 }, { 4, 416, 2048 }, { 5, 417, 2048 }, { 5, 418, 2048 }, { 6, 419, 2048 }, { 5, 420, 2048 }, { 6, 421, 2048 }, { 6, 422, 2048 }, { 7, 423, 2048 }, { 5, 424, 2048 }, { 6, 425, 2048 }, { 6, 426, 2048 }, { 7, 427, 2048 }, { 6, 428, 2048 }, { 7, 429, 2048 }, { 7, 430, 2048 }, { 8, 431, 2048 }, { 5, 432, 2048 }, { 6, 433, 2048 }, { 6, 434, 2048 }, { 7, 435, 2048 }, { 6, 436, 2048 }, { 7, 437, 2048 }, { 7, 438, 2048 }, { 8, 439, 2048 }, { 6, 440, 2048 }, { 7, 441, 2048 }, { 7, 442, 2048 }, { 8, 443, 2048 }, { 7, 444, 2048 }, { 8, 445, 2048 }, { 8, 446, 2048 }, { 9, 447, 2048 }, { 4, 448, 2048 }, { 5, 449, 2048 }, { 5, 450, 2048 }, { 6, 451, 2048 }, { 5, 452, 2048 }, { 6, 453, 2048 }, { 6, 454, 2048 }, { 7, 455, 2048 }, { 5, 456, 2048 }, { 6, 457, 2048 }, { 6, 458, 2048 }, { 7, 459, 2048 }, { 6, 460, 2048 }, { 7, 461, 2048 }, { 7, 462, 2048 }, { 8, 463, 2048 }, { 5, 464, 2048 }, { 6, 465, 2048 }, { 6, 466, 2048 }, { 7, 467, 2048 }, { 6, 468, 2048 }, { 7, 469, 2048 }, { 7, 470, 2048 }, { 8, 471, 2048 }, { 6, 472, 2048 }, { 7, 473, 2048 }, { 7, 474, 2048 }, { 8, 475, 2048 }, { 7, 476, 2048 }, { 8, 477, 2048 }, { 8, 478, 2048 }, { 9, 479, 2048 }, { 5, 480, 2048 }, { 6, 481, 2048 }, { 6, 482, 2048 }, { 7, 483, 2048 }, { 6, 484, 2048 }, { 7, 485, 2048 }, { 7, 486, 2048 }, { 8, 487, 2048 }, { 6, 488, 2048 }, { 7, 489, 2048 }, { 7, 490, 2048 }, { 8, 491, 2048 }, { 7, 492, 2048 }, { 8, 493, 2048 }, { 8, 494, 2048 }, { 9, 495, 2048 }, { 6, 496, 2048 }, { 7, 497, 2048 }, { 7, 498, 2048 }, { 8, 499, 2048 }, { 7, 500, 2048 }, { 8, 501, 2048 }, { 8, 502, 2048 }, { 9, 503, 2048 }, { 7, 504, 2048 }, { 8, 505, 2048 }, { 8, 506, 2048 }, { 9, 507, 2048 }, { 8, 508, 2048 }, { 9, 509, 2048 }, { 9, 510, 2048 }, { 10, 511, 2048 }, { 2, 512, 2048 }, { 3, 513, 2048 }, { 3, 514, 2048 }, { 4, 515, 2048 }, { 3, 516, 2048 }, { 4, 517, 2048 }, { 4, 518, 2048 }, { 5, 519, 2048 }, { 3, 520, 2048 }, { 4, 521, 2048 }, { 4, 522, 2048 }, { 5, 523, 2048 }, { 4, 524, 2048 }, { 5, 525, 2048 }, { 5, 526, 2048 }, { 6, 527, 2048 }, { 3, 528, 2048 }, { 4, 529, 2048 }, { 4, 530, 2048 }, { 5, 531, 2048 }, { 4, 532, 2048 }, { 5, 533, 2048 }, { 5, 534, 2048 }, { 6, 535, 2048 }, { 4, 536, 2048 }, { 5, 537, 2048 }, { 5, 538, 2048 }, { 6, 539, 2048 }, { 5, 540, 2048 }, { 6, 541, 2048 }, { 6, 542, 2048 }, { 7, 543, 2048 }, { 3, 544, 2048 }, { 4, 545, 2048 }, { 4, 546, 2048 }, { 5, 547, 2048 }, { 4, 548, 2048 }, { 5, 549, 2048 }, { 5, 550, 2048 }, { 6, 551, 2048 }, { 4, 552, 2048 }, { 5, 553, 2048 }, { 5, 554, 2048 }, { 6, 555, 2048 }, { 5, 556, 2048 }, { 6, 557, 2048 }, { 6, 558, 2048 }, { 7, 559, 2048 }, { 4, 560, 2048 }, { 5, 561, 2048 }, { 5, 562, 2048 }, { 6, 563, 2048 }, { 5, 564, 2048 }, { 6, 565, 2048 }, { 6, 566, 2048 }, { 7, 567, 2048 }, { 5, 568, 2048 }, { 6, 569, 2048 }, { 6, 570, 2048 }, { 7, 571, 2048 }, { 6, 572, 2048 }, { 7, 573, 2048 }, { 7, 574, 2048 }, { 8, 575, 2048 }, { 3, 576, 2048 }, { 4, 577, 2048 }, { 4, 578, 2048 }, { 5, 579, 2048 }, { 4, 580, 2048 }, { 5, 581, 2048 }, { 5, 582, 2048 }, { 6, 583, 2048 }, { 4, 584, 2048 }, { 5, 585, 2048 }, { 5, 586, 2048 }, { 6, 587, 2048 }, { 5, 588, 2048 }, { 6, 589, 2048 }, { 6, 590, 2048 }, { 7, 591, 2048 }, { 4, 592, 2048 }, { 5, 593, 2048 }, { 5, 594, 2048 }, { 6, 595, 2048 }, { 5, 596, 2048 }, { 6, 597, 2048 }, { 6, 598, 2048 }, { 7, 599, 2048 }, { 5, 600, 2048 }, { 6, 601, 2048 }, { 6, 602, 2048 }, { 7, 603, 2048 }, { 6, 604, 2048 }, { 7, 605, 2048 }, { 7, 606, 2048 }, { 8, 607, 2048 }, { 4, 608, 2048 }, { 5, 609, 2048 }, { 5, 610, 2048 }, { 6, 611, 2048 }, { 5, 612, 2048 }, { 6, 613, 2048 }, { 6, 614, 2048 }, { 7, 615, 2048 }, { 5, 616, 2048 }, { 6, 617, 2048 }, { 6, 618, 2048 }, { 7, 619, 2048 }, { 6, 620, 2048 }, { 7, 621, 2048 }, { 7, 622, 2048 }, { 8, 623, 2048 }, { 5, 624, 2048 }, { 6, 625, 2048 }, { 6, 626, 2048 }, { 7, 627, 2048 }, { 6, 628, 2048 }, { 7, 629, 2048 }, { 7, 630, 2048 }, { 8, 631, 2048 }, { 6, 632, 2048 }, { 7, 633, 2048 }, { 7, 634, 2048 }, { 8, 635, 2048 }, { 7, 636, 2048 }, { 8, 637, 2048 }, { 8, 638, 2048 }, { 9, 639, 2048 }, { 3, 640, 2048 }, { 4, 641, 2048 }, { 4, 642, 2048 }, { 5, 643, 2048 }, { 4, 644, 2048 }, { 5, 645, 2048 }, { 5, 646, 2048 }, { 6, 647, 2048 }, { 4, 648, 2048 }, { 5, 649, 2048 }, { 5, 650, 2048 }, { 6, 651, 2048 }, { 5, 652, 2048 }, { 6, 653, 2048 }, { 6, 654, 2048 }, { 7, 655, 2048 }, { 4, 656, 2048 }, { 5, 657, 2048 }, { 5, 658, 2048 }, { 6, 659, 2048 }, { 5, 660, 2048 }, { 6, 661, 2048 }, { 6, 662, 2048 }, { 7, 663, 2048 }, { 5, 664, 2048 }, { 6, 665, 2048 }, { 6, 666, 2048 }, { 7, 667, 2048 }, { 6, 668, 2048 }, { 7, 669, 2048 }, { 7, 670, 2048 }, { 8, 671, 2048 }, { 4, 672, 2048 }, { 5, 673, 2048 }, { 5, 674, 2048 }, { 6, 675, 2048 }, { 5, 676, 2048 }, { 6, 677, 2048 }, { 6, 678, 2048 }, { 7, 679, 2048 }, { 5, 680, 2048 }, { 6, 681, 2048 }, { 6, 682, 2048 }, { 7, 683, 2048 }, { 6, 684, 2048 }, { 7, 685, 2048 }, { 7, 686, 2048 }, { 8, 687, 2048 }, { 5, 688, 2048 }, { 6, 689, 2048 }, { 6, 690, 2048 }, { 7, 691, 2048 }, { 6, 692, 2048 }, { 7, 693, 2048 }, { 7, 694, 2048 }, { 8, 695, 2048 }, { 6, 696, 2048 }, { 7, 697, 2048 }, { 7, 698, 2048 }, { 8, 699, 2048 }, { 7, 700, 2048 }, { 8, 701, 2048 }, { 8, 702, 2048 }, { 9, 703, 2048 }, { 4, 704, 2048 }, { 5, 705, 2048 }, { 5, 706, 2048 }, { 6, 707, 2048 }, { 5, 708, 2048 }, { 6, 709, 2048 }, { 6, 710, 2048 }, { 7, 711, 2048 }, { 5, 712, 2048 }, { 6, 713, 2048 }, { 6, 714, 2048 }, { 7, 715, 2048 }, { 6, 716, 2048 }, { 7, 717, 2048 }, { 7, 718, 2048 }, { 8, 719, 2048 }, { 5, 720, 2048 }, { 6, 721, 2048 }, { 6, 722, 2048 }, { 7, 723, 2048 }, { 6, 724, 2048 }, { 7, 725, 2048 }, { 7, 726, 2048 }, { 8, 727, 2048 }, { 6, 728, 2048 }, { 7, 729, 2048 }, { 7, 730, 2048 }, { 8, 731, 2048 }, { 7, 732, 2048 }, { 8, 733, 2048 }, { 8, 734, 2048 }, { 9, 735, 2048 }, { 5, 736, 2048 }, { 6, 737, 2048 }, { 6, 738, 2048 }, { 7, 739, 2048 }, { 6, 740, 2048 }, { 7, 741, 2048 }, { 7, 742, 2048 }, { 8, 743, 2048 }, { 6, 744, 2048 }, { 7, 745, 2048 }, { 7, 746, 2048 }, { 8, 747, 2048 }, { 7, 748, 2048 }, { 8, 749, 2048 }, { 8, 750, 2048 }, { 9, 751, 2048 }, { 6, 752, 2048 }, { 7, 753, 2048 }, { 7, 754, 2048 }, { 8, 755, 2048 }, { 7, 756, 2048 }, { 8, 757, 2048 }, { 8, 758, 2048 }, { 9, 759, 2048 }, { 7, 760, 2048 }, { 8, 761, 2048 }, { 8, 762, 2048 }, { 9, 763, 2048 }, { 8, 764, 2048 }, { 9, 765, 2048 }, { 9, 766, 2048 }, { 10, 767, 2048 }, { 3, 768, 2048 }, { 4, 769, 2048 }, { 4, 770, 2048 }, { 5, 771, 2048 }, { 4, 772, 2048 }, { 5, 773, 2048 }, { 5, 774, 2048 }, { 6, 775, 2048 }, { 4, 776, 2048 }, { 5, 777, 2048 }, { 5, 778, 2048 }, { 6, 779, 2048 }, { 5, 780, 2048 }, { 6, 781, 2048 }, { 6, 782, 2048 }, { 7, 783, 2048 }, { 4, 784, 2048 }, { 5, 785, 2048 }, { 5, 786, 2048 }, { 6, 787, 2048 }, { 5, 788, 2048 }, { 6, 789, 2048 }, { 6, 790, 2048 }, { 7, 791, 2048 }, { 5, 792, 2048 }, { 6, 793, 2048 }, { 6, 794, 2048 }, { 7, 795, 2048 }, { 6, 796, 2048 }, { 7, 797, 2048 }, { 7, 798, 2048 }, { 8, 799, 2048 }, { 4, 800, 2048 }, { 5, 801, 2048 }, { 5, 802, 2048 }, { 6, 803, 2048 }, { 5, 804, 2048 }, { 6, 805, 2048 }, { 6, 806, 2048 }, { 7, 807, 2048 }, { 5, 808, 2048 }, { 6, 809, 2048 }, { 6, 810, 2048 }, { 7, 811, 2048 }, { 6, 812, 2048 }, { 7, 813, 2048 }, { 7, 814, 2048 }, { 8, 815, 2048 }, { 5, 816, 2048 }, { 6, 817, 2048 }, { 6, 818, 2048 }, { 7, 819, 2048 }, { 6, 820, 2048 }, { 7, 821, 2048 }, { 7, 822, 2048 }, { 8, 823, 2048 }, { 6, 824, 2048 }, { 7, 825, 2048 }, { 7, 826, 2048 }, { 8, 827, 2048 }, { 7, 828, 2048 }, { 8, 829, 2048 }, { 8, 830, 2048 }, { 9, 831, 2048 }, { 4, 832, 2048 }, { 5, 833, 2048 }, { 5, 834, 2048 }, { 6, 835, 2048 }, { 5, 836, 2048 }, { 6, 837, 2048 }, { 6, 838, 2048 }, { 7, 839, 2048 }, { 5, 840, 2048 }, { 6, 841, 2048 }, { 6, 842, 2048 }, { 7, 843, 2048 }, { 6, 844, 2048 }, { 7, 845, 2048 }, { 7, 846, 2048 }, { 8, 847, 2048 }, { 5, 848, 2048 }, { 6, 849, 2048 }, { 6, 850, 2048 }, { 7, 851, 2048 }, { 6, 852, 2048 }, { 7, 853, 2048 }, { 7, 854, 2048 }, { 8, 855, 2048 }, { 6, 856, 2048 }, { 7, 857, 2048 }, { 7, 858, 2048 }, { 8, 859, 2048 }, { 7, 860, 2048 }, { 8, 861, 2048 }, { 8, 862, 2048 }, { 9, 863, 2048 }, { 5, 864, 2048 }, { 6, 865, 2048 }, { 6, 866, 2048 }, { 7, 867, 2048 }, { 6, 868, 2048 }, { 7, 869, 2048 }, { 7, 870, 2048 }, { 8, 871, 2048 }, { 6, 872, 2048 }, { 7, 873, 2048 }, { 7, 874, 2048 }, { 8, 875, 2048 }, { 7, 876, 2048 }, { 8, 877, 2048 }, { 8, 878, 2048 }, { 9, 879, 2048 }, { 6, 880, 2048 }, { 7, 881, 2048 }, { 7, 882, 2048 }, { 8, 883, 2048 }, { 7, 884, 2048 }, { 8, 885, 2048 }, { 8, 886, 2048 }, { 9, 887, 2048 }, { 7, 888, 2048 }, { 8, 889, 2048 }, { 8, 890, 2048 }, { 9, 891, 2048 }, { 8, 892, 2048 }, { 9, 893, 2048 }, { 9, 894, 2048 }, { 10, 895, 2048 }, { 4, 896, 2048 }, { 5, 897, 2048 }, { 5, 898, 2048 }, { 6, 899, 2048 }, { 5, 900, 2048 }, { 6, 901, 2048 }, { 6, 902, 2048 }, { 7, 903, 2048 }, { 5, 904, 2048 }, { 6, 905, 2048 }, { 6, 906, 2048 }, { 7, 907, 2048 }, { 6, 908, 2048 }, { 7, 909, 2048 }, { 7, 910, 2048 }, { 8, 911, 2048 }, { 5, 912, 2048 }, { 6, 913, 2048 }, { 6, 914, 2048 }, { 7, 915, 2048 }, { 6, 916, 2048 }, { 7, 917, 2048 }, { 7, 918, 2048 }, { 8, 919, 2048 }, { 6, 920, 2048 }, { 7, 921, 2048 }, { 7, 922, 2048 }, { 8, 923, 2048 }, { 7, 924, 2048 }, { 8, 925, 2048 }, { 8, 926, 2048 }, { 9, 927, 2048 }, { 5, 928, 2048 }, { 6, 929, 2048 }, { 6, 930, 2048 }, { 7, 931, 2048 }, { 6, 932, 2048 }, { 7, 933, 2048 }, { 7, 934, 2048 }, { 8, 935, 2048 }, { 6, 936, 2048 }, { 7, 937, 2048 }, { 7, 938, 2048 }, { 8, 939, 2048 }, { 7, 940, 2048 }, { 8, 941, 2048 }, { 8, 942, 2048 }, { 9, 943, 2048 }, { 6, 944, 2048 }, { 7, 945, 2048 }, { 7, 946, 2048 }, { 8, 947, 2048 }, { 7, 948, 2048 }, { 8, 949, 2048 }, { 8, 950, 2048 }, { 9, 951, 2048 }, { 7, 952, 2048 }, { 8, 953, 2048 }, { 8, 954, 2048 }, { 9, 955, 2048 }, { 8, 956, 2048 }, { 9, 957, 2048 }, { 9, 958, 2048 }, { 10, 959, 2048 }, { 5, 960, 2048 }, { 6, 961, 2048 }, { 6, 962, 2048 }, { 7, 963, 2048 }, { 6, 964, 2048 }, { 7, 965, 2048 }, { 7, 966, 2048 }, { 8, 967, 2048 }, { 6, 968, 2048 }, { 7, 969, 2048 }, { 7, 970, 2048 }, { 8, 971, 2048 }, { 7, 972, 2048 }, { 8, 973, 2048 }, { 8, 974, 2048 }, { 9, 975, 2048 }, { 6, 976, 2048 }, { 7, 977, 2048 }, { 7, 978, 2048 }, { 8, 979, 2048 }, { 7, 980, 2048 }, { 8, 981, 2048 }, { 8, 982, 2048 }, { 9, 983, 2048 }, { 7, 984, 2048 }, { 8, 985, 2048 }, { 8, 986, 2048 }, { 9, 987, 2048 }, { 8, 988, 2048 }, { 9, 989, 2048 }, { 9, 990, 2048 }, { 10, 991, 2048 }, { 6, 992, 2048 }, { 7, 993, 2048 }, { 7, 994, 2048 }, { 8, 995, 2048 }, { 7, 996, 2048 }, { 8, 997, 2048 }, { 8, 998, 2048 }, { 9, 999, 2048 }, { 7, 1000, 2048 }, { 8, 1001, 2048 }, { 8, 1002, 2048 }, { 9, 1003, 2048 }, { 8, 1004, 2048 }, { 9, 1005, 2048 }, { 9, 1006, 2048 }, { 10, 1007, 2048 }, { 7, 1008, 2048 }, { 8, 1009, 2048 }, { 8, 1010, 2048 }, { 9, 1011, 2048 }, { 8, 1012, 2048 }, { 9, 1013, 2048 }, { 9, 1014, 2048 }, { 10, 1015, 2048 }, { 8, 1016, 2048 }, { 9, 1017, 2048 }, { 9, 1018, 2048 }, { 10, 1019, 2048 }, { 9, 1020, 2048 }, { 10, 1021, 2048 }, { 10, 1022, 2048 }, { 11, 1023, 2048 }, { 2, 1024, 2048 }, { 3, 1025, 2048 }, { 3, 1026, 2048 }, { 4, 1027, 2048 }, { 3, 1028, 2048 }, { 4, 1029, 2048 }, { 4, 1030, 2048 }, { 5, 1031, 2048 }, { 3, 1032, 2048 }, { 4, 1033, 2048 }, { 4, 1034, 2048 }, { 5, 1035, 2048 }, { 4, 1036, 2048 }, { 5, 1037, 2048 }, { 5, 1038, 2048 }, { 6, 1039, 2048 }, { 3, 1040, 2048 }, { 4, 1041, 2048 }, { 4, 1042, 2048 }, { 5, 1043, 2048 }, { 4, 1044, 2048 }, { 5, 1045, 2048 }, { 5, 1046, 2048 }, { 6, 1047, 2048 }, { 4, 1048, 2048 }, { 5, 1049, 2048 }, { 5, 1050, 2048 }, { 6, 1051, 2048 }, { 5, 1052, 2048 }, { 6, 1053, 2048 }, { 6, 1054, 2048 }, { 7, 1055, 2048 }, { 3, 1056, 2048 }, { 4, 1057, 2048 }, { 4, 1058, 2048 }, { 5, 1059, 2048 }, { 4, 1060, 2048 }, { 5, 1061, 2048 }, { 5, 1062, 2048 }, { 6, 1063, 2048 }, { 4, 1064, 2048 }, { 5, 1065, 2048 }, { 5, 1066, 2048 }, { 6, 1067, 2048 }, { 5, 1068, 2048 }, { 6, 1069, 2048 }, { 6, 1070, 2048 }, { 7, 1071, 2048 }, { 4, 1072, 2048 }, { 5, 1073, 2048 }, { 5, 1074, 2048 }, { 6, 1075, 2048 }, { 5, 1076, 2048 }, { 6, 1077, 2048 }, { 6, 1078, 2048 }, { 7, 1079, 2048 }, { 5, 1080, 2048 }, { 6, 1081, 2048 }, { 6, 1082, 2048 }, { 7, 1083, 2048 }, { 6, 1084, 2048 }, { 7, 1085, 2048 }, { 7, 1086, 2048 }, { 8, 1087, 2048 }, { 3, 1088, 2048 }, { 4, 1089, 2048 }, { 4, 1090, 2048 }, { 5, 1091, 2048 }, { 4, 1092, 2048 }, { 5, 1093, 2048 }, { 5, 1094, 2048 }, { 6, 1095, 2048 }, { 4, 1096, 2048 }, { 5, 1097, 2048 }, { 5, 1098, 2048 }, { 6, 1099, 2048 }, { 5, 1100, 2048 }, { 6, 1101, 2048 }, { 6, 1102, 2048 }, { 7, 1103, 2048 }, { 4, 1104, 2048 }, { 5, 1105, 2048 }, { 5, 1106, 2048 }, { 6, 1107, 2048 }, { 5, 1108, 2048 }, { 6, 1109, 2048 }, { 6, 1110, 2048 }, { 7, 1111, 2048 }, { 5, 1112, 2048 }, { 6, 1113, 2048 }, { 6, 1114, 2048 }, { 7, 1115, 2048 }, { 6, 1116, 2048 }, { 7, 1117, 2048 }, { 7, 1118, 2048 }, { 8, 1119, 2048 }, { 4, 1120, 2048 }, { 5, 1121, 2048 }, { 5, 1122, 2048 }, { 6, 1123, 2048 }, { 5, 1124, 2048 }, { 6, 1125, 2048 }, { 6, 1126, 2048 }, { 7, 1127, 2048 }, { 5, 1128, 2048 }, { 6, 1129, 2048 }, { 6, 1130, 2048 }, { 7, 1131, 2048 }, { 6, 1132, 2048 }, { 7, 1133, 2048 }, { 7, 1134, 2048 }, { 8, 1135, 2048 }, { 5, 1136, 2048 }, { 6, 1137, 2048 }, { 6, 1138, 2048 }, { 7, 1139, 2048 }, { 6, 1140, 2048 }, { 7, 1141, 2048 }, { 7, 1142, 2048 }, { 8, 1143, 2048 }, { 6, 1144, 2048 }, { 7, 1145, 2048 }, { 7, 1146, 2048 }, { 8, 1147, 2048 }, { 7, 1148, 2048 }, { 8, 1149, 2048 }, { 8, 1150, 2048 }, { 9, 1151, 2048 }, { 3, 1152, 2048 }, { 4, 1153, 2048 }, { 4, 1154, 2048 }, { 5, 1155, 2048 }, { 4, 1156, 2048 }, { 5, 1157, 2048 }, { 5, 1158, 2048 }, { 6, 1159, 2048 }, { 4, 1160, 2048 }, { 5, 1161, 2048 }, { 5, 1162, 2048 }, { 6, 1163, 2048 }, { 5, 1164, 2048 }, { 6, 1165, 2048 }, { 6, 1166, 2048 }, { 7, 1167, 2048 }, { 4, 1168, 2048 }, { 5, 1169, 2048 }, { 5, 1170, 2048 }, { 6, 1171, 2048 }, { 5, 1172, 2048 }, { 6, 1173, 2048 }, { 6, 1174, 2048 }, { 7, 1175, 2048 }, { 5, 1176, 2048 }, { 6, 1177, 2048 }, { 6, 1178, 2048 }, { 7, 1179, 2048 }, { 6, 1180, 2048 }, { 7, 1181, 2048 }, { 7, 1182, 2048 }, { 8, 1183, 2048 }, { 4, 1184, 2048 }, { 5, 1185, 2048 }, { 5, 1186, 2048 }, { 6, 1187, 2048 }, { 5, 1188, 2048 }, { 6, 1189, 2048 }, { 6, 1190, 2048 }, { 7, 1191, 2048 }, { 5, 1192, 2048 }, { 6, 1193, 2048 }, { 6, 1194, 2048 }, { 7, 1195, 2048 }, { 6, 1196, 2048 }, { 7, 1197, 2048 }, { 7, 1198, 2048 }, { 8, 1199, 2048 }, { 5, 1200, 2048 }, { 6, 1201, 2048 }, { 6, 1202, 2048 }, { 7, 1203, 2048 }, { 6, 1204, 2048 }, { 7, 1205, 2048 }, { 7, 1206, 2048 }, { 8, 1207, 2048 }, { 6, 1208, 2048 }, { 7, 1209, 2048 }, { 7, 1210, 2048 }, { 8, 1211, 2048 }, { 7, 1212, 2048 }, { 8, 1213, 2048 }, { 8, 1214, 2048 }, { 9, 1215, 2048 }, { 4, 1216, 2048 }, { 5, 1217, 2048 }, { 5, 1218, 2048 }, { 6, 1219, 2048 }, { 5, 1220, 2048 }, { 6, 1221, 2048 }, { 6, 1222, 2048 }, { 7, 1223, 2048 }, { 5, 1224, 2048 }, { 6, 1225, 2048 }, { 6, 1226, 2048 }, { 7, 1227, 2048 }, { 6, 1228, 2048 }, { 7, 1229, 2048 }, { 7, 1230, 2048 }, { 8, 1231, 2048 }, { 5, 1232, 2048 }, { 6, 1233, 2048 }, { 6, 1234, 2048 }, { 7, 1235, 2048 }, { 6, 1236, 2048 }, { 7, 1237, 2048 }, { 7, 1238, 2048 }, { 8, 1239, 2048 }, { 6, 1240, 2048 }, { 7, 1241, 2048 }, { 7, 1242, 2048 }, { 8, 1243, 2048 }, { 7, 1244, 2048 }, { 8, 1245, 2048 }, { 8, 1246, 2048 }, { 9, 1247, 2048 }, { 5, 1248, 2048 }, { 6, 1249, 2048 }, { 6, 1250, 2048 }, { 7, 1251, 2048 }, { 6, 1252, 2048 }, { 7, 1253, 2048 }, { 7, 1254, 2048 }, { 8, 1255, 2048 }, { 6, 1256, 2048 }, { 7, 1257, 2048 }, { 7, 1258, 2048 }, { 8, 1259, 2048 }, { 7, 1260, 2048 }, { 8, 1261, 2048 }, { 8, 1262, 2048 }, { 9, 1263, 2048 }, { 6, 1264, 2048 }, { 7, 1265, 2048 }, { 7, 1266, 2048 }, { 8, 1267, 2048 }, { 7, 1268, 2048 }, { 8, 1269, 2048 }, { 8, 1270, 2048 }, { 9, 1271, 2048 }, { 7, 1272, 2048 }, { 8, 1273, 2048 }, { 8, 1274, 2048 }, { 9, 1275, 2048 }, { 8, 1276, 2048 }, { 9, 1277, 2048 }, { 9, 1278, 2048 }, { 10, 1279, 2048 }, { 3, 1280, 2048 }, { 4, 1281, 2048 }, { 4, 1282, 2048 }, { 5, 1283, 2048 }, { 4, 1284, 2048 }, { 5, 1285, 2048 }, { 5, 1286, 2048 }, { 6, 1287, 2048 }, { 4, 1288, 2048 }, { 5, 1289, 2048 }, { 5, 1290, 2048 }, { 6, 1291, 2048 }, { 5, 1292, 2048 }, { 6, 1293, 2048 }, { 6, 1294, 2048 }, { 7, 1295, 2048 }, { 4, 1296, 2048 }, { 5, 1297, 2048 }, { 5, 1298, 2048 }, { 6, 1299, 2048 }, { 5, 1300, 2048 }, { 6, 1301, 2048 }, { 6, 1302, 2048 }, { 7, 1303, 2048 }, { 5, 1304, 2048 }, { 6, 1305, 2048 }, { 6, 1306, 2048 }, { 7, 1307, 2048 }, { 6, 1308, 2048 }, { 7, 1309, 2048 }, { 7, 1310, 2048 }, { 8, 1311, 2048 }, { 4, 1312, 2048 }, { 5, 1313, 2048 }, { 5, 1314, 2048 }, { 6, 1315, 2048 }, { 5, 1316, 2048 }, { 6, 1317, 2048 }, { 6, 1318, 2048 }, { 7, 1319, 2048 }, { 5, 1320, 2048 }, { 6, 1321, 2048 }, { 6, 1322, 2048 }, { 7, 1323, 2048 }, { 6, 1324, 2048 }, { 7, 1325, 2048 }, { 7, 1326, 2048 }, { 8, 1327, 2048 }, { 5, 1328, 2048 }, { 6, 1329, 2048 }, { 6, 1330, 2048 }, { 7, 1331, 2048 }, { 6, 1332, 2048 }, { 7, 1333, 2048 }, { 7, 1334, 2048 }, { 8, 1335, 2048 }, { 6, 1336, 2048 }, { 7, 1337, 2048 }, { 7, 1338, 2048 }, { 8, 1339, 2048 }, { 7, 1340, 2048 }, { 8, 1341, 2048 }, { 8, 1342, 2048 }, { 9, 1343, 2048 }, { 4, 1344, 2048 }, { 5, 1345, 2048 }, { 5, 1346, 2048 }, { 6, 1347, 2048 }, { 5, 1348, 2048 }, { 6, 1349, 2048 }, { 6, 1350, 2048 }, { 7, 1351, 2048 }, { 5, 1352, 2048 }, { 6, 1353, 2048 }, { 6, 1354, 2048 }, { 7, 1355, 2048 }, { 6, 1356, 2048 }, { 7, 1357, 2048 }, { 7, 1358, 2048 }, { 8, 1359, 2048 }, { 5, 1360, 2048 }, { 6, 1361, 2048 }, { 6, 1362, 2048 }, { 7, 1363, 2048 }, { 6, 1364, 2048 }, { 7, 1365, 2048 }, { 7, 1366, 2048 }, { 8, 1367, 2048 }, { 6, 1368, 2048 }, { 7, 1369, 2048 }, { 7, 1370, 2048 }, { 8, 1371, 2048 }, { 7, 1372, 2048 }, { 8, 1373, 2048 }, { 8, 1374, 2048 }, { 9, 1375, 2048 }, { 5, 1376, 2048 }, { 6, 1377, 2048 }, { 6, 1378, 2048 }, { 7, 1379, 2048 }, { 6, 1380, 2048 }, { 7, 1381, 2048 }, { 7, 1382, 2048 }, { 8, 1383, 2048 }, { 6, 1384, 2048 }, { 7, 1385, 2048 }, { 7, 1386, 2048 }, { 8, 1387, 2048 }, { 7, 1388, 2048 }, { 8, 1389, 2048 }, { 8, 1390, 2048 }, { 9, 1391, 2048 }, { 6, 1392, 2048 }, { 7, 1393, 2048 }, { 7, 1394, 2048 }, { 8, 1395, 2048 }, { 7, 1396, 2048 }, { 8, 1397, 2048 }, { 8, 1398, 2048 }, { 9, 1399, 2048 }, { 7, 1400, 2048 }, { 8, 1401, 2048 }, { 8, 1402, 2048 }, { 9, 1403, 2048 }, { 8, 1404, 2048 }, { 9, 1405, 2048 }, { 9, 1406, 2048 }, { 10, 1407, 2048 }, { 4, 1408, 2048 }, { 5, 1409, 2048 }, { 5, 1410, 2048 }, { 6, 1411, 2048 }, { 5, 1412, 2048 }, { 6, 1413, 2048 }, { 6, 1414, 2048 }, { 7, 1415, 2048 }, { 5, 1416, 2048 }, { 6, 1417, 2048 }, { 6, 1418, 2048 }, { 7, 1419, 2048 }, { 6, 1420, 2048 }, { 7, 1421, 2048 }, { 7, 1422, 2048 }, { 8, 1423, 2048 }, { 5, 1424, 2048 }, { 6, 1425, 2048 }, { 6, 1426, 2048 }, { 7, 1427, 2048 }, { 6, 1428, 2048 }, { 7, 1429, 2048 }, { 7, 1430, 2048 }, { 8, 1431, 2048 }, { 6, 1432, 2048 }, { 7, 1433, 2048 }, { 7, 1434, 2048 }, { 8, 1435, 2048 }, { 7, 1436, 2048 }, { 8, 1437, 2048 }, { 8, 1438, 2048 }, { 9, 1439, 2048 }, { 5, 1440, 2048 }, { 6, 1441, 2048 }, { 6, 1442, 2048 }, { 7, 1443, 2048 }, { 6, 1444, 2048 }, { 7, 1445, 2048 }, { 7, 1446, 2048 }, { 8, 1447, 2048 }, { 6, 1448, 2048 }, { 7, 1449, 2048 }, { 7, 1450, 2048 }, { 8, 1451, 2048 }, { 7, 1452, 2048 }, { 8, 1453, 2048 }, { 8, 1454, 2048 }, { 9, 1455, 2048 }, { 6, 1456, 2048 }, { 7, 1457, 2048 }, { 7, 1458, 2048 }, { 8, 1459, 2048 }, { 7, 1460, 2048 }, { 8, 1461, 2048 }, { 8, 1462, 2048 }, { 9, 1463, 2048 }, { 7, 1464, 2048 }, { 8, 1465, 2048 }, { 8, 1466, 2048 }, { 9, 1467, 2048 }, { 8, 1468, 2048 }, { 9, 1469, 2048 }, { 9, 1470, 2048 }, { 10, 1471, 2048 }, { 5, 1472, 2048 }, { 6, 1473, 2048 }, { 6, 1474, 2048 }, { 7, 1475, 2048 }, { 6, 1476, 2048 }, { 7, 1477, 2048 }, { 7, 1478, 2048 }, { 8, 1479, 2048 }, { 6, 1480, 2048 }, { 7, 1481, 2048 }, { 7, 1482, 2048 }, { 8, 1483, 2048 }, { 7, 1484, 2048 }, { 8, 1485, 2048 }, { 8, 1486, 2048 }, { 9, 1487, 2048 }, { 6, 1488, 2048 }, { 7, 1489, 2048 }, { 7, 1490, 2048 }, { 8, 1491, 2048 }, { 7, 1492, 2048 }, { 8, 1493, 2048 }, { 8, 1494, 2048 }, { 9, 1495, 2048 }, { 7, 1496, 2048 }, { 8, 1497, 2048 }, { 8, 1498, 2048 }, { 9, 1499, 2048 }, { 8, 1500, 2048 }, { 9, 1501, 2048 }, { 9, 1502, 2048 }, { 10, 1503, 2048 }, { 6, 1504, 2048 }, { 7, 1505, 2048 }, { 7, 1506, 2048 }, { 8, 1507, 2048 }, { 7, 1508, 2048 }, { 8, 1509, 2048 }, { 8, 1510, 2048 }, { 9, 1511, 2048 }, { 7, 1512, 2048 }, { 8, 1513, 2048 }, { 8, 1514, 2048 }, { 9, 1515, 2048 }, { 8, 1516, 2048 }, { 9, 1517, 2048 }, { 9, 1518, 2048 }, { 10, 1519, 2048 }, { 7, 1520, 2048 }, { 8, 1521, 2048 }, { 8, 1522, 2048 }, { 9, 1523, 2048 }, { 8, 1524, 2048 }, { 9, 1525, 2048 }, { 9, 1526, 2048 }, { 10, 1527, 2048 }, { 8, 1528, 2048 }, { 9, 1529, 2048 }, { 9, 1530, 2048 }, { 10, 1531, 2048 }, { 9, 1532, 2048 }, { 10, 1533, 2048 }, { 10, 1534, 2048 }, { 11, 1535, 2048 }, { 3, 1536, 2048 }, { 4, 1537, 2048 }, { 4, 1538, 2048 }, { 5, 1539, 2048 }, { 4, 1540, 2048 }, { 5, 1541, 2048 }, { 5, 1542, 2048 }, { 6, 1543, 2048 }, { 4, 1544, 2048 }, { 5, 1545, 2048 }, { 5, 1546, 2048 }, { 6, 1547, 2048 }, { 5, 1548, 2048 }, { 6, 1549, 2048 }, { 6, 1550, 2048 }, { 7, 1551, 2048 }, { 4, 1552, 2048 }, { 5, 1553, 2048 }, { 5, 1554, 2048 }, { 6, 1555, 2048 }, { 5, 1556, 2048 }, { 6, 1557, 2048 }, { 6, 1558, 2048 }, { 7, 1559, 2048 }, { 5, 1560, 2048 }, { 6, 1561, 2048 }, { 6, 1562, 2048 }, { 7, 1563, 2048 }, { 6, 1564, 2048 }, { 7, 1565, 2048 }, { 7, 1566, 2048 }, { 8, 1567, 2048 }, { 4, 1568, 2048 }, { 5, 1569, 2048 }, { 5, 1570, 2048 }, { 6, 1571, 2048 }, { 5, 1572, 2048 }, { 6, 1573, 2048 }, { 6, 1574, 2048 }, { 7, 1575, 2048 }, { 5, 1576, 2048 }, { 6, 1577, 2048 }, { 6, 1578, 2048 }, { 7, 1579, 2048 }, { 6, 1580, 2048 }, { 7, 1581, 2048 }, { 7, 1582, 2048 }, { 8, 1583, 2048 }, { 5, 1584, 2048 }, { 6, 1585, 2048 }, { 6, 1586, 2048 }, { 7, 1587, 2048 }, { 6, 1588, 2048 }, { 7, 1589, 2048 }, { 7, 1590, 2048 }, { 8, 1591, 2048 }, { 6, 1592, 2048 }, { 7, 1593, 2048 }, { 7, 1594, 2048 }, { 8, 1595, 2048 }, { 7, 1596, 2048 }, { 8, 1597, 2048 }, { 8, 1598, 2048 }, { 9, 1599, 2048 }, { 4, 1600, 2048 }, { 5, 1601, 2048 }, { 5, 1602, 2048 }, { 6, 1603, 2048 }, { 5, 1604, 2048 }, { 6, 1605, 2048 }, { 6, 1606, 2048 }, { 7, 1607, 2048 }, { 5, 1608, 2048 }, { 6, 1609, 2048 }, { 6, 1610, 2048 }, { 7, 1611, 2048 }, { 6, 1612, 2048 }, { 7, 1613, 2048 }, { 7, 1614, 2048 }, { 8, 1615, 2048 }, { 5, 1616, 2048 }, { 6, 1617, 2048 }, { 6, 1618, 2048 }, { 7, 1619, 2048 }, { 6, 1620, 2048 }, { 7, 1621, 2048 }, { 7, 1622, 2048 }, { 8, 1623, 2048 }, { 6, 1624, 2048 }, { 7, 1625, 2048 }, { 7, 1626, 2048 }, { 8, 1627, 2048 }, { 7, 1628, 2048 }, { 8, 1629, 2048 }, { 8, 1630, 2048 }, { 9, 1631, 2048 }, { 5, 1632, 2048 }, { 6, 1633, 2048 }, { 6, 1634, 2048 }, { 7, 1635, 2048 }, { 6, 1636, 2048 }, { 7, 1637, 2048 }, { 7, 1638, 2048 }, { 8, 1639, 2048 }, { 6, 1640, 2048 }, { 7, 1641, 2048 }, { 7, 1642, 2048 }, { 8, 1643, 2048 }, { 7, 1644, 2048 }, { 8, 1645, 2048 }, { 8, 1646, 2048 }, { 9, 1647, 2048 }, { 6, 1648, 2048 }, { 7, 1649, 2048 }, { 7, 1650, 2048 }, { 8, 1651, 2048 }, { 7, 1652, 2048 }, { 8, 1653, 2048 }, { 8, 1654, 2048 }, { 9, 1655, 2048 }, { 7, 1656, 2048 }, { 8, 1657, 2048 }, { 8, 1658, 2048 }, { 9, 1659, 2048 }, { 8, 1660, 2048 }, { 9, 1661, 2048 }, { 9, 1662, 2048 }, { 10, 1663, 2048 }, { 4, 1664, 2048 }, { 5, 1665, 2048 }, { 5, 1666, 2048 }, { 6, 1667, 2048 }, { 5, 1668, 2048 }, { 6, 1669, 2048 }, { 6, 1670, 2048 }, { 7, 1671, 2048 }, { 5, 1672, 2048 }, { 6, 1673, 2048 }, { 6, 1674, 2048 }, { 7, 1675, 2048 }, { 6, 1676, 2048 }, { 7, 1677, 2048 }, { 7, 1678, 2048 }, { 8, 1679, 2048 }, { 5, 1680, 2048 }, { 6, 1681, 2048 }, { 6, 1682, 2048 }, { 7, 1683, 2048 }, { 6, 1684, 2048 }, { 7, 1685, 2048 }, { 7, 1686, 2048 }, { 8, 1687, 2048 }, { 6, 1688, 2048 }, { 7, 1689, 2048 }, { 7, 1690, 2048 }, { 8, 1691, 2048 }, { 7, 1692, 2048 }, { 8, 1693, 2048 }, { 8, 1694, 2048 }, { 9, 1695, 2048 }, { 5, 1696, 2048 }, { 6, 1697, 2048 }, { 6, 1698, 2048 }, { 7, 1699, 2048 }, { 6, 1700, 2048 }, { 7, 1701, 2048 }, { 7, 1702, 2048 }, { 8, 1703, 2048 }, { 6, 1704, 2048 }, { 7, 1705, 2048 }, { 7, 1706, 2048 }, { 8, 1707, 2048 }, { 7, 1708, 2048 }, { 8, 1709, 2048 }, { 8, 1710, 2048 }, { 9, 1711, 2048 }, { 6, 1712, 2048 }, { 7, 1713, 2048 }, { 7, 1714, 2048 }, { 8, 1715, 2048 }, { 7, 1716, 2048 }, { 8, 1717, 2048 }, { 8, 1718, 2048 }, { 9, 1719, 2048 }, { 7, 1720, 2048 }, { 8, 1721, 2048 }, { 8, 1722, 2048 }, { 9, 1723, 2048 }, { 8, 1724, 2048 }, { 9, 1725, 2048 }, { 9, 1726, 2048 }, { 10, 1727, 2048 }, { 5, 1728, 2048 }, { 6, 1729, 2048 }, { 6, 1730, 2048 }, { 7, 1731, 2048 }, { 6, 1732, 2048 }, { 7, 1733, 2048 }, { 7, 1734, 2048 }, { 8, 1735, 2048 }, { 6, 1736, 2048 }, { 7, 1737, 2048 }, { 7, 1738, 2048 }, { 8, 1739, 2048 }, { 7, 1740, 2048 }, { 8, 1741, 2048 }, { 8, 1742, 2048 }, { 9, 1743, 2048 }, { 6, 1744, 2048 }, { 7, 1745, 2048 }, { 7, 1746, 2048 }, { 8, 1747, 2048 }, { 7, 1748, 2048 }, { 8, 1749, 2048 }, { 8, 1750, 2048 }, { 9, 1751, 2048 }, { 7, 1752, 2048 }, { 8, 1753, 2048 }, { 8, 1754, 2048 }, { 9, 1755, 2048 }, { 8, 1756, 2048 }, { 9, 1757, 2048 }, { 9, 1758, 2048 }, { 10, 1759, 2048 }, { 6, 1760, 2048 }, { 7, 1761, 2048 }, { 7, 1762, 2048 }, { 8, 1763, 2048 }, { 7, 1764, 2048 }, { 8, 1765, 2048 }, { 8, 1766, 2048 }, { 9, 1767, 2048 }, { 7, 1768, 2048 }, { 8, 1769, 2048 }, { 8, 1770, 2048 }, { 9, 1771, 2048 }, { 8, 1772, 2048 }, { 9, 1773, 2048 }, { 9, 1774, 2048 }, { 10, 1775, 2048 }, { 7, 1776, 2048 }, { 8, 1777, 2048 }, { 8, 1778, 2048 }, { 9, 1779, 2048 }, { 8, 1780, 2048 }, { 9, 1781, 2048 }, { 9, 1782, 2048 }, { 10, 1783, 2048 }, { 8, 1784, 2048 }, { 9, 1785, 2048 }, { 9, 1786, 2048 }, { 10, 1787, 2048 }, { 9, 1788, 2048 }, { 10, 1789, 2048 }, { 10, 1790, 2048 }, { 11, 1791, 2048 }, { 4, 1792, 2048 }, { 5, 1793, 2048 }, { 5, 1794, 2048 }, { 6, 1795, 2048 }, { 5, 1796, 2048 }, { 6, 1797, 2048 }, { 6, 1798, 2048 }, { 7, 1799, 2048 }, { 5, 1800, 2048 }, { 6, 1801, 2048 }, { 6, 1802, 2048 }, { 7, 1803, 2048 }, { 6, 1804, 2048 }, { 7, 1805, 2048 }, { 7, 1806, 2048 }, { 8, 1807, 2048 }, { 5, 1808, 2048 }, { 6, 1809, 2048 }, { 6, 1810, 2048 }, { 7, 1811, 2048 }, { 6, 1812, 2048 }, { 7, 1813, 2048 }, { 7, 1814, 2048 }, { 8, 1815, 2048 }, { 6, 1816, 2048 }, { 7, 1817, 2048 }, { 7, 1818, 2048 }, { 8, 1819, 2048 }, { 7, 1820, 2048 }, { 8, 1821, 2048 }, { 8, 1822, 2048 }, { 9, 1823, 2048 }, { 5, 1824, 2048 }, { 6, 1825, 2048 }, { 6, 1826, 2048 }, { 7, 1827, 2048 }, { 6, 1828, 2048 }, { 7, 1829, 2048 }, { 7, 1830, 2048 }, { 8, 1831, 2048 }, { 6, 1832, 2048 }, { 7, 1833, 2048 }, { 7, 1834, 2048 }, { 8, 1835, 2048 }, { 7, 1836, 2048 }, { 8, 1837, 2048 }, { 8, 1838, 2048 }, { 9, 1839, 2048 }, { 6, 1840, 2048 }, { 7, 1841, 2048 }, { 7, 1842, 2048 }, { 8, 1843, 2048 }, { 7, 1844, 2048 }, { 8, 1845, 2048 }, { 8, 1846, 2048 }, { 9, 1847, 2048 }, { 7, 1848, 2048 }, { 8, 1849, 2048 }, { 8, 1850, 2048 }, { 9, 1851, 2048 }, { 8, 1852, 2048 }, { 9, 1853, 2048 }, { 9, 1854, 2048 }, { 10, 1855, 2048 }, { 5, 1856, 2048 }, { 6, 1857, 2048 }, { 6, 1858, 2048 }, { 7, 1859, 2048 }, { 6, 1860, 2048 }, { 7, 1861, 2048 }, { 7, 1862, 2048 }, { 8, 1863, 2048 }, { 6, 1864, 2048 }, { 7, 1865, 2048 }, { 7, 1866, 2048 }, { 8, 1867, 2048 }, { 7, 1868, 2048 }, { 8, 1869, 2048 }, { 8, 1870, 2048 }, { 9, 1871, 2048 }, { 6, 1872, 2048 }, { 7, 1873, 2048 }, { 7, 1874, 2048 }, { 8, 1875, 2048 }, { 7, 1876, 2048 }, { 8, 1877, 2048 }, { 8, 1878, 2048 }, { 9, 1879, 2048 }, { 7, 1880, 2048 }, { 8, 1881, 2048 }, { 8, 1882, 2048 }, { 9, 1883, 2048 }, { 8, 1884, 2048 }, { 9, 1885, 2048 }, { 9, 1886, 2048 }, { 10, 1887, 2048 }, { 6, 1888, 2048 }, { 7, 1889, 2048 }, { 7, 1890, 2048 }, { 8, 1891, 2048 }, { 7, 1892, 2048 }, { 8, 1893, 2048 }, { 8, 1894, 2048 }, { 9, 1895, 2048 }, { 7, 1896, 2048 }, { 8, 1897, 2048 }, { 8, 1898, 2048 }, { 9, 1899, 2048 }, { 8, 1900, 2048 }, { 9, 1901, 2048 }, { 9, 1902, 2048 }, { 10, 1903, 2048 }, { 7, 1904, 2048 }, { 8, 1905, 2048 }, { 8, 1906, 2048 }, { 9, 1907, 2048 }, { 8, 1908, 2048 }, { 9, 1909, 2048 }, { 9, 1910, 2048 }, { 10, 1911, 2048 }, { 8, 1912, 2048 }, { 9, 1913, 2048 }, { 9, 1914, 2048 }, { 10, 1915, 2048 }, { 9, 1916, 2048 }, { 10, 1917, 2048 }, { 10, 1918, 2048 }, { 11, 1919, 2048 }, { 5, 1920, 2048 }, { 6, 1921, 2048 }, { 6, 1922, 2048 }, { 7, 1923, 2048 }, { 6, 1924, 2048 }, { 7, 1925, 2048 }, { 7, 1926, 2048 }, { 8, 1927, 2048 }, { 6, 1928, 2048 }, { 7, 1929, 2048 }, { 7, 1930, 2048 }, { 8, 1931, 2048 }, { 7, 1932, 2048 }, { 8, 1933, 2048 }, { 8, 1934, 2048 }, { 9, 1935, 2048 }, { 6, 1936, 2048 }, { 7, 1937, 2048 }, { 7, 1938, 2048 }, { 8, 1939, 2048 }, { 7, 1940, 2048 }, { 8, 1941, 2048 }, { 8, 1942, 2048 }, { 9, 1943, 2048 }, { 7, 1944, 2048 }, { 8, 1945, 2048 }, { 8, 1946, 2048 }, { 9, 1947, 2048 }, { 8, 1948, 2048 }, { 9, 1949, 2048 }, { 9, 1950, 2048 }, { 10, 1951, 2048 }, { 6, 1952, 2048 }, { 7, 1953, 2048 }, { 7, 1954, 2048 }, { 8, 1955, 2048 }, { 7, 1956, 2048 }, { 8, 1957, 2048 }, { 8, 1958, 2048 }, { 9, 1959, 2048 }, { 7, 1960, 2048 }, { 8, 1961, 2048 }, { 8, 1962, 2048 }, { 9, 1963, 2048 }, { 8, 1964, 2048 }, { 9, 1965, 2048 }, { 9, 1966, 2048 }, { 10, 1967, 2048 }, { 7, 1968, 2048 }, { 8, 1969, 2048 }, { 8, 1970, 2048 }, { 9, 1971, 2048 }, { 8, 1972, 2048 }, { 9, 1973, 2048 }, { 9, 1974, 2048 }, { 10, 1975, 2048 }, { 8, 1976, 2048 }, { 9, 1977, 2048 }, { 9, 1978, 2048 }, { 10, 1979, 2048 }, { 9, 1980, 2048 }, { 10, 1981, 2048 }, { 10, 1982, 2048 }, { 11, 1983, 2048 }, { 6, 1984, 2048 }, { 7, 1985, 2048 }, { 7, 1986, 2048 }, { 8, 1987, 2048 }, { 7, 1988, 2048 }, { 8, 1989, 2048 }, { 8, 1990, 2048 }, { 9, 1991, 2048 }, { 7, 1992, 2048 }, { 8, 1993, 2048 }, { 8, 1994, 2048 }, { 9, 1995, 2048 }, { 8, 1996, 2048 }, { 9, 1997, 2048 }, { 9, 1998, 2048 }, { 10, 1999, 2048 }, { 7, 2000, 2048 }, { 8, 2001, 2048 }, { 8, 2002, 2048 }, { 9, 2003, 2048 }, { 8, 2004, 2048 }, { 9, 2005, 2048 }, { 9, 2006, 2048 }, { 10, 2007, 2048 }, { 8, 2008, 2048 }, { 9, 2009, 2048 }, { 9, 2010, 2048 }, { 10, 2011, 2048 }, { 9, 2012, 2048 }, { 10, 2013, 2048 }, { 10, 2014, 2048 }, { 11, 2015, 2048 }, { 7, 2016, 2048 }, { 8, 2017, 2048 }, { 8, 2018, 2048 }, { 9, 2019, 2048 }, { 8, 2020, 2048 }, { 9, 2021, 2048 }, { 9, 2022, 2048 }, { 10, 2023, 2048 }, { 8, 2024, 2048 }, { 9, 2025, 2048 }, { 9, 2026, 2048 }, { 10, 2027, 2048 }, { 9, 2028, 2048 }, { 10, 2029, 2048 }, { 10, 2030, 2048 }, { 11, 2031, 2048 }, { 8, 2032, 2048 }, { 9, 2033, 2048 }, { 9, 2034, 2048 }, { 10, 2035, 2048 }, { 9, 2036, 2048 }, { 10, 2037, 2048 }, { 10, 2038, 2048 }, { 11, 2039, 2048 }, { 9, 2040, 2048 }, { 10, 2041, 2048 }, { 10, 2042, 2048 }, { 11, 2043, 2048 }, { 10, 2044, 2048 }, { 11, 2045, 2048 }, { 11, 2046, 2048 }, { 12, 2047, 2048 }, #endif #endif #endif #endif #endif #endif }; /* find a hole and free as required, return -1 if no hole found */ static int find_hole(void) { unsigned x; int y, z; for (z = -1, y = INT_MAX, x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].lru_count < y && fp_cache[x].lock == 0) { z = x; y = fp_cache[x].lru_count; } } /* decrease all */ for (x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].lru_count > 3) { --(fp_cache[x].lru_count); } } /* free entry z */ if (z >= 0 && fp_cache[z].g) { mp_clear(&fp_cache[z].mu); wc_ecc_del_point(fp_cache[z].g); fp_cache[z].g = NULL; for (x = 0; x < (1U<<FP_LUT); x++) { wc_ecc_del_point(fp_cache[z].LUT[x]); fp_cache[z].LUT[x] = NULL; } fp_cache[z].lru_count = 0; } return z; } /* determine if a base is already in the cache and if so, where */ static int find_base(ecc_point* g) { int x; for (x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].g != NULL && mp_cmp(fp_cache[x].g->x, g->x) == MP_EQ && mp_cmp(fp_cache[x].g->y, g->y) == MP_EQ && mp_cmp(fp_cache[x].g->z, g->z) == MP_EQ) { break; } } if (x == FP_ENTRIES) { x = -1; } return x; } /* add a new base to the cache */ static int add_entry(int idx, ecc_point *g) { unsigned x, y; /* allocate base and LUT */ fp_cache[idx].g = wc_ecc_new_point(); if (fp_cache[idx].g == NULL) { return GEN_MEM_ERR; } /* copy x and y */ if ((mp_copy(g->x, fp_cache[idx].g->x) != MP_OKAY) || (mp_copy(g->y, fp_cache[idx].g->y) != MP_OKAY) || (mp_copy(g->z, fp_cache[idx].g->z) != MP_OKAY)) { wc_ecc_del_point(fp_cache[idx].g); fp_cache[idx].g = NULL; return GEN_MEM_ERR; } for (x = 0; x < (1U<<FP_LUT); x++) { fp_cache[idx].LUT[x] = wc_ecc_new_point(); if (fp_cache[idx].LUT[x] == NULL) { for (y = 0; y < x; y++) { wc_ecc_del_point(fp_cache[idx].LUT[y]); fp_cache[idx].LUT[y] = NULL; } wc_ecc_del_point(fp_cache[idx].g); fp_cache[idx].g = NULL; fp_cache[idx].lru_count = 0; return GEN_MEM_ERR; } } fp_cache[idx].lru_count = 0; return MP_OKAY; } #endif #ifndef WOLFSSL_SP_MATH /* build the LUT by spacing the bits of the input by #modulus/FP_LUT bits apart * * The algorithm builds patterns in increasing bit order by first making all * single bit input patterns, then all two bit input patterns and so on */ static int build_lut(int idx, mp_int* a, mp_int* modulus, mp_digit mp, mp_int* mu) { int err; unsigned x, y, bitlen, lut_gap; mp_int tmp; if (mp_init(&tmp) != MP_OKAY) return GEN_MEM_ERR; /* sanity check to make sure lut_order table is of correct size, should compile out to a NOP if true */ if ((sizeof(lut_orders) / sizeof(lut_orders[0])) < (1U<<FP_LUT)) { err = BAD_FUNC_ARG; } else { /* get bitlen and round up to next multiple of FP_LUT */ bitlen = mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { bitlen += FP_LUT - x; } lut_gap = bitlen / FP_LUT; /* init the mu */ err = mp_init_copy(&fp_cache[idx].mu, mu); } /* copy base */ if (err == MP_OKAY) { if ((mp_mulmod(fp_cache[idx].g->x, mu, modulus, fp_cache[idx].LUT[1]->x) != MP_OKAY) || (mp_mulmod(fp_cache[idx].g->y, mu, modulus, fp_cache[idx].LUT[1]->y) != MP_OKAY) || (mp_mulmod(fp_cache[idx].g->z, mu, modulus, fp_cache[idx].LUT[1]->z) != MP_OKAY)) { err = MP_MULMOD_E; } } /* make all single bit entries */ for (x = 1; x < FP_LUT; x++) { if (err != MP_OKAY) break; if ((mp_copy(fp_cache[idx].LUT[1<<(x-1)]->x, fp_cache[idx].LUT[1<<x]->x) != MP_OKAY) || (mp_copy(fp_cache[idx].LUT[1<<(x-1)]->y, fp_cache[idx].LUT[1<<x]->y) != MP_OKAY) || (mp_copy(fp_cache[idx].LUT[1<<(x-1)]->z, fp_cache[idx].LUT[1<<x]->z) != MP_OKAY)){ err = MP_INIT_E; break; } else { /* now double it bitlen/FP_LUT times */ for (y = 0; y < lut_gap; y++) { if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[1<<x], fp_cache[idx].LUT[1<<x], a, modulus, mp)) != MP_OKAY) { break; } } } } /* now make all entries in increase order of hamming weight */ for (x = 2; x <= FP_LUT; x++) { if (err != MP_OKAY) break; for (y = 0; y < (1UL<<FP_LUT); y++) { if (lut_orders[y].ham != (int)x) continue; /* perform the add */ if ((err = ecc_projective_add_point( fp_cache[idx].LUT[lut_orders[y].terma], fp_cache[idx].LUT[lut_orders[y].termb], fp_cache[idx].LUT[y], a, modulus, mp)) != MP_OKAY) { break; } } } /* now map all entries back to affine space to make point addition faster */ for (x = 1; x < (1UL<<FP_LUT); x++) { if (err != MP_OKAY) break; /* convert z to normal from montgomery */ err = mp_montgomery_reduce(fp_cache[idx].LUT[x]->z, modulus, mp); /* invert it */ if (err == MP_OKAY) err = mp_invmod(fp_cache[idx].LUT[x]->z, modulus, fp_cache[idx].LUT[x]->z); if (err == MP_OKAY) /* now square it */ err = mp_sqrmod(fp_cache[idx].LUT[x]->z, modulus, &tmp); if (err == MP_OKAY) /* fix x */ err = mp_mulmod(fp_cache[idx].LUT[x]->x, &tmp, modulus, fp_cache[idx].LUT[x]->x); if (err == MP_OKAY) /* get 1/z^3 */ err = mp_mulmod(&tmp, fp_cache[idx].LUT[x]->z, modulus, &tmp); if (err == MP_OKAY) /* fix y */ err = mp_mulmod(fp_cache[idx].LUT[x]->y, &tmp, modulus, fp_cache[idx].LUT[x]->y); if (err == MP_OKAY) /* free z */ mp_clear(fp_cache[idx].LUT[x]->z); } mp_clear(&tmp); if (err == MP_OKAY) return MP_OKAY; /* err cleanup */ for (y = 0; y < (1U<<FP_LUT); y++) { wc_ecc_del_point(fp_cache[idx].LUT[y]); fp_cache[idx].LUT[y] = NULL; } wc_ecc_del_point(fp_cache[idx].g); fp_cache[idx].g = NULL; fp_cache[idx].lru_count = 0; mp_clear(&fp_cache[idx].mu); return err; } /* perform a fixed point ECC mulmod */ static int accel_fp_mul(int idx, mp_int* k, ecc_point *R, mp_int* a, mp_int* modulus, mp_digit mp, int map) { #define KB_SIZE 128 #ifdef WOLFSSL_SMALL_STACK unsigned char* kb = NULL; #else unsigned char kb[KB_SIZE]; #endif int x, err; unsigned y, z = 0, bitlen, bitpos, lut_gap, first; mp_int tk, order; if (mp_init_multi(&tk, &order, NULL, NULL, NULL, NULL) != MP_OKAY) return MP_INIT_E; /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(k) > mp_unsigned_bin_size(modulus)) { /* find order */ y = mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } /* back off if we are on the 521 bit curve */ if (y == 66) --x; if ((err = mp_read_radix(&order, ecc_sets[x].order, MP_RADIX_HEX)) != MP_OKAY) { goto done; } /* k must be less than modulus */ if (mp_cmp(k, &order) != MP_LT) { if ((err = mp_mod(k, &order, &tk)) != MP_OKAY) { goto done; } } else { if ((err = mp_copy(k, &tk)) != MP_OKAY) { goto done; } } } else { if ((err = mp_copy(k, &tk)) != MP_OKAY) { goto done; } } /* get bitlen and round up to next multiple of FP_LUT */ bitlen = mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { bitlen += FP_LUT - x; } lut_gap = bitlen / FP_LUT; /* get the k value */ if (mp_unsigned_bin_size(&tk) > (int)(KB_SIZE - 2)) { err = BUFFER_E; goto done; } /* store k */ #ifdef WOLFSSL_SMALL_STACK kb = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (kb == NULL) { err = MEMORY_E; goto done; } #endif XMEMSET(kb, 0, KB_SIZE); if ((err = mp_to_unsigned_bin(&tk, kb)) == MP_OKAY) { /* let's reverse kb so it's little endian */ x = 0; y = mp_unsigned_bin_size(&tk); if (y > 0) { y -= 1; } while ((unsigned)x < y) { z = kb[x]; kb[x] = kb[y]; kb[y] = (byte)z; ++x; --y; } /* at this point we can start, yipee */ first = 1; for (x = lut_gap-1; x >= 0; x--) { /* extract FP_LUT bits from kb spread out by lut_gap bits and offset by x bits from the start */ bitpos = x; for (y = z = 0; y < FP_LUT; y++) { z |= ((kb[bitpos>>3] >> (bitpos&7)) & 1) << y; bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid the mult in each loop */ } /* double if not first */ if (!first) { if ((err = ecc_projective_dbl_point(R, R, a, modulus, mp)) != MP_OKAY) { break; } } /* add if not first, otherwise copy */ if (!first && z) { if ((err = ecc_projective_add_point(R, fp_cache[idx].LUT[z], R, a, modulus, mp)) != MP_OKAY) { break; } } else if (z) { if ((mp_copy(fp_cache[idx].LUT[z]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx].LUT[z]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx].mu, R->z) != MP_OKAY)) { err = GEN_MEM_ERR; break; } first = 0; } } } if (err == MP_OKAY) { (void) z; /* Acknowledge the unused assignment */ ForceZero(kb, KB_SIZE); /* map R back from projective space */ if (map) { err = ecc_map(R, modulus, mp); } else { err = MP_OKAY; } } done: /* cleanup */ mp_clear(&order); mp_clear(&tk); #ifdef WOLFSSL_SMALL_STACK XFREE(kb, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif #undef KB_SIZE return err; } #endif #ifdef ECC_SHAMIR #ifndef WOLFSSL_SP_MATH /* perform a fixed point ECC mulmod */ static int accel_fp_mul2add(int idx1, int idx2, mp_int* kA, mp_int* kB, ecc_point *R, mp_int* a, mp_int* modulus, mp_digit mp) { #define KB_SIZE 128 #ifdef WOLFSSL_SMALL_STACK unsigned char* kb[2] = {NULL, NULL}; #else unsigned char kb[2][KB_SIZE]; #endif int x, err; unsigned y, z, bitlen, bitpos, lut_gap, first, zA, zB; mp_int tka, tkb, order; if (mp_init_multi(&tka, &tkb, &order, NULL, NULL, NULL) != MP_OKAY) return MP_INIT_E; /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(kA) > mp_unsigned_bin_size(modulus)) { /* find order */ y = mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } /* back off if we are on the 521 bit curve */ if (y == 66) --x; if ((err = mp_read_radix(&order, ecc_sets[x].order, MP_RADIX_HEX)) != MP_OKAY) { goto done; } /* kA must be less than modulus */ if (mp_cmp(kA, &order) != MP_LT) { if ((err = mp_mod(kA, &order, &tka)) != MP_OKAY) { goto done; } } else { if ((err = mp_copy(kA, &tka)) != MP_OKAY) { goto done; } } } else { if ((err = mp_copy(kA, &tka)) != MP_OKAY) { goto done; } } /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(kB) > mp_unsigned_bin_size(modulus)) { /* find order */ y = mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } /* back off if we are on the 521 bit curve */ if (y == 66) --x; if ((err = mp_read_radix(&order, ecc_sets[x].order, MP_RADIX_HEX)) != MP_OKAY) { goto done; } /* kB must be less than modulus */ if (mp_cmp(kB, &order) != MP_LT) { if ((err = mp_mod(kB, &order, &tkb)) != MP_OKAY) { goto done; } } else { if ((err = mp_copy(kB, &tkb)) != MP_OKAY) { goto done; } } } else { if ((err = mp_copy(kB, &tkb)) != MP_OKAY) { goto done; } } /* get bitlen and round up to next multiple of FP_LUT */ bitlen = mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { bitlen += FP_LUT - x; } lut_gap = bitlen / FP_LUT; /* get the k value */ if ((mp_unsigned_bin_size(&tka) > (int)(KB_SIZE - 2)) || (mp_unsigned_bin_size(&tkb) > (int)(KB_SIZE - 2)) ) { err = BUFFER_E; goto done; } /* store k */ #ifdef WOLFSSL_SMALL_STACK kb[0] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (kb[0] == NULL) { err = MEMORY_E; goto done; } #endif XMEMSET(kb[0], 0, KB_SIZE); if ((err = mp_to_unsigned_bin(&tka, kb[0])) != MP_OKAY) { goto done; } /* let's reverse kb so it's little endian */ x = 0; y = mp_unsigned_bin_size(&tka); if (y > 0) { y -= 1; } mp_clear(&tka); while ((unsigned)x < y) { z = kb[0][x]; kb[0][x] = kb[0][y]; kb[0][y] = (byte)z; ++x; --y; } /* store b */ #ifdef WOLFSSL_SMALL_STACK kb[1] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (kb[1] == NULL) { err = MEMORY_E; goto done; } #endif XMEMSET(kb[1], 0, KB_SIZE); if ((err = mp_to_unsigned_bin(&tkb, kb[1])) == MP_OKAY) { x = 0; y = mp_unsigned_bin_size(&tkb); if (y > 0) { y -= 1; } while ((unsigned)x < y) { z = kb[1][x]; kb[1][x] = kb[1][y]; kb[1][y] = (byte)z; ++x; --y; } /* at this point we can start, yipee */ first = 1; for (x = lut_gap-1; x >= 0; x--) { /* extract FP_LUT bits from kb spread out by lut_gap bits and offset by x bits from the start */ bitpos = x; for (y = zA = zB = 0; y < FP_LUT; y++) { zA |= ((kb[0][bitpos>>3] >> (bitpos&7)) & 1) << y; zB |= ((kb[1][bitpos>>3] >> (bitpos&7)) & 1) << y; bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid the mult in each loop */ } /* double if not first */ if (!first) { if ((err = ecc_projective_dbl_point(R, R, a, modulus, mp)) != MP_OKAY) { break; } } /* add if not first, otherwise copy */ if (!first) { if (zA) { if ((err = ecc_projective_add_point(R, fp_cache[idx1].LUT[zA], R, a, modulus, mp)) != MP_OKAY) { break; } } if (zB) { if ((err = ecc_projective_add_point(R, fp_cache[idx2].LUT[zB], R, a, modulus, mp)) != MP_OKAY) { break; } } } else { if (zA) { if ((mp_copy(fp_cache[idx1].LUT[zA]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx1].LUT[zA]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx1].mu, R->z) != MP_OKAY)) { err = GEN_MEM_ERR; break; } first = 0; } if (zB && first == 0) { if (zB) { if ((err = ecc_projective_add_point(R, fp_cache[idx2].LUT[zB], R, a, modulus, mp)) != MP_OKAY){ break; } } } else if (zB && first == 1) { if ((mp_copy(fp_cache[idx2].LUT[zB]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx2].LUT[zB]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx2].mu, R->z) != MP_OKAY)) { err = GEN_MEM_ERR; break; } first = 0; } } } } done: /* cleanup */ mp_clear(&tkb); mp_clear(&tka); mp_clear(&order); #ifdef WOLFSSL_SMALL_STACK if (kb[0]) #endif ForceZero(kb[0], KB_SIZE); #ifdef WOLFSSL_SMALL_STACK if (kb[1]) #endif ForceZero(kb[1], KB_SIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(kb[0], NULL, DYNAMIC_TYPE_ECC_BUFFER); XFREE(kb[1], NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif #undef KB_SIZE if (err != MP_OKAY) return err; return ecc_map(R, modulus, mp); } /** ECC Fixed Point mulmod global with heap hint used Computes kA*A + kB*B = C using Shamir's Trick A First point to multiply kA What to multiple A by B Second point to multiply kB What to multiple B by C [out] Destination point (can overlap with A or B) a ECC curve parameter a modulus Modulus for curve return MP_OKAY on success */ int ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point* B, mp_int* kB, ecc_point* C, mp_int* a, mp_int* modulus, void* heap) { int idx1 = -1, idx2 = -1, err = MP_OKAY, mpInit = 0; mp_digit mp; mp_int mu; err = mp_init(&mu); if (err != MP_OKAY) return err; #ifndef HAVE_THREAD_LS if (initMutex == 0) { wc_InitMutex(&ecc_fp_lock); initMutex = 1; } if (wc_LockMutex(&ecc_fp_lock) != 0) return BAD_MUTEX_E; #endif /* HAVE_THREAD_LS */ /* find point */ idx1 = find_base(A); /* no entry? */ if (idx1 == -1) { /* find hole and add it */ if ((idx1 = find_hole()) >= 0) { err = add_entry(idx1, A); } } if (err == MP_OKAY && idx1 != -1) { /* increment LRU */ ++(fp_cache[idx1].lru_count); } if (err == MP_OKAY) /* find point */ idx2 = find_base(B); if (err == MP_OKAY) { /* no entry? */ if (idx2 == -1) { /* find hole and add it */ if ((idx2 = find_hole()) >= 0) err = add_entry(idx2, B); } } if (err == MP_OKAY && idx2 != -1) { /* increment LRU */ ++(fp_cache[idx2].lru_count); } if (err == MP_OKAY) { /* if it's 2 build the LUT, if it's higher just use the LUT */ if (idx1 >= 0 && fp_cache[idx1].lru_count == 2) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { mpInit = 1; err = mp_montgomery_calc_normalization(&mu, modulus); } if (err == MP_OKAY) /* build the LUT */ err = build_lut(idx1, a, modulus, mp, &mu); } } if (err == MP_OKAY) { /* if it's 2 build the LUT, if it's higher just use the LUT */ if (idx2 >= 0 && fp_cache[idx2].lru_count == 2) { if (mpInit == 0) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { mpInit = 1; err = mp_montgomery_calc_normalization(&mu, modulus); } } if (err == MP_OKAY) /* build the LUT */ err = build_lut(idx2, a, modulus, mp, &mu); } } if (err == MP_OKAY) { if (idx1 >=0 && idx2 >= 0 && fp_cache[idx1].lru_count >= 2 && fp_cache[idx2].lru_count >= 2) { if (mpInit == 0) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); } if (err == MP_OKAY) err = accel_fp_mul2add(idx1, idx2, kA, kB, C, a, modulus, mp); } else { err = normal_ecc_mul2add(A, kA, B, kB, C, a, modulus, heap); } } #ifndef HAVE_THREAD_LS wc_UnLockMutex(&ecc_fp_lock); #endif /* HAVE_THREAD_LS */ mp_clear(&mu); return err; } #endif #endif /* ECC_SHAMIR */ /** ECC Fixed Point mulmod global k The multiplicand G Base point to multiply R [out] Destination of product a ECC curve parameter a modulus The modulus for the curve map [boolean] If non-zero maps the point back to affine co-ordinates, otherwise it's left in jacobian-montgomery form return MP_OKAY if successful */ int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map, void* heap) { #ifndef WOLFSSL_SP_MATH int idx, err = MP_OKAY; mp_digit mp; mp_int mu; int mpSetup = 0; if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } if (mp_init(&mu) != MP_OKAY) return MP_INIT_E; #ifndef HAVE_THREAD_LS if (initMutex == 0) { wc_InitMutex(&ecc_fp_lock); initMutex = 1; } if (wc_LockMutex(&ecc_fp_lock) != 0) return BAD_MUTEX_E; #endif /* HAVE_THREAD_LS */ /* find point */ idx = find_base(G); /* no entry? */ if (idx == -1) { /* find hole and add it */ idx = find_hole(); if (idx >= 0) err = add_entry(idx, G); } if (err == MP_OKAY && idx >= 0) { /* increment LRU */ ++(fp_cache[idx].lru_count); } if (err == MP_OKAY) { /* if it's 2 build the LUT, if it's higher just use the LUT */ if (idx >= 0 && fp_cache[idx].lru_count == 2) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { /* compute mu */ mpSetup = 1; err = mp_montgomery_calc_normalization(&mu, modulus); } if (err == MP_OKAY) /* build the LUT */ err = build_lut(idx, a, modulus, mp, &mu); } } if (err == MP_OKAY) { if (idx >= 0 && fp_cache[idx].lru_count >= 2) { if (mpSetup == 0) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); } if (err == MP_OKAY) err = accel_fp_mul(idx, k, R, a, modulus, mp, map); } else { err = normal_ecc_mulmod(k, G, R, a, modulus, map, heap); } } #ifndef HAVE_THREAD_LS wc_UnLockMutex(&ecc_fp_lock); #endif /* HAVE_THREAD_LS */ mp_clear(&mu); return err; #else if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } return sp_ecc_mulmod_256(k, G, R, map, heap); #endif } #ifndef WOLFSSL_SP_MATH /* helper function for freeing the cache ... must be called with the cache mutex locked */ static void wc_ecc_fp_free_cache(void) { unsigned x, y; for (x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].g != NULL) { for (y = 0; y < (1U<<FP_LUT); y++) { wc_ecc_del_point(fp_cache[x].LUT[y]); fp_cache[x].LUT[y] = NULL; } wc_ecc_del_point(fp_cache[x].g); fp_cache[x].g = NULL; mp_clear(&fp_cache[x].mu); fp_cache[x].lru_count = 0; fp_cache[x].lock = 0; } } } #endif /** Free the Fixed Point cache */ void wc_ecc_fp_free(void) { #ifndef WOLFSSL_SP_MATH #ifndef HAVE_THREAD_LS if (initMutex == 0) { wc_InitMutex(&ecc_fp_lock); initMutex = 1; } if (wc_LockMutex(&ecc_fp_lock) == 0) { #endif /* HAVE_THREAD_LS */ wc_ecc_fp_free_cache(); #ifndef HAVE_THREAD_LS wc_UnLockMutex(&ecc_fp_lock); wc_FreeMutex(&ecc_fp_lock); initMutex = 0; } #endif /* HAVE_THREAD_LS */ #endif } #endif /* FP_ECC */ #ifdef HAVE_ECC_ENCRYPT enum ecCliState { ecCLI_INIT = 1, ecCLI_SALT_GET = 2, ecCLI_SALT_SET = 3, ecCLI_SENT_REQ = 4, ecCLI_RECV_RESP = 5, ecCLI_BAD_STATE = 99 }; enum ecSrvState { ecSRV_INIT = 1, ecSRV_SALT_GET = 2, ecSRV_SALT_SET = 3, ecSRV_RECV_REQ = 4, ecSRV_SENT_RESP = 5, ecSRV_BAD_STATE = 99 }; struct ecEncCtx { const byte* kdfSalt; /* optional salt for kdf */ const byte* kdfInfo; /* optional info for kdf */ const byte* macSalt; /* optional salt for mac */ word32 kdfSaltSz; /* size of kdfSalt */ word32 kdfInfoSz; /* size of kdfInfo */ word32 macSaltSz; /* size of macSalt */ void* heap; /* heap hint for memory used */ byte clientSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */ byte serverSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */ byte encAlgo; /* which encryption type */ byte kdfAlgo; /* which key derivation function type */ byte macAlgo; /* which mac function type */ byte protocol; /* are we REQ_RESP client or server ? */ byte cliSt; /* protocol state, for sanity checks */ byte srvSt; /* protocol state, for sanity checks */ }; const byte* wc_ecc_ctx_get_own_salt(ecEncCtx* ctx) { if (ctx == NULL || ctx->protocol == 0) return NULL; if (ctx->protocol == REQ_RESP_CLIENT) { if (ctx->cliSt == ecCLI_INIT) { ctx->cliSt = ecCLI_SALT_GET; return ctx->clientSalt; } else { ctx->cliSt = ecCLI_BAD_STATE; return NULL; } } else if (ctx->protocol == REQ_RESP_SERVER) { if (ctx->srvSt == ecSRV_INIT) { ctx->srvSt = ecSRV_SALT_GET; return ctx->serverSalt; } else { ctx->srvSt = ecSRV_BAD_STATE; return NULL; } } return NULL; } /* optional set info, can be called before or after set_peer_salt */ int wc_ecc_ctx_set_info(ecEncCtx* ctx, const byte* info, int sz) { if (ctx == NULL || info == 0 || sz < 0) return BAD_FUNC_ARG; ctx->kdfInfo = info; ctx->kdfInfoSz = sz; return 0; } static const char* exchange_info = "Secure Message Exchange"; int wc_ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt) { byte tmp[EXCHANGE_SALT_SZ/2]; int halfSz = EXCHANGE_SALT_SZ/2; if (ctx == NULL || ctx->protocol == 0 || salt == NULL) return BAD_FUNC_ARG; if (ctx->protocol == REQ_RESP_CLIENT) { XMEMCPY(ctx->serverSalt, salt, EXCHANGE_SALT_SZ); if (ctx->cliSt == ecCLI_SALT_GET) ctx->cliSt = ecCLI_SALT_SET; else { ctx->cliSt = ecCLI_BAD_STATE; return BAD_STATE_E; } } else { XMEMCPY(ctx->clientSalt, salt, EXCHANGE_SALT_SZ); if (ctx->srvSt == ecSRV_SALT_GET) ctx->srvSt = ecSRV_SALT_SET; else { ctx->srvSt = ecSRV_BAD_STATE; return BAD_STATE_E; } } /* mix half and half */ /* tmp stores 2nd half of client before overwrite */ XMEMCPY(tmp, ctx->clientSalt + halfSz, halfSz); XMEMCPY(ctx->clientSalt + halfSz, ctx->serverSalt, halfSz); XMEMCPY(ctx->serverSalt, tmp, halfSz); ctx->kdfSalt = ctx->clientSalt; ctx->kdfSaltSz = EXCHANGE_SALT_SZ; ctx->macSalt = ctx->serverSalt; ctx->macSaltSz = EXCHANGE_SALT_SZ; if (ctx->kdfInfo == NULL) { /* default info */ ctx->kdfInfo = (const byte*)exchange_info; ctx->kdfInfoSz = EXCHANGE_INFO_SZ; } return 0; } static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags, WC_RNG* rng) { byte* saltBuffer = NULL; if (ctx == NULL || rng == NULL || flags == 0) return BAD_FUNC_ARG; saltBuffer = (flags == REQ_RESP_CLIENT) ? ctx->clientSalt : ctx->serverSalt; return wc_RNG_GenerateBlock(rng, saltBuffer, EXCHANGE_SALT_SZ); } static void ecc_ctx_init(ecEncCtx* ctx, int flags) { if (ctx) { XMEMSET(ctx, 0, sizeof(ecEncCtx)); ctx->encAlgo = ecAES_128_CBC; ctx->kdfAlgo = ecHKDF_SHA256; ctx->macAlgo = ecHMAC_SHA256; ctx->protocol = (byte)flags; if (flags == REQ_RESP_CLIENT) ctx->cliSt = ecCLI_INIT; if (flags == REQ_RESP_SERVER) ctx->srvSt = ecSRV_INIT; } } /* allow ecc context reset so user doesn't have to init/free for reuse */ int wc_ecc_ctx_reset(ecEncCtx* ctx, WC_RNG* rng) { if (ctx == NULL || rng == NULL) return BAD_FUNC_ARG; ecc_ctx_init(ctx, ctx->protocol); return ecc_ctx_set_salt(ctx, ctx->protocol, rng); } ecEncCtx* wc_ecc_ctx_new_ex(int flags, WC_RNG* rng, void* heap) { int ret = 0; ecEncCtx* ctx = (ecEncCtx*)XMALLOC(sizeof(ecEncCtx), heap, DYNAMIC_TYPE_ECC); if (ctx) { ctx->protocol = (byte)flags; ctx->heap = heap; } ret = wc_ecc_ctx_reset(ctx, rng); if (ret != 0) { wc_ecc_ctx_free(ctx); ctx = NULL; } return ctx; } /* alloc/init and set defaults, return new Context */ ecEncCtx* wc_ecc_ctx_new(int flags, WC_RNG* rng) { return wc_ecc_ctx_new_ex(flags, rng, NULL); } /* free any resources, clear any keys */ void wc_ecc_ctx_free(ecEncCtx* ctx) { if (ctx) { ForceZero(ctx, sizeof(ecEncCtx)); XFREE(ctx, ctx->heap, DYNAMIC_TYPE_ECC); } } static int ecc_get_key_sizes(ecEncCtx* ctx, int* encKeySz, int* ivSz, int* keysLen, word32* digestSz, word32* blockSz) { if (ctx) { switch (ctx->encAlgo) { case ecAES_128_CBC: *encKeySz = KEY_SIZE_128; *ivSz = IV_SIZE_128; *blockSz = AES_BLOCK_SIZE; break; default: return BAD_FUNC_ARG; } switch (ctx->macAlgo) { case ecHMAC_SHA256: *digestSz = WC_SHA256_DIGEST_SIZE; break; default: return BAD_FUNC_ARG; } } else return BAD_FUNC_ARG; *keysLen = *encKeySz + *ivSz + *digestSz; return 0; } /* ecc encrypt with shared secret run through kdf ctx holds non default algos and inputs msgSz should be the right size for encAlgo, i.e., already padded return 0 on success */ int wc_ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx) { int ret = 0; word32 blockSz; word32 digestSz; ecEncCtx localCtx; #ifdef WOLFSSL_SMALL_STACK byte* sharedSecret; byte* keys; #else byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */ byte keys[ECC_BUFSIZE]; /* max size */ #endif word32 sharedSz = ECC_MAXSIZE; int keysLen; int encKeySz; int ivSz; int offset = 0; /* keys offset if doing msg exchange */ byte* encKey; byte* encIv; byte* macKey; if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL || outSz == NULL) return BAD_FUNC_ARG; if (ctx == NULL) { /* use defaults */ ecc_ctx_init(&localCtx, 0); ctx = &localCtx; } ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz, &blockSz); if (ret != 0) return ret; if (ctx->protocol == REQ_RESP_SERVER) { offset = keysLen; keysLen *= 2; if (ctx->srvSt != ecSRV_RECV_REQ) return BAD_STATE_E; ctx->srvSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */ } else if (ctx->protocol == REQ_RESP_CLIENT) { if (ctx->cliSt != ecCLI_SALT_SET) return BAD_STATE_E; ctx->cliSt = ecCLI_SENT_REQ; /* only do this once */ } if (keysLen > ECC_BUFSIZE) /* keys size */ return BUFFER_E; if ( (msgSz%blockSz) != 0) return BAD_PADDING_E; if (*outSz < (msgSz + digestSz)) return BUFFER_E; #ifdef WOLFSSL_SMALL_STACK sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (sharedSecret == NULL) return MEMORY_E; keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (keys == NULL) { XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); return MEMORY_E; } #endif do { #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); if (ret != 0) break; #endif ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz); } while (ret == WC_PENDING_E); if (ret == 0) { switch (ctx->kdfAlgo) { case ecHKDF_SHA256 : ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt, ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz, keys, keysLen); break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { encKey = keys + offset; encIv = encKey + encKeySz; macKey = encKey + encKeySz + ivSz; switch (ctx->encAlgo) { case ecAES_128_CBC: { Aes aes; ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv, AES_ENCRYPTION); if (ret != 0) break; ret = wc_AesCbcEncrypt(&aes, out, msg, msgSz); #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &aes.asyncDev, WC_ASYNC_FLAG_NONE); #endif } break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { switch (ctx->macAlgo) { case ecHMAC_SHA256: { Hmac hmac; ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID); if (ret == 0) { ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE); if (ret == 0) ret = wc_HmacUpdate(&hmac, out, msgSz); if (ret == 0) ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz); if (ret == 0) ret = wc_HmacFinal(&hmac, out+msgSz); wc_HmacFree(&hmac); } } break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) *outSz = msgSz + digestSz; #ifdef WOLFSSL_SMALL_STACK XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return ret; } /* ecc decrypt with shared secret run through kdf ctx holds non default algos and inputs return 0 on success */ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx) { int ret = 0; word32 blockSz; word32 digestSz; ecEncCtx localCtx; #ifdef WOLFSSL_SMALL_STACK byte* sharedSecret; byte* keys; #else byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */ byte keys[ECC_BUFSIZE]; /* max size */ #endif word32 sharedSz = ECC_MAXSIZE; int keysLen; int encKeySz; int ivSz; int offset = 0; /* in case using msg exchange */ byte* encKey; byte* encIv; byte* macKey; if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL || outSz == NULL) return BAD_FUNC_ARG; if (ctx == NULL) { /* use defaults */ ecc_ctx_init(&localCtx, 0); ctx = &localCtx; } ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz, &blockSz); if (ret != 0) return ret; if (ctx->protocol == REQ_RESP_CLIENT) { offset = keysLen; keysLen *= 2; if (ctx->cliSt != ecCLI_SENT_REQ) return BAD_STATE_E; ctx->cliSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */ } else if (ctx->protocol == REQ_RESP_SERVER) { if (ctx->srvSt != ecSRV_SALT_SET) return BAD_STATE_E; ctx->srvSt = ecSRV_RECV_REQ; /* only do this once */ } if (keysLen > ECC_BUFSIZE) /* keys size */ return BUFFER_E; if ( ((msgSz-digestSz) % blockSz) != 0) return BAD_PADDING_E; if (*outSz < (msgSz - digestSz)) return BUFFER_E; #ifdef WOLFSSL_SMALL_STACK sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (sharedSecret == NULL) return MEMORY_E; keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (keys == NULL) { XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); return MEMORY_E; } #endif do { #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); if (ret != 0) break; #endif ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz); } while (ret == WC_PENDING_E); if (ret == 0) { switch (ctx->kdfAlgo) { case ecHKDF_SHA256 : ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt, ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz, keys, keysLen); break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { encKey = keys + offset; encIv = encKey + encKeySz; macKey = encKey + encKeySz + ivSz; switch (ctx->macAlgo) { case ecHMAC_SHA256: { byte verify[WC_SHA256_DIGEST_SIZE]; Hmac hmac; ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID); if (ret == 0) { ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE); if (ret == 0) ret = wc_HmacUpdate(&hmac, msg, msgSz-digestSz); if (ret == 0) ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz); if (ret == 0) ret = wc_HmacFinal(&hmac, verify); if (ret == 0) { if (XMEMCMP(verify, msg + msgSz - digestSz, digestSz) != 0) ret = -1; } wc_HmacFree(&hmac); } break; } default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { switch (ctx->encAlgo) { #ifdef HAVE_AES_CBC case ecAES_128_CBC: { Aes aes; ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv, AES_DECRYPTION); if (ret != 0) break; ret = wc_AesCbcDecrypt(&aes, out, msg, msgSz-digestSz); #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &aes.asyncDev, WC_ASYNC_FLAG_NONE); #endif } break; #endif default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) *outSz = msgSz - digestSz; #ifdef WOLFSSL_SMALL_STACK XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return ret; } #endif /* HAVE_ECC_ENCRYPT */ #ifdef HAVE_COMP_KEY #ifndef WOLFSSL_ATECC508A #ifndef WOLFSSL_SP_MATH int do_mp_jacobi(mp_int* a, mp_int* n, int* c); int do_mp_jacobi(mp_int* a, mp_int* n, int* c) { int k, s, res; int r = 0; /* initialize to help static analysis out */ mp_digit residue; /* if a < 0 return MP_VAL */ if (mp_isneg(a) == MP_YES) { return MP_VAL; } /* if n <= 0 return MP_VAL */ if (mp_cmp_d(n, 0) != MP_GT) { return MP_VAL; } /* step 1. handle case of a == 0 */ if (mp_iszero (a) == MP_YES) { /* special case of a == 0 and n == 1 */ if (mp_cmp_d (n, 1) == MP_EQ) { *c = 1; } else { *c = 0; } return MP_OKAY; } /* step 2. if a == 1, return 1 */ if (mp_cmp_d (a, 1) == MP_EQ) { *c = 1; return MP_OKAY; } /* default */ s = 0; /* divide out larger power of two */ k = mp_cnt_lsb(a); res = mp_div_2d(a, k, a, NULL); if (res == MP_OKAY) { /* step 4. if e is even set s=1 */ if ((k & 1) == 0) { s = 1; } else { /* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */ residue = n->dp[0] & 7; if (residue == 1 || residue == 7) { s = 1; } else if (residue == 3 || residue == 5) { s = -1; } } /* step 5. if p == 3 (mod 4) *and* a == 3 (mod 4) then s = -s */ if ( ((n->dp[0] & 3) == 3) && ((a->dp[0] & 3) == 3)) { s = -s; } } if (res == MP_OKAY) { /* if a == 1 we're done */ if (mp_cmp_d(a, 1) == MP_EQ) { *c = s; } else { /* n1 = n mod a */ res = mp_mod (n, a, n); if (res == MP_OKAY) res = do_mp_jacobi(n, a, &r); if (res == MP_OKAY) *c = s * r; } } return res; } /* computes the jacobi c = (a | n) (or Legendre if n is prime) * HAC pp. 73 Algorithm 2.149 * HAC is wrong here, as the special case of (0 | 1) is not * handled correctly. */ int mp_jacobi(mp_int* a, mp_int* n, int* c) { mp_int a1, n1; int res; /* step 3. write a = a1 * 2**k */ if ((res = mp_init_multi(&a1, &n1, NULL, NULL, NULL, NULL)) != MP_OKAY) { return res; } if ((res = mp_copy(a, &a1)) != MP_OKAY) { goto done; } if ((res = mp_copy(n, &n1)) != MP_OKAY) { goto done; } res = do_mp_jacobi(&a1, &n1, c); done: /* cleanup */ mp_clear(&n1); mp_clear(&a1); return res; } /* Solves the modular equation x^2 = n (mod p) * where prime number is greater than 2 (odd prime). * The result is returned in the third argument x * the function returns MP_OKAY on success, MP_VAL or another error on failure */ int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret) { #ifdef SQRTMOD_USE_MOD_EXP int res; mp_int e; res = mp_init(&e); if (res == MP_OKAY) res = mp_add_d(prime, 1, &e); if (res == MP_OKAY) res = mp_div_2d(&e, 2, &e, NULL); if (res == MP_OKAY) res = mp_exptmod(n, &e, prime, ret); mp_clear(&e); return res; #else int res, legendre, done = 0; mp_int t1, C, Q, S, Z, M, T, R, two; mp_digit i; /* first handle the simple cases n = 0 or n = 1 */ if (mp_cmp_d(n, 0) == MP_EQ) { mp_zero(ret); return MP_OKAY; } if (mp_cmp_d(n, 1) == MP_EQ) { return mp_set(ret, 1); } /* prime must be odd */ if (mp_cmp_d(prime, 2) == MP_EQ) { return MP_VAL; } /* is quadratic non-residue mod prime */ if ((res = mp_jacobi(n, prime, &legendre)) != MP_OKAY) { return res; } if (legendre == -1) { return MP_VAL; } if ((res = mp_init_multi(&t1, &C, &Q, &S, &Z, &M)) != MP_OKAY) return res; if ((res = mp_init_multi(&T, &R, &two, NULL, NULL, NULL)) != MP_OKAY) { mp_clear(&t1); mp_clear(&C); mp_clear(&Q); mp_clear(&S); mp_clear(&Z); mp_clear(&M); return res; } /* SPECIAL CASE: if prime mod 4 == 3 * compute directly: res = n^(prime+1)/4 mod prime * Handbook of Applied Cryptography algorithm 3.36 */ res = mp_mod_d(prime, 4, &i); if (res == MP_OKAY && i == 3) { res = mp_add_d(prime, 1, &t1); if (res == MP_OKAY) res = mp_div_2(&t1, &t1); if (res == MP_OKAY) res = mp_div_2(&t1, &t1); if (res == MP_OKAY) res = mp_exptmod(n, &t1, prime, ret); done = 1; } /* NOW: TonelliShanks algorithm */ if (res == MP_OKAY && done == 0) { /* factor out powers of 2 from prime-1, defining Q and S * as: prime-1 = Q*2^S */ /* Q = prime - 1 */ res = mp_copy(prime, &Q); if (res == MP_OKAY) res = mp_sub_d(&Q, 1, &Q); /* S = 0 */ if (res == MP_OKAY) mp_zero(&S); while (res == MP_OKAY && mp_iseven(&Q) == MP_YES) { /* Q = Q / 2 */ res = mp_div_2(&Q, &Q); /* S = S + 1 */ if (res == MP_OKAY) res = mp_add_d(&S, 1, &S); } /* find a Z such that the Legendre symbol (Z|prime) == -1 */ /* Z = 2 */ if (res == MP_OKAY) res = mp_set_int(&Z, 2); while (res == MP_OKAY) { res = mp_jacobi(&Z, prime, &legendre); if (res == MP_OKAY && legendre == -1) break; /* Z = Z + 1 */ if (res == MP_OKAY) res = mp_add_d(&Z, 1, &Z); } /* C = Z ^ Q mod prime */ if (res == MP_OKAY) res = mp_exptmod(&Z, &Q, prime, &C); /* t1 = (Q + 1) / 2 */ if (res == MP_OKAY) res = mp_add_d(&Q, 1, &t1); if (res == MP_OKAY) res = mp_div_2(&t1, &t1); /* R = n ^ ((Q + 1) / 2) mod prime */ if (res == MP_OKAY) res = mp_exptmod(n, &t1, prime, &R); /* T = n ^ Q mod prime */ if (res == MP_OKAY) res = mp_exptmod(n, &Q, prime, &T); /* M = S */ if (res == MP_OKAY) res = mp_copy(&S, &M); if (res == MP_OKAY) res = mp_set_int(&two, 2); while (res == MP_OKAY && done == 0) { res = mp_copy(&T, &t1); /* reduce to 1 and count */ i = 0; while (res == MP_OKAY) { if (mp_cmp_d(&t1, 1) == MP_EQ) break; res = mp_exptmod(&t1, &two, prime, &t1); if (res == MP_OKAY) i++; } if (res == MP_OKAY && i == 0) { res = mp_copy(&R, ret); done = 1; } if (done == 0) { /* t1 = 2 ^ (M - i - 1) */ if (res == MP_OKAY) res = mp_sub_d(&M, i, &t1); if (res == MP_OKAY) res = mp_sub_d(&t1, 1, &t1); if (res == MP_OKAY) res = mp_exptmod(&two, &t1, prime, &t1); /* t1 = C ^ (2 ^ (M - i - 1)) mod prime */ if (res == MP_OKAY) res = mp_exptmod(&C, &t1, prime, &t1); /* C = (t1 * t1) mod prime */ if (res == MP_OKAY) res = mp_sqrmod(&t1, prime, &C); /* R = (R * t1) mod prime */ if (res == MP_OKAY) res = mp_mulmod(&R, &t1, prime, &R); /* T = (T * C) mod prime */ if (res == MP_OKAY) res = mp_mulmod(&T, &C, prime, &T); /* M = i */ if (res == MP_OKAY) res = mp_set(&M, i); } } } /* done */ mp_clear(&t1); mp_clear(&C); mp_clear(&Q); mp_clear(&S); mp_clear(&Z); mp_clear(&M); mp_clear(&T); mp_clear(&R); mp_clear(&two); return res; #endif } #endif #endif /* !WOLFSSL_ATECC508A */ /* export public ECC key in ANSI X9.63 format compressed */ static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen) { word32 numlen; int ret = MP_OKAY; if (key == NULL || out == NULL || outLen == NULL) return BAD_FUNC_ARG; if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numlen = key->dp->size; if (*outLen < (1 + numlen)) { *outLen = 1 + numlen; return BUFFER_E; } #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ ret = BAD_COND_E; #else /* store first byte */ out[0] = mp_isodd(key->pubkey.y) == MP_YES ? ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN; /* pad and store x */ XMEMSET(out+1, 0, numlen); ret = mp_to_unsigned_bin(key->pubkey.x, out+1 + (numlen - mp_unsigned_bin_size(key->pubkey.x))); *outLen = 1 + numlen; #endif /* WOLFSSL_ATECC508A */ return ret; } #endif /* HAVE_COMP_KEY */ int wc_ecc_get_oid(word32 oidSum, const byte** oid, word32* oidSz) { int x; if (oidSum == 0) { return BAD_FUNC_ARG; } /* find matching OID sum (based on encoded value) */ for (x = 0; ecc_sets[x].size != 0; x++) { if (ecc_sets[x].oidSum == oidSum) { int ret = 0; #ifdef HAVE_OID_ENCODING /* check cache */ oid_cache_t* o = &ecc_oid_cache[x]; if (o->oidSz == 0) { o->oidSz = sizeof(o->oid); ret = EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz, o->oid, &o->oidSz); } if (oidSz) { *oidSz = o->oidSz; } if (oid) { *oid = o->oid; } #else if (oidSz) { *oidSz = ecc_sets[x].oidSz; } if (oid) { *oid = ecc_sets[x].oid; } #endif /* on success return curve id */ if (ret == 0) { ret = ecc_sets[x].id; } return ret; } } return NOT_COMPILED_IN; } #ifdef WOLFSSL_CUSTOM_CURVES int wc_ecc_set_custom_curve(ecc_key* key, const ecc_set_type* dp) { if (key == NULL || dp == NULL) { return BAD_FUNC_ARG; } key->idx = ECC_CUSTOM_IDX; key->dp = dp; return 0; } #endif /* WOLFSSL_CUSTOM_CURVES */ #ifdef HAVE_X963_KDF static INLINE void IncrementX963KdfCounter(byte* inOutCtr) { int i; /* in network byte order so start at end and work back */ for (i = 3; i >= 0; i--) { if (++inOutCtr[i]) /* we're done unless we overflow */ return; } } /* ASN X9.63 Key Derivation Function (SEC1) */ int wc_X963_KDF(enum wc_HashType type, const byte* secret, word32 secretSz, const byte* sinfo, word32 sinfoSz, byte* out, word32 outSz) { int ret, i; int digestSz, copySz; int remaining = outSz; byte* outIdx; byte counter[4]; byte tmp[WC_MAX_DIGEST_SIZE]; #ifdef WOLFSSL_SMALL_STACK wc_HashAlg* hash; #else wc_HashAlg hash[1]; #endif if (secret == NULL || secretSz == 0 || out == NULL) return BAD_FUNC_ARG; /* X9.63 allowed algos only */ if (type != WC_HASH_TYPE_SHA && type != WC_HASH_TYPE_SHA224 && type != WC_HASH_TYPE_SHA256 && type != WC_HASH_TYPE_SHA384 && type != WC_HASH_TYPE_SHA512) return BAD_FUNC_ARG; digestSz = wc_HashGetDigestSize(type); if (digestSz < 0) return digestSz; #ifdef WOLFSSL_SMALL_STACK hash = (wc_HashAlg*)XMALLOC(sizeof(wc_HashAlg), NULL, DYNAMIC_TYPE_HASHES); if (hash == NULL) return MEMORY_E; #endif ret = wc_HashInit(hash, type); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } outIdx = out; XMEMSET(counter, 0, sizeof(counter)); for (i = 1; remaining > 0; i++) { IncrementX963KdfCounter(counter); ret = wc_HashUpdate(hash, type, secret, secretSz); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } ret = wc_HashUpdate(hash, type, counter, sizeof(counter)); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } if (sinfo) { ret = wc_HashUpdate(hash, type, sinfo, sinfoSz); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } } ret = wc_HashFinal(hash, type, tmp); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } copySz = min(remaining, digestSz); XMEMCPY(outIdx, tmp, copySz); remaining -= copySz; outIdx += copySz; } #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return 0; } #endif /* HAVE_X963_KDF */ #endif /* HAVE_ECC */
./CrossVul/dataset_final_sorted/CWE-200/c/bad_187_0
crossvul-cpp_data_bad_3824_0
/* xfrm_user.c: User interface to configure xfrm engine. * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * * Changes: * Mitsuru KANDA @USAGI * Kazunori MIYAZAWA @USAGI * Kunihiro Ishiguro <kunihiro@ipinfusion.com> * IPv6 support * */ #include <linux/crypto.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/string.h> #include <linux/net.h> #include <linux/skbuff.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/init.h> #include <linux/security.h> #include <net/sock.h> #include <net/xfrm.h> #include <net/netlink.h> #include <net/ah.h> #include <asm/uaccess.h> #if IS_ENABLED(CONFIG_IPV6) #include <linux/in6.h> #endif static inline int aead_len(struct xfrm_algo_aead *alg) { return sizeof(*alg) + ((alg->alg_key_len + 7) / 8); } static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type) { struct nlattr *rt = attrs[type]; struct xfrm_algo *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < xfrm_alg_len(algp)) return -EINVAL; switch (type) { case XFRMA_ALG_AUTH: case XFRMA_ALG_CRYPT: case XFRMA_ALG_COMP: break; default: return -EINVAL; } algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static int verify_auth_trunc(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC]; struct xfrm_algo_auth *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < xfrm_alg_auth_len(algp)) return -EINVAL; algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static int verify_aead(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_ALG_AEAD]; struct xfrm_algo_aead *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < aead_len(algp)) return -EINVAL; algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type, xfrm_address_t **addrp) { struct nlattr *rt = attrs[type]; if (rt && addrp) *addrp = nla_data(rt); } static inline int verify_sec_ctx_len(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = nla_data(rt); if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len)) return -EINVAL; return 0; } static inline int verify_replay(struct xfrm_usersa_info *p, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL]; if ((p->flags & XFRM_STATE_ESN) && !rt) return -EINVAL; if (!rt) return 0; if (p->id.proto != IPPROTO_ESP) return -EINVAL; if (p->replay_window != 0) return -EINVAL; return 0; } static int verify_newsa_info(struct xfrm_usersa_info *p, struct nlattr **attrs) { int err; err = -EINVAL; switch (p->family) { case AF_INET: break; case AF_INET6: #if IS_ENABLED(CONFIG_IPV6) break; #else err = -EAFNOSUPPORT; goto out; #endif default: goto out; } err = -EINVAL; switch (p->id.proto) { case IPPROTO_AH: if ((!attrs[XFRMA_ALG_AUTH] && !attrs[XFRMA_ALG_AUTH_TRUNC]) || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_ALG_COMP] || attrs[XFRMA_TFCPAD]) goto out; break; case IPPROTO_ESP: if (attrs[XFRMA_ALG_COMP]) goto out; if (!attrs[XFRMA_ALG_AUTH] && !attrs[XFRMA_ALG_AUTH_TRUNC] && !attrs[XFRMA_ALG_CRYPT] && !attrs[XFRMA_ALG_AEAD]) goto out; if ((attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_CRYPT]) && attrs[XFRMA_ALG_AEAD]) goto out; if (attrs[XFRMA_TFCPAD] && p->mode != XFRM_MODE_TUNNEL) goto out; break; case IPPROTO_COMP: if (!attrs[XFRMA_ALG_COMP] || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_TFCPAD]) goto out; break; #if IS_ENABLED(CONFIG_IPV6) case IPPROTO_DSTOPTS: case IPPROTO_ROUTING: if (attrs[XFRMA_ALG_COMP] || attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_ENCAP] || attrs[XFRMA_SEC_CTX] || attrs[XFRMA_TFCPAD] || !attrs[XFRMA_COADDR]) goto out; break; #endif default: goto out; } if ((err = verify_aead(attrs))) goto out; if ((err = verify_auth_trunc(attrs))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP))) goto out; if ((err = verify_sec_ctx_len(attrs))) goto out; if ((err = verify_replay(p, attrs))) goto out; err = -EINVAL; switch (p->mode) { case XFRM_MODE_TRANSPORT: case XFRM_MODE_TUNNEL: case XFRM_MODE_ROUTEOPTIMIZATION: case XFRM_MODE_BEET: break; default: goto out; } err = 0; out: return err; } static int attach_one_algo(struct xfrm_algo **algpp, u8 *props, struct xfrm_algo_desc *(*get_byname)(const char *, int), struct nlattr *rta) { struct xfrm_algo *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); *algpp = p; return 0; } static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo *ualg; struct xfrm_algo_auth *p; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aalg_get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); p->alg_key_len = ualg->alg_key_len; p->alg_trunc_len = algo->uinfo.auth.icv_truncbits; memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8); *algpp = p; return 0; } static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo_auth *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aalg_get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN || ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits) return -EINVAL; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); if (!p->alg_trunc_len) p->alg_trunc_len = algo->uinfo.auth.icv_truncbits; *algpp = p; return 0; } static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo_aead *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); *algpp = p; return 0; } static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; if (!replay_esn || !rp) return 0; up = nla_data(rp); if (xfrm_replay_state_esn_len(replay_esn) != xfrm_replay_state_esn_len(up)) return -EINVAL; return 0; } static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn, struct xfrm_replay_state_esn **preplay_esn, struct nlattr *rta) { struct xfrm_replay_state_esn *p, *pp, *up; if (!rta) return 0; up = nla_data(rta); p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!p) return -ENOMEM; pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!pp) { kfree(p); return -ENOMEM; } *replay_esn = p; *preplay_esn = pp; return 0; } static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx) { int len = 0; if (xfrm_ctx) { len += sizeof(struct xfrm_user_sec_ctx); len += xfrm_ctx->ctx_len; } return len; } static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&x->id, &p->id, sizeof(x->id)); memcpy(&x->sel, &p->sel, sizeof(x->sel)); memcpy(&x->lft, &p->lft, sizeof(x->lft)); x->props.mode = p->mode; x->props.replay_window = p->replay_window; x->props.reqid = p->reqid; x->props.family = p->family; memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr)); x->props.flags = p->flags; if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC)) x->sel.family = p->family; } /* * someday when pfkey also has support, we could have the code * somehow made shareable and move it to xfrm_state.c - JHS * */ static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs) { struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL]; struct nlattr *lt = attrs[XFRMA_LTIME_VAL]; struct nlattr *et = attrs[XFRMA_ETIMER_THRESH]; struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH]; if (re) { struct xfrm_replay_state_esn *replay_esn; replay_esn = nla_data(re); memcpy(x->replay_esn, replay_esn, xfrm_replay_state_esn_len(replay_esn)); memcpy(x->preplay_esn, replay_esn, xfrm_replay_state_esn_len(replay_esn)); } if (rp) { struct xfrm_replay_state *replay; replay = nla_data(rp); memcpy(&x->replay, replay, sizeof(*replay)); memcpy(&x->preplay, replay, sizeof(*replay)); } if (lt) { struct xfrm_lifetime_cur *ltime; ltime = nla_data(lt); x->curlft.bytes = ltime->bytes; x->curlft.packets = ltime->packets; x->curlft.add_time = ltime->add_time; x->curlft.use_time = ltime->use_time; } if (et) x->replay_maxage = nla_get_u32(et); if (rt) x->replay_maxdiff = nla_get_u32(rt); } static struct xfrm_state *xfrm_state_construct(struct net *net, struct xfrm_usersa_info *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = xfrm_state_alloc(net); int err = -ENOMEM; if (!x) goto error_no_put; copy_from_user_state(x, p); if ((err = attach_aead(&x->aead, &x->props.ealgo, attrs[XFRMA_ALG_AEAD]))) goto error; if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH_TRUNC]))) goto error; if (!x->props.aalgo) { if ((err = attach_auth(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH]))) goto error; } if ((err = attach_one_algo(&x->ealg, &x->props.ealgo, xfrm_ealg_get_byname, attrs[XFRMA_ALG_CRYPT]))) goto error; if ((err = attach_one_algo(&x->calg, &x->props.calgo, xfrm_calg_get_byname, attrs[XFRMA_ALG_COMP]))) goto error; if (attrs[XFRMA_ENCAP]) { x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]), sizeof(*x->encap), GFP_KERNEL); if (x->encap == NULL) goto error; } if (attrs[XFRMA_TFCPAD]) x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]); if (attrs[XFRMA_COADDR]) { x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]), sizeof(*x->coaddr), GFP_KERNEL); if (x->coaddr == NULL) goto error; } xfrm_mark_get(attrs, &x->mark); err = __xfrm_init_state(x, false); if (err) goto error; if (attrs[XFRMA_SEC_CTX] && security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX]))) goto error; if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn, attrs[XFRMA_REPLAY_ESN_VAL]))) goto error; x->km.seq = p->seq; x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth; /* sysctl_xfrm_aevent_etime is in 100ms units */ x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M; if ((err = xfrm_init_replay(x))) goto error; /* override default values from above */ xfrm_update_ae_params(x, attrs); return x; error: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); error_no_put: *errp = err; return NULL; } static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_usersa_info *p = nlmsg_data(nlh); struct xfrm_state *x; int err; struct km_event c; uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; err = verify_newsa_info(p, attrs); if (err) return err; x = xfrm_state_construct(net, p, attrs, &err); if (!x) return err; xfrm_state_hold(x); if (nlh->nlmsg_type == XFRM_MSG_NEWSA) err = xfrm_state_add(x); else err = xfrm_state_update(x); security_task_getsecid(current, &sid); xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static struct xfrm_state *xfrm_user_state_lookup(struct net *net, struct xfrm_usersa_id *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = NULL; struct xfrm_mark m; int err; u32 mark = xfrm_mark_get(attrs, &m); if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) { err = -ESRCH; x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family); } else { xfrm_address_t *saddr = NULL; verify_one_addr(attrs, XFRMA_SRCADDR, &saddr); if (!saddr) { err = -EINVAL; goto out; } err = -ESRCH; x = xfrm_state_lookup_byaddr(net, mark, &p->daddr, saddr, p->proto, p->family); } out: if (!x && errp) *errp = err; return x; } static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; int err = -ESRCH; struct km_event c; struct xfrm_usersa_id *p = nlmsg_data(nlh); uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; x = xfrm_user_state_lookup(net, p, attrs, &err); if (x == NULL) return err; if ((err = security_xfrm_state_delete(x)) != 0) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: security_task_getsecid(current, &sid); xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid); xfrm_state_put(x); return err; } static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memset(p, 0, sizeof(*p)); memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } struct xfrm_dump_info { struct sk_buff *in_skb; struct sk_buff *out_skb; u32 nlmsg_seq; u16 nlmsg_flags; }; static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb) { struct xfrm_user_sec_ctx *uctx; struct nlattr *attr; int ctx_size = sizeof(*uctx) + s->ctx_len; attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size); if (attr == NULL) return -EMSGSIZE; uctx = nla_data(attr); uctx->exttype = XFRMA_SEC_CTX; uctx->len = ctx_size; uctx->ctx_doi = s->ctx_doi; uctx->ctx_alg = s->ctx_alg; uctx->ctx_len = s->ctx_len; memcpy(uctx + 1, s->ctx_str, s->ctx_len); return 0; } static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb) { struct xfrm_algo *algo; struct nlattr *nla; nla = nla_reserve(skb, XFRMA_ALG_AUTH, sizeof(*algo) + (auth->alg_key_len + 7) / 8); if (!nla) return -EMSGSIZE; algo = nla_data(nla); strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name)); memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8); algo->alg_key_len = auth->alg_key_len; return 0; } /* Don't change this without updating xfrm_sa_len! */ static int copy_to_user_state_extra(struct xfrm_state *x, struct xfrm_usersa_info *p, struct sk_buff *skb) { int ret = 0; copy_to_user_state(x, p); if (x->coaddr) { ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr); if (ret) goto out; } if (x->lastused) { ret = nla_put_u64(skb, XFRMA_LASTUSED, x->lastused); if (ret) goto out; } if (x->aead) { ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead); if (ret) goto out; } if (x->aalg) { ret = copy_to_user_auth(x->aalg, skb); if (!ret) ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC, xfrm_alg_auth_len(x->aalg), x->aalg); if (ret) goto out; } if (x->ealg) { ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg); if (ret) goto out; } if (x->calg) { ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg); if (ret) goto out; } if (x->encap) { ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap); if (ret) goto out; } if (x->tfcpad) { ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad); if (ret) goto out; } ret = xfrm_mark_put(skb, &x->mark); if (ret) goto out; if (x->replay_esn) { ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL, xfrm_replay_state_esn_len(x->replay_esn), x->replay_esn); if (ret) goto out; } if (x->security) ret = copy_sec_ctx(x->security, skb); out: return ret; } static int dump_one_state(struct xfrm_state *x, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct xfrm_usersa_info *p; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags); if (nlh == NULL) return -EMSGSIZE; p = nlmsg_data(nlh); err = copy_to_user_state_extra(x, p, skb); if (err) { nlmsg_cancel(skb, nlh); return err; } nlmsg_end(skb, nlh); return 0; } static int xfrm_dump_sa_done(struct netlink_callback *cb) { struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1]; xfrm_state_walk_done(walk); return 0; } static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_state_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_state_walk_init(walk, 0); } (void) xfrm_state_walk(net, walk, dump_one_state, &info); return skb->len; } static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb, struct xfrm_state *x, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; int err; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; err = dump_one_state(x, 0, &info); if (err) { kfree_skb(skb); return ERR_PTR(err); } return skb; } static inline size_t xfrm_spdinfo_msgsize(void) { return NLMSG_ALIGN(4) + nla_total_size(sizeof(struct xfrmu_spdinfo)) + nla_total_size(sizeof(struct xfrmu_spdhinfo)); } static int build_spdinfo(struct sk_buff *skb, struct net *net, u32 pid, u32 seq, u32 flags) { struct xfrmk_spdinfo si; struct xfrmu_spdinfo spc; struct xfrmu_spdhinfo sph; struct nlmsghdr *nlh; int err; u32 *f; nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0); if (nlh == NULL) /* shouldn't really happen ... */ return -EMSGSIZE; f = nlmsg_data(nlh); *f = flags; xfrm_spd_getinfo(net, &si); spc.incnt = si.incnt; spc.outcnt = si.outcnt; spc.fwdcnt = si.fwdcnt; spc.inscnt = si.inscnt; spc.outscnt = si.outscnt; spc.fwdscnt = si.fwdscnt; sph.spdhcnt = si.spdhcnt; sph.spdhmcnt = si.spdhmcnt; err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc); if (!err) err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct sk_buff *r_skb; u32 *flags = nlmsg_data(nlh); u32 spid = NETLINK_CB(skb).pid; u32 seq = nlh->nlmsg_seq; r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC); if (r_skb == NULL) return -ENOMEM; if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0) BUG(); return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid); } static inline size_t xfrm_sadinfo_msgsize(void) { return NLMSG_ALIGN(4) + nla_total_size(sizeof(struct xfrmu_sadhinfo)) + nla_total_size(4); /* XFRMA_SAD_CNT */ } static int build_sadinfo(struct sk_buff *skb, struct net *net, u32 pid, u32 seq, u32 flags) { struct xfrmk_sadinfo si; struct xfrmu_sadhinfo sh; struct nlmsghdr *nlh; int err; u32 *f; nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0); if (nlh == NULL) /* shouldn't really happen ... */ return -EMSGSIZE; f = nlmsg_data(nlh); *f = flags; xfrm_sad_getinfo(net, &si); sh.sadhmcnt = si.sadhmcnt; sh.sadhcnt = si.sadhcnt; err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt); if (!err) err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct sk_buff *r_skb; u32 *flags = nlmsg_data(nlh); u32 spid = NETLINK_CB(skb).pid; u32 seq = nlh->nlmsg_seq; r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC); if (r_skb == NULL) return -ENOMEM; if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0) BUG(); return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid); } static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_usersa_id *p = nlmsg_data(nlh); struct xfrm_state *x; struct sk_buff *resp_skb; int err = -ESRCH; x = xfrm_user_state_lookup(net, p, attrs, &err); if (x == NULL) goto out_noput; resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); } xfrm_state_put(x); out_noput: return err; } static int verify_userspi_info(struct xfrm_userspi_info *p) { switch (p->info.id.proto) { case IPPROTO_AH: case IPPROTO_ESP: break; case IPPROTO_COMP: /* IPCOMP spi is 16-bits. */ if (p->max >= 0x10000) return -EINVAL; break; default: return -EINVAL; } if (p->min > p->max) return -EINVAL; return 0; } static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct xfrm_userspi_info *p; struct sk_buff *resp_skb; xfrm_address_t *daddr; int family; int err; u32 mark; struct xfrm_mark m; p = nlmsg_data(nlh); err = verify_userspi_info(p); if (err) goto out_noput; family = p->info.family; daddr = &p->info.id.daddr; x = NULL; mark = xfrm_mark_get(attrs, &m); if (p->info.seq) { x = xfrm_find_acq_byseq(net, mark, p->info.seq); if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid, p->info.id.proto, daddr, &p->info.saddr, 1, family); err = -ENOENT; if (x == NULL) goto out_noput; err = xfrm_alloc_spi(x, p->min, p->max); if (err) goto out; resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); goto out; } err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); out: xfrm_state_put(x); out_noput: return err; } static int verify_policy_dir(u8 dir) { switch (dir) { case XFRM_POLICY_IN: case XFRM_POLICY_OUT: case XFRM_POLICY_FWD: break; default: return -EINVAL; } return 0; } static int verify_policy_type(u8 type) { switch (type) { case XFRM_POLICY_TYPE_MAIN: #ifdef CONFIG_XFRM_SUB_POLICY case XFRM_POLICY_TYPE_SUB: #endif break; default: return -EINVAL; } return 0; } static int verify_newpolicy_info(struct xfrm_userpolicy_info *p) { switch (p->share) { case XFRM_SHARE_ANY: case XFRM_SHARE_SESSION: case XFRM_SHARE_USER: case XFRM_SHARE_UNIQUE: break; default: return -EINVAL; } switch (p->action) { case XFRM_POLICY_ALLOW: case XFRM_POLICY_BLOCK: break; default: return -EINVAL; } switch (p->sel.family) { case AF_INET: break; case AF_INET6: #if IS_ENABLED(CONFIG_IPV6) break; #else return -EAFNOSUPPORT; #endif default: return -EINVAL; } return verify_policy_dir(p->dir); } static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = nla_data(rt); return security_xfrm_policy_alloc(&pol->security, uctx); } static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut, int nr) { int i; xp->xfrm_nr = nr; for (i = 0; i < nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&t->id, &ut->id, sizeof(struct xfrm_id)); memcpy(&t->saddr, &ut->saddr, sizeof(xfrm_address_t)); t->reqid = ut->reqid; t->mode = ut->mode; t->share = ut->share; t->optional = ut->optional; t->aalgos = ut->aalgos; t->ealgos = ut->ealgos; t->calgos = ut->calgos; /* If all masks are ~0, then we allow all algorithms. */ t->allalgs = !~(t->aalgos & t->ealgos & t->calgos); t->encap_family = ut->family; } } static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family) { int i; if (nr > XFRM_MAX_DEPTH) return -EINVAL; for (i = 0; i < nr; i++) { /* We never validated the ut->family value, so many * applications simply leave it at zero. The check was * never made and ut->family was ignored because all * templates could be assumed to have the same family as * the policy itself. Now that we will have ipv4-in-ipv6 * and ipv6-in-ipv4 tunnels, this is no longer true. */ if (!ut[i].family) ut[i].family = family; switch (ut[i].family) { case AF_INET: break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: break; #endif default: return -EINVAL; } } return 0; } static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_TMPL]; if (!rt) { pol->xfrm_nr = 0; } else { struct xfrm_user_tmpl *utmpl = nla_data(rt); int nr = nla_len(rt) / sizeof(*utmpl); int err; err = validate_tmpl(nr, utmpl, pol->family); if (err) return err; copy_templates(pol, utmpl, nr); } return 0; } static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_POLICY_TYPE]; struct xfrm_userpolicy_type *upt; u8 type = XFRM_POLICY_TYPE_MAIN; int err; if (rt) { upt = nla_data(rt); type = upt->type; } err = verify_policy_type(type); if (err) return err; *tp = type; return 0; } static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p) { xp->priority = p->priority; xp->index = p->index; memcpy(&xp->selector, &p->sel, sizeof(xp->selector)); memcpy(&xp->lft, &p->lft, sizeof(xp->lft)); xp->action = p->action; xp->flags = p->flags; xp->family = p->sel.family; /* XXX xp->share = p->share; */ } static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir) { memcpy(&p->sel, &xp->selector, sizeof(p->sel)); memcpy(&p->lft, &xp->lft, sizeof(p->lft)); memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft)); p->priority = xp->priority; p->index = xp->index; p->sel.family = xp->family; p->dir = dir; p->action = xp->action; p->flags = xp->flags; p->share = XFRM_SHARE_ANY; /* XXX xp->share */ } static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp) { struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL); int err; if (!xp) { *errp = -ENOMEM; return NULL; } copy_from_user_policy(xp, p); err = copy_from_user_policy_type(&xp->type, attrs); if (err) goto error; if (!(err = copy_from_user_tmpl(xp, attrs))) err = copy_from_user_sec_ctx(xp, attrs); if (err) goto error; xfrm_mark_get(attrs, &xp->mark); return xp; error: *errp = err; xp->walk.dead = 1; xfrm_policy_destroy(xp); return NULL; } static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_userpolicy_info *p = nlmsg_data(nlh); struct xfrm_policy *xp; struct km_event c; int err; int excl; uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; err = verify_newpolicy_info(p); if (err) return err; err = verify_sec_ctx_len(attrs); if (err) return err; xp = xfrm_policy_construct(net, p, attrs, &err); if (!xp) return err; /* shouldn't excl be based on nlh flags?? * Aha! this is anti-netlink really i.e more pfkey derived * in netlink excl is a flag and you wouldnt need * a type XFRM_MSG_UPDPOLICY - JHS */ excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY; err = xfrm_policy_insert(p->dir, xp, excl); security_task_getsecid(current, &sid); xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid); if (err) { security_xfrm_policy_free(xp->security); kfree(xp); return err; } c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); xfrm_pol_put(xp); return 0; } static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = kp->encap_family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } return nla_put(skb, XFRMA_TMPL, sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec); } static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb) { if (x->security) { return copy_sec_ctx(x->security, skb); } return 0; } static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb) { if (xp->security) return copy_sec_ctx(xp->security, skb); return 0; } static inline size_t userpolicy_type_attrsize(void) { #ifdef CONFIG_XFRM_SUB_POLICY return nla_total_size(sizeof(struct xfrm_userpolicy_type)); #else return 0; #endif } #ifdef CONFIG_XFRM_SUB_POLICY static int copy_to_user_policy_type(u8 type, struct sk_buff *skb) { struct xfrm_userpolicy_type upt = { .type = type, }; return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt); } #else static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb) { return 0; } #endif static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct xfrm_userpolicy_info *p; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags); if (nlh == NULL) return -EMSGSIZE; p = nlmsg_data(nlh); copy_to_user_policy(xp, p, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_sec_ctx(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } nlmsg_end(skb, nlh); return 0; } static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; xfrm_policy_walk_done(walk); return 0; } static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY); } (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; } static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb, struct xfrm_policy *xp, int dir, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; int err; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; err = dump_one_policy(xp, dir, 0, &info); if (err) { kfree_skb(skb); return ERR_PTR(err); } return skb; } static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_userpolicy_id *p; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct km_event c; int delete; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); p = nlmsg_data(nlh); delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY; err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = verify_policy_dir(p->dir); if (err) return err; if (p->index) xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err); else { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_sec_ctx *ctx; err = verify_sec_ctx_len(attrs); if (err) return err; ctx = NULL; if (rt) { struct xfrm_user_sec_ctx *uctx = nla_data(rt); err = security_xfrm_policy_alloc(&ctx, uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel, ctx, delete, &err); security_xfrm_policy_free(ctx); } if (xp == NULL) return -ENOENT; if (!delete) { struct sk_buff *resp_skb; resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); } } else { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid, sid); if (err != 0) goto out; c.data.byid = p->index; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); } out: xfrm_pol_put(xp); return err; } static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; struct xfrm_usersa_flush *p = nlmsg_data(nlh); struct xfrm_audit audit_info; int err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_state_flush(net, p->proto, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.proto = p->proto; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_state_notify(NULL, &c); return 0; } static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x) { size_t replay_size = x->replay_esn ? xfrm_replay_state_esn_len(x->replay_esn) : sizeof(struct xfrm_replay_state); return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id)) + nla_total_size(replay_size) + nla_total_size(sizeof(struct xfrm_lifetime_cur)) + nla_total_size(sizeof(struct xfrm_mark)) + nla_total_size(4) /* XFRM_AE_RTHR */ + nla_total_size(4); /* XFRM_AE_ETHR */ } static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c) { struct xfrm_aevent_id *id; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0); if (nlh == NULL) return -EMSGSIZE; id = nlmsg_data(nlh); memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr)); id->sa_id.spi = x->id.spi; id->sa_id.family = x->props.family; id->sa_id.proto = x->id.proto; memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr)); id->reqid = x->props.reqid; id->flags = c->data.aevent; if (x->replay_esn) { err = nla_put(skb, XFRMA_REPLAY_ESN_VAL, xfrm_replay_state_esn_len(x->replay_esn), x->replay_esn); } else { err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay), &x->replay); } if (err) goto out_cancel; err = nla_put(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft); if (err) goto out_cancel; if (id->flags & XFRM_AE_RTHR) { err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff); if (err) goto out_cancel; } if (id->flags & XFRM_AE_ETHR) { err = nla_put_u32(skb, XFRMA_ETIMER_THRESH, x->replay_maxage * 10 / HZ); if (err) goto out_cancel; } err = xfrm_mark_put(skb, &x->mark); if (err) goto out_cancel; return nlmsg_end(skb, nlh); out_cancel: nlmsg_cancel(skb, nlh); return err; } static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct sk_buff *r_skb; int err; struct km_event c; u32 mark; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct xfrm_usersa_id *id = &p->sa_id; mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family); if (x == NULL) return -ESRCH; r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC); if (r_skb == NULL) { xfrm_state_put(x); return -ENOMEM; } /* * XXX: is this lock really needed - none of the other * gets lock (the concern is things getting updated * while we are still reading) - jhs */ spin_lock_bh(&x->lock); c.data.aevent = p->flags; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; if (build_aevent(r_skb, x, &c) < 0) BUG(); err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid); spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct km_event c; int err = - EINVAL; u32 mark = 0; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL]; struct nlattr *lt = attrs[XFRMA_LTIME_VAL]; if (!lt && !rp && !re) return err; /* pedantic mode - thou shalt sayeth replaceth */ if (!(nlh->nlmsg_flags&NLM_F_REPLACE)) return err; mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family); if (x == NULL) return -ESRCH; if (x->km.state != XFRM_STATE_VALID) goto out; err = xfrm_replay_verify_len(x->replay_esn, rp); if (err) goto out; spin_lock_bh(&x->lock); xfrm_update_ae_params(x, attrs); spin_unlock_bh(&x->lock); c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.data.aevent = XFRM_AE_CU; km_state_notify(x, &c); err = 0; out: xfrm_state_put(x); return err; } static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct xfrm_audit audit_info; err = copy_from_user_policy_type(&type, attrs); if (err) return err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_policy_flush(net, type, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.type = type; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_user_polexpire *up = nlmsg_data(nlh); struct xfrm_userpolicy_info *p = &up->pol; u8 type = XFRM_POLICY_TYPE_MAIN; int err = -ENOENT; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = verify_policy_dir(p->dir); if (err) return err; if (p->index) xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err); else { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_sec_ctx *ctx; err = verify_sec_ctx_len(attrs); if (err) return err; ctx = NULL; if (rt) { struct xfrm_user_sec_ctx *uctx = nla_data(rt); err = security_xfrm_policy_alloc(&ctx, uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel, ctx, 0, &err); security_xfrm_policy_free(ctx); } if (xp == NULL) return -ENOENT; if (unlikely(xp->walk.dead)) goto out; err = 0; if (up->hard) { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); xfrm_policy_delete(xp, p->dir); xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid); } else { // reset the timers here? WARN(1, "Dont know what to do with soft policy expire\n"); } km_policy_expired(xp, p->dir, up->hard, current->pid); out: xfrm_pol_put(xp); return err; } static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; int err; struct xfrm_user_expire *ue = nlmsg_data(nlh); struct xfrm_usersa_info *p = &ue->state; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family); err = -ENOENT; if (x == NULL) return err; spin_lock_bh(&x->lock); err = -EINVAL; if (x->km.state != XFRM_STATE_VALID) goto out; km_state_expired(x, ue->hard, current->pid); if (ue->hard) { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); __xfrm_state_delete(x); xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid); } err = 0; out: spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_user_tmpl *ut; int i; struct nlattr *rt = attrs[XFRMA_TMPL]; struct xfrm_mark mark; struct xfrm_user_acquire *ua = nlmsg_data(nlh); struct xfrm_state *x = xfrm_state_alloc(net); int err = -ENOMEM; if (!x) goto nomem; xfrm_mark_get(attrs, &mark); err = verify_newpolicy_info(&ua->policy); if (err) goto bad_policy; /* build an XP */ xp = xfrm_policy_construct(net, &ua->policy, attrs, &err); if (!xp) goto free_state; memcpy(&x->id, &ua->id, sizeof(ua->id)); memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr)); memcpy(&x->sel, &ua->sel, sizeof(ua->sel)); xp->mark.m = x->mark.m = mark.m; xp->mark.v = x->mark.v = mark.v; ut = nla_data(rt); /* extract the templates and for each call km_key */ for (i = 0; i < xp->xfrm_nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&x->id, &t->id, sizeof(x->id)); x->props.mode = t->mode; x->props.reqid = t->reqid; x->props.family = ut->family; t->aalgos = ua->aalgos; t->ealgos = ua->ealgos; t->calgos = ua->calgos; err = km_query(x, t, xp); } kfree(x); kfree(xp); return 0; bad_policy: WARN(1, "BAD policy passed\n"); free_state: kfree(x); nomem: return err; } #ifdef CONFIG_XFRM_MIGRATE static int copy_from_user_migrate(struct xfrm_migrate *ma, struct xfrm_kmaddress *k, struct nlattr **attrs, int *num) { struct nlattr *rt = attrs[XFRMA_MIGRATE]; struct xfrm_user_migrate *um; int i, num_migrate; if (k != NULL) { struct xfrm_user_kmaddress *uk; uk = nla_data(attrs[XFRMA_KMADDRESS]); memcpy(&k->local, &uk->local, sizeof(k->local)); memcpy(&k->remote, &uk->remote, sizeof(k->remote)); k->family = uk->family; k->reserved = uk->reserved; } um = nla_data(rt); num_migrate = nla_len(rt) / sizeof(*um); if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH) return -EINVAL; for (i = 0; i < num_migrate; i++, um++, ma++) { memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr)); memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr)); memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr)); memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr)); ma->proto = um->proto; ma->mode = um->mode; ma->reqid = um->reqid; ma->old_family = um->old_family; ma->new_family = um->new_family; } *num = i; return 0; } static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct xfrm_userpolicy_id *pi = nlmsg_data(nlh); struct xfrm_migrate m[XFRM_MAX_DEPTH]; struct xfrm_kmaddress km, *kmp; u8 type; int err; int n = 0; if (attrs[XFRMA_MIGRATE] == NULL) return -EINVAL; kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL; err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n); if (err) return err; if (!n) return 0; xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp); return 0; } #else static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { return -ENOPROTOOPT; } #endif #ifdef CONFIG_XFRM_MIGRATE static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb) { struct xfrm_user_migrate um; memset(&um, 0, sizeof(um)); um.proto = m->proto; um.mode = m->mode; um.reqid = m->reqid; um.old_family = m->old_family; memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr)); memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr)); um.new_family = m->new_family; memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr)); memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr)); return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um); } static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb) { struct xfrm_user_kmaddress uk; memset(&uk, 0, sizeof(uk)); uk.family = k->family; uk.reserved = k->reserved; memcpy(&uk.local, &k->local, sizeof(uk.local)); memcpy(&uk.remote, &k->remote, sizeof(uk.remote)); return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk); } static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma) { return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id)) + (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0) + nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate) + userpolicy_type_attrsize(); } static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k, const struct xfrm_selector *sel, u8 dir, u8 type) { const struct xfrm_migrate *mp; struct xfrm_userpolicy_id *pol_id; struct nlmsghdr *nlh; int i, err; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0); if (nlh == NULL) return -EMSGSIZE; pol_id = nlmsg_data(nlh); /* copy data from selector, dir, and type to the pol_id */ memset(pol_id, 0, sizeof(*pol_id)); memcpy(&pol_id->sel, sel, sizeof(pol_id->sel)); pol_id->dir = dir; if (k != NULL) { err = copy_to_user_kmaddress(k, skb); if (err) goto out_cancel; } err = copy_to_user_policy_type(type, skb); if (err) goto out_cancel; for (i = 0, mp = m ; i < num_migrate; i++, mp++) { err = copy_to_user_migrate(mp, skb); if (err) goto out_cancel; } return nlmsg_end(skb, nlh); out_cancel: nlmsg_cancel(skb, nlh); return err; } static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k) { struct net *net = &init_net; struct sk_buff *skb; skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; /* build migrate */ if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC); } #else static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k) { return -ENOPROTOOPT; } #endif #define XMSGSIZE(type) sizeof(struct type) static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info), [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire), [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire), [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire), [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush), [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0, [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), [XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), [XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report), [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32), [XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32), }; #undef XMSGSIZE static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = { [XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)}, [XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)}, [XFRMA_LASTUSED] = { .type = NLA_U64}, [XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)}, [XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) }, [XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) }, [XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) }, [XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) }, [XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) }, [XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) }, [XFRMA_REPLAY_THRESH] = { .type = NLA_U32 }, [XFRMA_ETIMER_THRESH] = { .type = NLA_U32 }, [XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) }, [XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) }, [XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)}, [XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) }, [XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) }, [XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) }, [XFRMA_TFCPAD] = { .type = NLA_U32 }, [XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) }, }; static struct xfrm_link { int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **); int (*dump)(struct sk_buff *, struct netlink_callback *); int (*done)(struct netlink_callback *); } xfrm_dispatch[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa }, [XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa, .dump = xfrm_dump_sa, .done = xfrm_dump_sa_done }, [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy }, [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy, .dump = xfrm_dump_policy, .done = xfrm_dump_policy_done }, [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi }, [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire }, [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire }, [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire}, [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa }, [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy }, [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae }, [XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae }, [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate }, [XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo }, [XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo }, }; static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct nlattr *attrs[XFRMA_MAX+1]; struct xfrm_link *link; int type, err; type = nlh->nlmsg_type; if (type > XFRM_MSG_MAX) return -EINVAL; type -= XFRM_MSG_BASE; link = &xfrm_dispatch[type]; /* All operations require privileges, even GET */ if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) || type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) && (nlh->nlmsg_flags & NLM_F_DUMP)) { if (link->dump == NULL) return -EINVAL; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, }; return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c); } } err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX, xfrma_policy); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } static void xfrm_netlink_rcv(struct sk_buff *skb) { mutex_lock(&xfrm_cfg_mutex); netlink_rcv_skb(skb, &xfrm_user_rcv_msg); mutex_unlock(&xfrm_cfg_mutex); } static inline size_t xfrm_expire_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_expire)) + nla_total_size(sizeof(struct xfrm_mark)); } static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c) { struct xfrm_user_expire *ue; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0); if (nlh == NULL) return -EMSGSIZE; ue = nlmsg_data(nlh); copy_to_user_state(x, &ue->state); ue->hard = (c->data.hard != 0) ? 1 : 0; err = xfrm_mark_put(skb, &x->mark); if (err) return err; return nlmsg_end(skb, nlh); } static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_expire(skb, x, c) < 0) { kfree_skb(skb); return -EMSGSIZE; } return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_aevent(skb, x, c) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC); } static int xfrm_notify_sa_flush(const struct km_event *c) { struct net *net = c->net; struct xfrm_usersa_flush *p; struct nlmsghdr *nlh; struct sk_buff *skb; int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush)); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0); if (nlh == NULL) { kfree_skb(skb); return -EMSGSIZE; } p = nlmsg_data(nlh); p->proto = c->data.proto; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); } static inline size_t xfrm_sa_len(struct xfrm_state *x) { size_t l = 0; if (x->aead) l += nla_total_size(aead_len(x->aead)); if (x->aalg) { l += nla_total_size(sizeof(struct xfrm_algo) + (x->aalg->alg_key_len + 7) / 8); l += nla_total_size(xfrm_alg_auth_len(x->aalg)); } if (x->ealg) l += nla_total_size(xfrm_alg_len(x->ealg)); if (x->calg) l += nla_total_size(sizeof(*x->calg)); if (x->encap) l += nla_total_size(sizeof(*x->encap)); if (x->tfcpad) l += nla_total_size(sizeof(x->tfcpad)); if (x->replay_esn) l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn)); if (x->security) l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) + x->security->ctx_len); if (x->coaddr) l += nla_total_size(sizeof(*x->coaddr)); /* Must count x->lastused as it may become non-zero behind our back. */ l += nla_total_size(sizeof(u64)); return l; } static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct xfrm_usersa_info *p; struct xfrm_usersa_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; int len = xfrm_sa_len(x); int headlen, err; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELSA) { len += nla_total_size(headlen); headlen = sizeof(*id); len += nla_total_size(sizeof(struct xfrm_mark)); } len += NLMSG_ALIGN(headlen); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; p = nlmsg_data(nlh); if (c->event == XFRM_MSG_DELSA) { struct nlattr *attr; id = nlmsg_data(nlh); memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr)); id->spi = x->id.spi; id->family = x->props.family; id->proto = x->id.proto; attr = nla_reserve(skb, XFRMA_SA, sizeof(*p)); err = -EMSGSIZE; if (attr == NULL) goto out_free_skb; p = nla_data(attr); } err = copy_to_user_state_extra(x, p, skb); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c) { switch (c->event) { case XFRM_MSG_EXPIRE: return xfrm_exp_state_notify(x, c); case XFRM_MSG_NEWAE: return xfrm_aevent_state_notify(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_UPDSA: case XFRM_MSG_NEWSA: return xfrm_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return xfrm_notify_sa_flush(c); default: printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n", c->event); break; } return 0; } static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x, struct xfrm_policy *xp) { return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire)) + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr) + nla_total_size(sizeof(struct xfrm_mark)) + nla_total_size(xfrm_user_sec_ctx_size(x->security)) + userpolicy_type_attrsize(); } static int build_acquire(struct sk_buff *skb, struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { __u32 seq = xfrm_get_acqseq(); struct xfrm_user_acquire *ua; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0); if (nlh == NULL) return -EMSGSIZE; ua = nlmsg_data(nlh); memcpy(&ua->id, &x->id, sizeof(ua->id)); memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr)); memcpy(&ua->sel, &x->sel, sizeof(ua->sel)); copy_to_user_policy(xp, &ua->policy, dir); ua->aalgos = xt->aalgos; ua->ealgos = xt->ealgos; ua->calgos = xt->calgos; ua->seq = x->km.seq = seq; err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_state_sec_ctx(x, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_acquire(skb, x, xt, xp, dir) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC); } /* User gives us xfrm_user_policy_info followed by an array of 0 * or more templates. */ static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt, u8 *data, int len, int *dir) { struct net *net = sock_net(sk); struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data; struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1); struct xfrm_policy *xp; int nr; switch (sk->sk_family) { case AF_INET: if (opt != IP_XFRM_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: if (opt != IPV6_XFRM_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(*p) || verify_newpolicy_info(p)) return NULL; nr = ((len - sizeof(*p)) / sizeof(*ut)); if (validate_tmpl(nr, ut, p->sel.family)) return NULL; if (p->dir > XFRM_POLICY_OUT) return NULL; xp = xfrm_policy_alloc(net, GFP_ATOMIC); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } copy_from_user_policy(xp, p); xp->type = XFRM_POLICY_TYPE_MAIN; copy_templates(xp, ut, nr); *dir = p->dir; return xp; } static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp) { return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire)) + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr) + nla_total_size(xfrm_user_sec_ctx_size(xp->security)) + nla_total_size(sizeof(struct xfrm_mark)) + userpolicy_type_attrsize(); } static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp, int dir, const struct km_event *c) { struct xfrm_user_polexpire *upe; int hard = c->data.hard; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0); if (nlh == NULL) return -EMSGSIZE; upe = nlmsg_data(nlh); copy_to_user_policy(xp, &upe->pol, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_sec_ctx(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } upe->hard = !!hard; return nlmsg_end(skb, nlh); } static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { struct net *net = xp_net(xp); struct sk_buff *skb; skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_polexpire(skb, xp, dir, c) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c) { int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr); struct net *net = xp_net(xp); struct xfrm_userpolicy_info *p; struct xfrm_userpolicy_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; int headlen, err; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELPOLICY) { len += nla_total_size(headlen); headlen = sizeof(*id); } len += userpolicy_type_attrsize(); len += nla_total_size(sizeof(struct xfrm_mark)); len += NLMSG_ALIGN(headlen); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; p = nlmsg_data(nlh); if (c->event == XFRM_MSG_DELPOLICY) { struct nlattr *attr; id = nlmsg_data(nlh); memset(id, 0, sizeof(*id)); id->dir = dir; if (c->data.byid) id->index = xp->index; else memcpy(&id->sel, &xp->selector, sizeof(id->sel)); attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p)); err = -EMSGSIZE; if (attr == NULL) goto out_free_skb; p = nla_data(attr); } copy_to_user_policy(xp, p, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_notify_policy_flush(const struct km_event *c) { struct net *net = c->net; struct nlmsghdr *nlh; struct sk_buff *skb; int err; skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; err = copy_to_user_policy_type(c->data.type, skb); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { switch (c->event) { case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: case XFRM_MSG_DELPOLICY: return xfrm_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: return xfrm_notify_policy_flush(c); case XFRM_MSG_POLEXPIRE: return xfrm_exp_policy_notify(xp, dir, c); default: printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n", c->event); } return 0; } static inline size_t xfrm_report_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_report)); } static int build_report(struct sk_buff *skb, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct xfrm_user_report *ur; struct nlmsghdr *nlh; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0); if (nlh == NULL) return -EMSGSIZE; ur = nlmsg_data(nlh); ur->proto = proto; memcpy(&ur->sel, sel, sizeof(ur->sel)); if (addr) { int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr); if (err) { nlmsg_cancel(skb, nlh); return err; } } return nlmsg_end(skb, nlh); } static int xfrm_send_report(struct net *net, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct sk_buff *skb; skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_report(skb, proto, sel, addr) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC); } static inline size_t xfrm_mapping_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping)); } static int build_mapping(struct sk_buff *skb, struct xfrm_state *x, xfrm_address_t *new_saddr, __be16 new_sport) { struct xfrm_user_mapping *um; struct nlmsghdr *nlh; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0); if (nlh == NULL) return -EMSGSIZE; um = nlmsg_data(nlh); memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr)); um->id.spi = x->id.spi; um->id.family = x->props.family; um->id.proto = x->id.proto; memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr)); memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr)); um->new_sport = new_sport; um->old_sport = x->encap->encap_sport; um->reqid = x->props.reqid; return nlmsg_end(skb, nlh); } static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport) { struct net *net = xs_net(x); struct sk_buff *skb; if (x->id.proto != IPPROTO_ESP) return -EINVAL; if (!x->encap) return -EINVAL; skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_mapping(skb, x, ipaddr, sport) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC); } static struct xfrm_mgr netlink_mgr = { .id = "netlink", .notify = xfrm_send_state_notify, .acquire = xfrm_send_acquire, .compile_policy = xfrm_compile_policy, .notify_policy = xfrm_send_policy_notify, .report = xfrm_send_report, .migrate = xfrm_send_migrate, .new_mapping = xfrm_send_mapping, }; static int __net_init xfrm_user_net_init(struct net *net) { struct sock *nlsk; struct netlink_kernel_cfg cfg = { .groups = XFRMNLGRP_MAX, .input = xfrm_netlink_rcv, }; nlsk = netlink_kernel_create(net, NETLINK_XFRM, THIS_MODULE, &cfg); if (nlsk == NULL) return -ENOMEM; net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */ rcu_assign_pointer(net->xfrm.nlsk, nlsk); return 0; } static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list) { struct net *net; list_for_each_entry(net, net_exit_list, exit_list) RCU_INIT_POINTER(net->xfrm.nlsk, NULL); synchronize_net(); list_for_each_entry(net, net_exit_list, exit_list) netlink_kernel_release(net->xfrm.nlsk_stash); } static struct pernet_operations xfrm_user_net_ops = { .init = xfrm_user_net_init, .exit_batch = xfrm_user_net_exit, }; static int __init xfrm_user_init(void) { int rv; printk(KERN_INFO "Initializing XFRM netlink socket\n"); rv = register_pernet_subsys(&xfrm_user_net_ops); if (rv < 0) return rv; rv = xfrm_register_km(&netlink_mgr); if (rv < 0) unregister_pernet_subsys(&xfrm_user_net_ops); return rv; } static void __exit xfrm_user_exit(void) { xfrm_unregister_km(&netlink_mgr); unregister_pernet_subsys(&xfrm_user_net_ops); } module_init(xfrm_user_init); module_exit(xfrm_user_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3824_0
crossvul-cpp_data_good_2770_0
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/backing-dev.h> #include <linux/compaction.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <linux/page_owner.h> #include <linux/sched/mm.h> #include <linux/ptrace.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } int isolate_movable_page(struct page *page, isolate_mode_t mode) { struct address_space *mapping; /* * Avoid burning cycles with pages that are yet under __free_pages(), * or just got freed under us. * * In case we 'win' a race for a movable page being freed under us and * raise its refcount preventing __free_pages() from doing its job * the put_page() at the end of this block will take care of * release this page, thus avoiding a nasty leakage. */ if (unlikely(!get_page_unless_zero(page))) goto out; /* * Check PageMovable before holding a PG_lock because page's owner * assumes anybody doesn't touch PG_lock of newly allocated page * so unconditionally grapping the lock ruins page's owner side. */ if (unlikely(!__PageMovable(page))) goto out_putpage; /* * As movable pages are not isolated from LRU lists, concurrent * compaction threads can race against page migration functions * as well as race against the releasing a page. * * In order to avoid having an already isolated movable page * being (wrongly) re-isolated while it is under migration, * or to avoid attempting to isolate pages being released, * lets be sure we have the page lock * before proceeding with the movable page isolation steps. */ if (unlikely(!trylock_page(page))) goto out_putpage; if (!PageMovable(page) || PageIsolated(page)) goto out_no_isolated; mapping = page_mapping(page); VM_BUG_ON_PAGE(!mapping, page); if (!mapping->a_ops->isolate_page(page, mode)) goto out_no_isolated; /* Driver shouldn't use PG_isolated bit of page->flags */ WARN_ON_ONCE(PageIsolated(page)); __SetPageIsolated(page); unlock_page(page); return 0; out_no_isolated: unlock_page(page); out_putpage: put_page(page); out: return -EBUSY; } /* It should be called on page which is PG_movable */ void putback_movable_page(struct page *page) { struct address_space *mapping; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageMovable(page), page); VM_BUG_ON_PAGE(!PageIsolated(page), page); mapping = page_mapping(page); mapping->a_ops->putback_page(page); __ClearPageIsolated(page); } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); /* * We isolated non-lru movable page so here we can use * __PageMovable because LRU page's mapping cannot have * PAGE_MAPPING_MOVABLE. */ if (unlikely(__PageMovable(page))) { VM_BUG_ON_PAGE(!PageIsolated(page), page); lock_page(page); if (PageMovable(page)) putback_movable_page(page); else __ClearPageIsolated(page); unlock_page(page); put_page(page); } else { dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } } } /* * Restore a potential migration pte to a working pte entry */ static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma, unsigned long addr, void *old) { struct page_vma_mapped_walk pvmw = { .page = old, .vma = vma, .address = addr, .flags = PVMW_SYNC | PVMW_MIGRATION, }; struct page *new; pte_t pte; swp_entry_t entry; VM_BUG_ON_PAGE(PageTail(page), page); while (page_vma_mapped_walk(&pvmw)) { if (PageKsm(page)) new = page; else new = page - pvmw.page->index + linear_page_index(vma, pvmw.address); get_page(new); pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot))); if (pte_swp_soft_dirty(*pvmw.pte)) pte = pte_mksoft_dirty(pte); /* * Recheck VMA as permissions can change since migration started */ entry = pte_to_swp_entry(*pvmw.pte); if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); flush_dcache_page(new); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte); if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, pvmw.address); else page_dup_rmap(new, true); } else #endif { set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte); if (PageAnon(new)) page_add_anon_rmap(new, vma, pvmw.address, false); else page_add_file_rmap(new, false); } if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new)) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, pvmw.address, pvmw.pte); } return true; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ void remove_migration_ptes(struct page *old, struct page *new, bool locked) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; if (locked) rmap_walk_locked(new, &rwc); else rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { struct zone *oldzone, *newzone; int dirty; int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) __SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } oldzone = page_zone(page); newzone = page_zone(newpage); spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_ref_freeze(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_ref_unfreeze(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); /* add cache reference */ if (PageSwapBacked(page)) { __SetPageSwapBacked(newpage); if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } } else { VM_BUG_ON_PAGE(PageSwapCache(page), page); } /* Move dirty while page refs frozen and newpage not yet exposed */ dirty = PageDirty(page); if (dirty) { ClearPageDirty(page); SetPageDirty(newpage); } radix_tree_replace_slot(&mapping->page_tree, pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_ref_unfreeze(page, expected_count - 1); spin_unlock(&mapping->tree_lock); /* Leave irq disabled to prevent preemption while updating stats */ /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_MAPPED if they * are mapped to swap space. */ if (newzone != oldzone) { __dec_node_state(oldzone->zone_pgdat, NR_FILE_PAGES); __inc_node_state(newzone->zone_pgdat, NR_FILE_PAGES); if (PageSwapBacked(page) && !PageSwapCache(page)) { __dec_node_state(oldzone->zone_pgdat, NR_SHMEM); __inc_node_state(newzone->zone_pgdat, NR_SHMEM); } if (dirty && mapping_cap_account_dirty(mapping)) { __dec_node_state(oldzone->zone_pgdat, NR_FILE_DIRTY); __dec_zone_state(oldzone, NR_ZONE_WRITE_PENDING); __inc_node_state(newzone->zone_pgdat, NR_FILE_DIRTY); __inc_zone_state(newzone, NR_ZONE_WRITE_PENDING); } } local_irq_enable(); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page_move_mapping); /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_ref_freeze(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(&mapping->page_tree, pslot, newpage); page_ref_unfreeze(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); /* Move dirty on pages not done by migrate_page_move_mapping() */ if (PageDirty(page)) SetPageDirty(newpage); if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); copy_page_owner(page, newpage); mem_cgroup_migrate(page, newpage); } EXPORT_SYMBOL(migrate_page_copy); /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single LRU page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page, false); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc = -EAGAIN; bool is_lru = !__PageMovable(page); VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (likely(is_lru)) { if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems * provide a migratepage callback. Anonymous pages * are part of swap space which also has its own * migratepage callback. This is the most common path * for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); } else { /* * In case of non-lru page, it could be released after * isolation step. In that case, we shouldn't try migration. */ VM_BUG_ON_PAGE(!PageIsolated(page), page); if (!PageMovable(page)) { rc = MIGRATEPAGE_SUCCESS; __ClearPageIsolated(page); goto out; } rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS && !PageIsolated(page)); } /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { if (__PageMovable(page)) { VM_BUG_ON_PAGE(!PageIsolated(page), page); /* * We clear PG_movable under page_lock so any compactor * cannot try to migrate this page. */ __ClearPageIsolated(page); } /* * Anonymous and movable page->mapping will be cleard by * free_pages_prepare so don't reset it here for keeping * the type to work PageAnon, for example. */ if (!PageMappingFlags(page)) page->mapping = NULL; } out: return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; bool is_lru = !__PageMovable(page); if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(!is_lru)) { rc = move_to_new_page(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page, false); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: /* * If migration is successful, decrease refcount of the newpage * which will not free the page because new page owner increased * refcounter. As well, if it is LRU page, add the page to LRU * list in here. */ if (rc == MIGRATEPAGE_SUCCESS) { if (unlikely(__PageMovable(newpage))) put_page(newpage); else putback_lru_page(newpage); } return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ ClearPageActive(page); ClearPageUnevictable(page); if (unlikely(__PageMovable(page))) { lock_page(page); if (!PageMovable(page)) __ClearPageIsolated(page); unlock_page(page); } if (put_new_page) put_new_page(newpage, private); else put_page(newpage); goto out; } if (unlikely(PageTransHuge(page))) { lock_page(page); rc = split_huge_page(page); unlock_page(page); if (rc) goto out; } rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) set_page_owner_migrate_reason(newpage, reason); out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); /* * Compaction can migrate also non-LRU pages which are * not accounted to NR_ISOLATED_*. They can be recognized * as __PageMovable */ if (likely(!__PageMovable(page))) dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } /* * If migration is successful, releases reference grabbed during * isolation. Otherwise, restore the page to right list unless * we want to retry. */ if (rc == MIGRATEPAGE_SUCCESS) { put_page(page); if (reason == MR_MEMORY_FAILURE) { /* * Set PG_HWPoison on just freed page * intentionally. Although it's rather weird, * it's how HWPoison flag works at the moment. */ if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } } else { if (rc != -EAGAIN) { if (likely(!__PageMovable(page))) { putback_lru_page(page); goto put_new; } lock_page(page); if (PageMovable(page)) putback_movable_page(page); else __ClearPageIsolated(page); unlock_page(page); put_page(page); } put_new: if (put_new_page) put_new_page(newpage, private); else put_page(newpage); } if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode, int reason) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; set_page_owner_migrate_reason(new_hpage, reason); } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); if (reason == MR_MEMORY_FAILURE && !test_set_page_hwpoison(hpage)) num_poisoned_pages_inc(); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode, reason); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: nr_failed++; goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. Use the regular "ptrace_may_access()" checks. */ if (!ptrace_may_access(task, PTRACE_MODE_READ_REALCREDS)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~__GFP_RECLAIM, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE), HPAGE_PMD_ORDER); if (!new_page) goto out_fail; prep_transhuge_page(new_page); isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } /* Prepare a page as a migration target */ __SetPageLocked(new_page); if (PageSwapBacked(page)) __SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || !page_ref_freeze(page, 2))) { spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } entry = mk_huge_pmd(new_page, vma->vm_page_prot); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start, true); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); page_ref_unfreeze(page, 2); mlock_migrate_page(new_page, page); page_remove_rmap(page, true); set_page_owner_migrate_reason(new_page, MR_NUMA_MISPLACED); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
./CrossVul/dataset_final_sorted/CWE-200/c/good_2770_0
crossvul-cpp_data_bad_2371_0
/* * Copyright (C) 1995 Linus Torvalds * * Pentium III FXSR, SSE support * Gareth Hughes <gareth@valinux.com>, May 2000 * * X86-64 port * Andi Kleen. * * CPU hotplug support - ashok.raj@intel.com */ /* * This file handles the architecture-dependent parts of process handling.. */ #include <linux/cpu.h> #include <linux/errno.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/elfcore.h> #include <linux/smp.h> #include <linux/slab.h> #include <linux/user.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/ptrace.h> #include <linux/notifier.h> #include <linux/kprobes.h> #include <linux/kdebug.h> #include <linux/prctl.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/ftrace.h> #include <asm/pgtable.h> #include <asm/processor.h> #include <asm/i387.h> #include <asm/fpu-internal.h> #include <asm/mmu_context.h> #include <asm/prctl.h> #include <asm/desc.h> #include <asm/proto.h> #include <asm/ia32.h> #include <asm/idle.h> #include <asm/syscalls.h> #include <asm/debugreg.h> #include <asm/switch_to.h> asmlinkage extern void ret_from_fork(void); __visible DEFINE_PER_CPU(unsigned long, old_rsp); /* Prints also some state that isn't saved in the pt_regs */ void __show_regs(struct pt_regs *regs, int all) { unsigned long cr0 = 0L, cr2 = 0L, cr3 = 0L, cr4 = 0L, fs, gs, shadowgs; unsigned long d0, d1, d2, d3, d6, d7; unsigned int fsindex, gsindex; unsigned int ds, cs, es; printk(KERN_DEFAULT "RIP: %04lx:[<%016lx>] ", regs->cs & 0xffff, regs->ip); printk_address(regs->ip); printk(KERN_DEFAULT "RSP: %04lx:%016lx EFLAGS: %08lx\n", regs->ss, regs->sp, regs->flags); printk(KERN_DEFAULT "RAX: %016lx RBX: %016lx RCX: %016lx\n", regs->ax, regs->bx, regs->cx); printk(KERN_DEFAULT "RDX: %016lx RSI: %016lx RDI: %016lx\n", regs->dx, regs->si, regs->di); printk(KERN_DEFAULT "RBP: %016lx R08: %016lx R09: %016lx\n", regs->bp, regs->r8, regs->r9); printk(KERN_DEFAULT "R10: %016lx R11: %016lx R12: %016lx\n", regs->r10, regs->r11, regs->r12); printk(KERN_DEFAULT "R13: %016lx R14: %016lx R15: %016lx\n", regs->r13, regs->r14, regs->r15); asm("movl %%ds,%0" : "=r" (ds)); asm("movl %%cs,%0" : "=r" (cs)); asm("movl %%es,%0" : "=r" (es)); asm("movl %%fs,%0" : "=r" (fsindex)); asm("movl %%gs,%0" : "=r" (gsindex)); rdmsrl(MSR_FS_BASE, fs); rdmsrl(MSR_GS_BASE, gs); rdmsrl(MSR_KERNEL_GS_BASE, shadowgs); if (!all) return; cr0 = read_cr0(); cr2 = read_cr2(); cr3 = read_cr3(); cr4 = read_cr4(); printk(KERN_DEFAULT "FS: %016lx(%04x) GS:%016lx(%04x) knlGS:%016lx\n", fs, fsindex, gs, gsindex, shadowgs); printk(KERN_DEFAULT "CS: %04x DS: %04x ES: %04x CR0: %016lx\n", cs, ds, es, cr0); printk(KERN_DEFAULT "CR2: %016lx CR3: %016lx CR4: %016lx\n", cr2, cr3, cr4); get_debugreg(d0, 0); get_debugreg(d1, 1); get_debugreg(d2, 2); get_debugreg(d3, 3); get_debugreg(d6, 6); get_debugreg(d7, 7); /* Only print out debug registers if they are in their non-default state. */ if ((d0 == 0) && (d1 == 0) && (d2 == 0) && (d3 == 0) && (d6 == DR6_RESERVED) && (d7 == 0x400)) return; printk(KERN_DEFAULT "DR0: %016lx DR1: %016lx DR2: %016lx\n", d0, d1, d2); printk(KERN_DEFAULT "DR3: %016lx DR6: %016lx DR7: %016lx\n", d3, d6, d7); } void release_thread(struct task_struct *dead_task) { if (dead_task->mm) { if (dead_task->mm->context.size) { pr_warn("WARNING: dead process %s still has LDT? <%p/%d>\n", dead_task->comm, dead_task->mm->context.ldt, dead_task->mm->context.size); BUG(); } } } static inline void set_32bit_tls(struct task_struct *t, int tls, u32 addr) { struct user_desc ud = { .base_addr = addr, .limit = 0xfffff, .seg_32bit = 1, .limit_in_pages = 1, .useable = 1, }; struct desc_struct *desc = t->thread.tls_array; desc += tls; fill_ldt(desc, &ud); } static inline u32 read_32bit_tls(struct task_struct *t, int tls) { return get_desc_base(&t->thread.tls_array[tls]); } int copy_thread(unsigned long clone_flags, unsigned long sp, unsigned long arg, struct task_struct *p) { int err; struct pt_regs *childregs; struct task_struct *me = current; p->thread.sp0 = (unsigned long)task_stack_page(p) + THREAD_SIZE; childregs = task_pt_regs(p); p->thread.sp = (unsigned long) childregs; p->thread.usersp = me->thread.usersp; set_tsk_thread_flag(p, TIF_FORK); p->thread.io_bitmap_ptr = NULL; savesegment(gs, p->thread.gsindex); p->thread.gs = p->thread.gsindex ? 0 : me->thread.gs; savesegment(fs, p->thread.fsindex); p->thread.fs = p->thread.fsindex ? 0 : me->thread.fs; savesegment(es, p->thread.es); savesegment(ds, p->thread.ds); memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps)); if (unlikely(p->flags & PF_KTHREAD)) { /* kernel thread */ memset(childregs, 0, sizeof(struct pt_regs)); childregs->sp = (unsigned long)childregs; childregs->ss = __KERNEL_DS; childregs->bx = sp; /* function */ childregs->bp = arg; childregs->orig_ax = -1; childregs->cs = __KERNEL_CS | get_kernel_rpl(); childregs->flags = X86_EFLAGS_IF | X86_EFLAGS_FIXED; return 0; } *childregs = *current_pt_regs(); childregs->ax = 0; if (sp) childregs->sp = sp; err = -ENOMEM; if (unlikely(test_tsk_thread_flag(me, TIF_IO_BITMAP))) { p->thread.io_bitmap_ptr = kmemdup(me->thread.io_bitmap_ptr, IO_BITMAP_BYTES, GFP_KERNEL); if (!p->thread.io_bitmap_ptr) { p->thread.io_bitmap_max = 0; return -ENOMEM; } set_tsk_thread_flag(p, TIF_IO_BITMAP); } /* * Set a new TLS for the child thread? */ if (clone_flags & CLONE_SETTLS) { #ifdef CONFIG_IA32_EMULATION if (test_thread_flag(TIF_IA32)) err = do_set_thread_area(p, -1, (struct user_desc __user *)childregs->si, 0); else #endif err = do_arch_prctl(p, ARCH_SET_FS, childregs->r8); if (err) goto out; } err = 0; out: if (err && p->thread.io_bitmap_ptr) { kfree(p->thread.io_bitmap_ptr); p->thread.io_bitmap_max = 0; } return err; } static void start_thread_common(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp, unsigned int _cs, unsigned int _ss, unsigned int _ds) { loadsegment(fs, 0); loadsegment(es, _ds); loadsegment(ds, _ds); load_gs_index(0); current->thread.usersp = new_sp; regs->ip = new_ip; regs->sp = new_sp; this_cpu_write(old_rsp, new_sp); regs->cs = _cs; regs->ss = _ss; regs->flags = X86_EFLAGS_IF; } void start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp) { start_thread_common(regs, new_ip, new_sp, __USER_CS, __USER_DS, 0); } #ifdef CONFIG_IA32_EMULATION void start_thread_ia32(struct pt_regs *regs, u32 new_ip, u32 new_sp) { start_thread_common(regs, new_ip, new_sp, test_thread_flag(TIF_X32) ? __USER_CS : __USER32_CS, __USER_DS, __USER_DS); } #endif /* * switch_to(x,y) should switch tasks from x to y. * * This could still be optimized: * - fold all the options into a flag word and test it with a single test. * - could test fs/gs bitsliced * * Kprobes not supported here. Set the probe on schedule instead. * Function graph tracer not supported too. */ __visible __notrace_funcgraph struct task_struct * __switch_to(struct task_struct *prev_p, struct task_struct *next_p) { struct thread_struct *prev = &prev_p->thread; struct thread_struct *next = &next_p->thread; int cpu = smp_processor_id(); struct tss_struct *tss = &per_cpu(init_tss, cpu); unsigned fsindex, gsindex; fpu_switch_t fpu; fpu = switch_fpu_prepare(prev_p, next_p, cpu); /* * Reload esp0, LDT and the page table pointer: */ load_sp0(tss, next); /* * Switch DS and ES. * This won't pick up thread selector changes, but I guess that is ok. */ savesegment(es, prev->es); if (unlikely(next->es | prev->es)) loadsegment(es, next->es); savesegment(ds, prev->ds); if (unlikely(next->ds | prev->ds)) loadsegment(ds, next->ds); /* We must save %fs and %gs before load_TLS() because * %fs and %gs may be cleared by load_TLS(). * * (e.g. xen_load_tls()) */ savesegment(fs, fsindex); savesegment(gs, gsindex); load_TLS(next, cpu); /* * Leave lazy mode, flushing any hypercalls made here. * This must be done before restoring TLS segments so * the GDT and LDT are properly updated, and must be * done before math_state_restore, so the TS bit is up * to date. */ arch_end_context_switch(next_p); /* * Switch FS and GS. * * Segment register != 0 always requires a reload. Also * reload when it has changed. When prev process used 64bit * base always reload to avoid an information leak. */ if (unlikely(fsindex | next->fsindex | prev->fs)) { loadsegment(fs, next->fsindex); /* * Check if the user used a selector != 0; if yes * clear 64bit base, since overloaded base is always * mapped to the Null selector */ if (fsindex) prev->fs = 0; } /* when next process has a 64bit base use it */ if (next->fs) wrmsrl(MSR_FS_BASE, next->fs); prev->fsindex = fsindex; if (unlikely(gsindex | next->gsindex | prev->gs)) { load_gs_index(next->gsindex); if (gsindex) prev->gs = 0; } if (next->gs) wrmsrl(MSR_KERNEL_GS_BASE, next->gs); prev->gsindex = gsindex; switch_fpu_finish(next_p, fpu); /* * Switch the PDA and FPU contexts. */ prev->usersp = this_cpu_read(old_rsp); this_cpu_write(old_rsp, next->usersp); this_cpu_write(current_task, next_p); /* * If it were not for PREEMPT_ACTIVE we could guarantee that the * preempt_count of all tasks was equal here and this would not be * needed. */ task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count); this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count); this_cpu_write(kernel_stack, (unsigned long)task_stack_page(next_p) + THREAD_SIZE - KERNEL_STACK_OFFSET); /* * Now maybe reload the debug registers and handle I/O bitmaps */ if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT || task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV)) __switch_to_xtra(prev_p, next_p, tss); return prev_p; } void set_personality_64bit(void) { /* inherit personality from parent */ /* Make sure to be in 64bit mode */ clear_thread_flag(TIF_IA32); clear_thread_flag(TIF_ADDR32); clear_thread_flag(TIF_X32); /* Ensure the corresponding mm is not marked. */ if (current->mm) current->mm->context.ia32_compat = 0; /* TBD: overwrites user setup. Should have two bits. But 64bit processes have always behaved this way, so it's not too bad. The main problem is just that 32bit childs are affected again. */ current->personality &= ~READ_IMPLIES_EXEC; } void set_personality_ia32(bool x32) { /* inherit personality from parent */ /* Make sure to be in 32bit mode */ set_thread_flag(TIF_ADDR32); /* Mark the associated mm as containing 32-bit tasks. */ if (x32) { clear_thread_flag(TIF_IA32); set_thread_flag(TIF_X32); if (current->mm) current->mm->context.ia32_compat = TIF_X32; current->personality &= ~READ_IMPLIES_EXEC; /* is_compat_task() uses the presence of the x32 syscall bit flag to determine compat status */ current_thread_info()->status &= ~TS_COMPAT; } else { set_thread_flag(TIF_IA32); clear_thread_flag(TIF_X32); if (current->mm) current->mm->context.ia32_compat = TIF_IA32; current->personality |= force_personality32; /* Prepare the first "return" to user space */ current_thread_info()->status |= TS_COMPAT; } } EXPORT_SYMBOL_GPL(set_personality_ia32); unsigned long get_wchan(struct task_struct *p) { unsigned long stack; u64 fp, ip; int count = 0; if (!p || p == current || p->state == TASK_RUNNING) return 0; stack = (unsigned long)task_stack_page(p); if (p->thread.sp < stack || p->thread.sp >= stack+THREAD_SIZE) return 0; fp = *(u64 *)(p->thread.sp); do { if (fp < (unsigned long)stack || fp >= (unsigned long)stack+THREAD_SIZE) return 0; ip = *(u64 *)(fp+8); if (!in_sched_functions(ip)) return ip; fp = *(u64 *)fp; } while (count++ < 16); return 0; } long do_arch_prctl(struct task_struct *task, int code, unsigned long addr) { int ret = 0; int doit = task == current; int cpu; switch (code) { case ARCH_SET_GS: if (addr >= TASK_SIZE_OF(task)) return -EPERM; cpu = get_cpu(); /* handle small bases via the GDT because that's faster to switch. */ if (addr <= 0xffffffff) { set_32bit_tls(task, GS_TLS, addr); if (doit) { load_TLS(&task->thread, cpu); load_gs_index(GS_TLS_SEL); } task->thread.gsindex = GS_TLS_SEL; task->thread.gs = 0; } else { task->thread.gsindex = 0; task->thread.gs = addr; if (doit) { load_gs_index(0); ret = wrmsrl_safe(MSR_KERNEL_GS_BASE, addr); } } put_cpu(); break; case ARCH_SET_FS: /* Not strictly needed for fs, but do it for symmetry with gs */ if (addr >= TASK_SIZE_OF(task)) return -EPERM; cpu = get_cpu(); /* handle small bases via the GDT because that's faster to switch. */ if (addr <= 0xffffffff) { set_32bit_tls(task, FS_TLS, addr); if (doit) { load_TLS(&task->thread, cpu); loadsegment(fs, FS_TLS_SEL); } task->thread.fsindex = FS_TLS_SEL; task->thread.fs = 0; } else { task->thread.fsindex = 0; task->thread.fs = addr; if (doit) { /* set the selector to 0 to not confuse __switch_to */ loadsegment(fs, 0); ret = wrmsrl_safe(MSR_FS_BASE, addr); } } put_cpu(); break; case ARCH_GET_FS: { unsigned long base; if (task->thread.fsindex == FS_TLS_SEL) base = read_32bit_tls(task, FS_TLS); else if (doit) rdmsrl(MSR_FS_BASE, base); else base = task->thread.fs; ret = put_user(base, (unsigned long __user *)addr); break; } case ARCH_GET_GS: { unsigned long base; unsigned gsindex; if (task->thread.gsindex == GS_TLS_SEL) base = read_32bit_tls(task, GS_TLS); else if (doit) { savesegment(gs, gsindex); if (gsindex) rdmsrl(MSR_KERNEL_GS_BASE, base); else base = task->thread.gs; } else base = task->thread.gs; ret = put_user(base, (unsigned long __user *)addr); break; } default: ret = -EINVAL; break; } return ret; } long sys_arch_prctl(int code, unsigned long addr) { return do_arch_prctl(current, code, addr); } unsigned long KSTK_ESP(struct task_struct *task) { return (test_tsk_thread_flag(task, TIF_IA32)) ? (task_pt_regs(task)->sp) : ((task)->thread.usersp); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2371_0
crossvul-cpp_data_bad_438_3
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Dynamic data structure definition. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <unistd.h> #include <pwd.h> #include "global_data.h" #include "list.h" #include "logger.h" #include "parser.h" #include "utils.h" #include "main.h" #include "memory.h" #ifdef _WITH_VRRP_ #include "vrrp.h" #include "vrrp_ipaddress.h" #endif #if HAVE_DECL_RLIMIT_RTTIME == 1 #include "process.h" #endif /* global vars */ data_t *global_data = NULL; data_t *old_global_data = NULL; /* Default settings */ static void set_default_router_id(data_t *data, char *new_id) { if (!new_id || !new_id[0]) return; data->router_id = MALLOC(strlen(new_id)+1); strcpy(data->router_id, new_id); } static void set_default_email_from(data_t * data, const char *hostname) { struct passwd *pwd = NULL; size_t len; if (!hostname || !hostname[0]) return; pwd = getpwuid(getuid()); if (!pwd) return; len = strlen(hostname) + strlen(pwd->pw_name) + 2; data->email_from = MALLOC(len); if (!data->email_from) return; snprintf(data->email_from, len, "%s@%s", pwd->pw_name, hostname); } static void set_default_smtp_connection_timeout(data_t * data) { data->smtp_connection_to = DEFAULT_SMTP_CONNECTION_TIMEOUT; } #ifdef _WITH_VRRP_ static void set_default_mcast_group(data_t * data) { inet_stosockaddr(INADDR_VRRP_GROUP, 0, (struct sockaddr_storage *)&data->vrrp_mcast_group4); inet_stosockaddr(INADDR6_VRRP_GROUP, 0, (struct sockaddr_storage *)&data->vrrp_mcast_group6); } static void set_vrrp_defaults(data_t * data) { data->vrrp_garp_rep = VRRP_GARP_REP; data->vrrp_garp_refresh.tv_sec = VRRP_GARP_REFRESH; data->vrrp_garp_refresh_rep = VRRP_GARP_REFRESH_REP; data->vrrp_garp_delay = VRRP_GARP_DELAY; data->vrrp_garp_lower_prio_delay = PARAMETER_UNSET; data->vrrp_garp_lower_prio_rep = PARAMETER_UNSET; data->vrrp_lower_prio_no_advert = false; data->vrrp_higher_prio_send_advert = false; data->vrrp_version = VRRP_VERSION_2; strcpy(data->vrrp_iptables_inchain, "INPUT"); #ifdef _HAVE_LIBIPSET_ data->using_ipsets = true; strcpy(data->vrrp_ipset_address, "keepalived"); strcpy(data->vrrp_ipset_address6, "keepalived6"); strcpy(data->vrrp_ipset_address_iface6, "keepalived_if6"); #endif data->vrrp_check_unicast_src = false; data->vrrp_skip_check_adv_addr = false; data->vrrp_strict = false; } #endif /* email facility functions */ static void free_email(void *data) { FREE(data); } static void dump_email(FILE *fp, void *data) { char *addr = data; conf_write(fp, " Email notification = %s", addr); } void alloc_email(char *addr) { size_t size = strlen(addr); char *new; new = (char *) MALLOC(size + 1); memcpy(new, addr, size + 1); list_add(global_data->email, new); } /* data facility functions */ data_t * alloc_global_data(void) { data_t *new; if (global_data) return global_data; new = (data_t *) MALLOC(sizeof(data_t)); new->email = alloc_list(free_email, dump_email); new->smtp_alert = -1; #ifdef _WITH_VRRP_ new->smtp_alert_vrrp = -1; #endif #ifdef _WITH_LVS_ new->smtp_alert_checker = -1; #endif #ifdef _WITH_VRRP_ set_default_mcast_group(new); set_vrrp_defaults(new); #endif new->notify_fifo.fd = -1; #ifdef _WITH_VRRP_ new->vrrp_notify_fifo.fd = -1; #if HAVE_DECL_RLIMIT_RTTIME == 1 new->vrrp_rlimit_rt = RT_RLIMIT_DEFAULT; #endif new->vrrp_rx_bufs_multiples = 3; #endif #ifdef _WITH_LVS_ new->lvs_notify_fifo.fd = -1; #if HAVE_DECL_RLIMIT_RTTIME == 1 new->checker_rlimit_rt = RT_RLIMIT_DEFAULT; #endif #ifdef _WITH_BFD_ #if HAVE_DECL_RLIMIT_RTTIME == 1 new->bfd_rlimit_rt = RT_RLIMIT_DEFAULT; #endif #endif #endif #ifdef _WITH_SNMP_ if (snmp) { #ifdef _WITH_SNMP_VRRP_ new->enable_snmp_vrrp = true; #endif #ifdef _WITH_SNMP_RFCV2_ new->enable_snmp_rfcv2 = true; #endif #ifdef _WITH_SNMP_RFCV3_ new->enable_snmp_rfcv3 = true; #endif #ifdef _WITH_SNMP_CHECKER_ new->enable_snmp_checker = true; #endif } if (snmp_socket) { new->snmp_socket = MALLOC(strlen(snmp_socket + 1)); strcpy(new->snmp_socket, snmp_socket); } #endif #ifdef _WITH_LVS_ #ifdef _WITH_VRRP_ new->lvs_syncd.syncid = PARAMETER_UNSET; #ifdef _HAVE_IPVS_SYNCD_ATTRIBUTES_ new->lvs_syncd.mcast_group.ss_family = AF_UNSPEC; #endif #endif #endif return new; } void init_global_data(data_t * data, data_t *old_global_data) { /* If this is a reload and we are running in a network namespace, * we may not be able to get local_name, so preserve it */ char unknown_name[] = "[unknown]"; /* If we are running in a network namespace, we may not be * able to get our local name now, so re-use original */ if (old_global_data) { data->local_name = old_global_data->local_name; old_global_data->local_name = NULL; } if (!data->local_name && (!data->router_id || (data->smtp_server.ss_family && (!data->smtp_helo_name || !data->email_from)))) { data->local_name = get_local_name(); /* If for some reason get_local_name() fails, we need to have * some string in local_name, otherwise keepalived can segfault */ if (!data->local_name) { data->local_name = MALLOC(sizeof(unknown_name)); strcpy(data->local_name, unknown_name); } } if (!data->router_id) set_default_router_id(data, data->local_name); if (data->smtp_server.ss_family) { if (!data->smtp_connection_to) set_default_smtp_connection_timeout(data); if (strcmp(data->local_name, unknown_name)) { if (!data->email_from) set_default_email_from(data, data->local_name); if (!data->smtp_helo_name) data->smtp_helo_name = data->local_name; } } /* Check that there aren't conflicts with the notify FIFOs */ #ifdef _WITH_VRRP_ /* If the global and vrrp notify FIFOs are the same, then data will be * duplicated on the FIFO */ if ( #ifndef _DEBUG_ prog_type == PROG_TYPE_VRRP && #endif data->notify_fifo.name && data->vrrp_notify_fifo.name && !strcmp(data->notify_fifo.name, data->vrrp_notify_fifo.name)) { log_message(LOG_INFO, "notify FIFO %s has been specified for global and vrrp FIFO - ignoring vrrp FIFO", data->vrrp_notify_fifo.name); FREE_PTR(data->vrrp_notify_fifo.name); data->vrrp_notify_fifo.name = NULL; free_notify_script(&data->vrrp_notify_fifo.script); } #endif #ifdef _WITH_LVS_ /* If the global and LVS notify FIFOs are the same, then data will be * duplicated on the FIFO */ #ifndef _DEBUG_ if (prog_type == PROG_TYPE_CHECKER) #endif { if (data->notify_fifo.name && data->lvs_notify_fifo.name && !strcmp(data->notify_fifo.name, data->lvs_notify_fifo.name)) { log_message(LOG_INFO, "notify FIFO %s has been specified for global and LVS FIFO - ignoring LVS FIFO", data->lvs_notify_fifo.name); FREE_PTR(data->lvs_notify_fifo.name); data->lvs_notify_fifo.name = NULL; free_notify_script(&data->lvs_notify_fifo.script); } #ifdef _WITH_VRRP_ /* If LVS and VRRP use the same FIFO, they cannot both have a script for the FIFO. * Use the VRRP script and ignore the LVS script */ if (data->lvs_notify_fifo.name && data->vrrp_notify_fifo.name && !strcmp(data->lvs_notify_fifo.name, data->vrrp_notify_fifo.name) && data->lvs_notify_fifo.script && data->vrrp_notify_fifo.script) { log_message(LOG_INFO, "LVS notify FIFO and vrrp FIFO are the same both with scripts - ignoring LVS FIFO script"); free_notify_script(&data->lvs_notify_fifo.script); } #endif } #endif } void free_global_data(data_t * data) { if (!data) return; free_list(&data->email); #if HAVE_DECL_CLONE_NEWNET FREE_PTR(data->network_namespace); #endif FREE_PTR(data->instance_name); FREE_PTR(data->router_id); FREE_PTR(data->email_from); FREE_PTR(data->smtp_helo_name); FREE_PTR(data->local_name); #ifdef _WITH_SNMP_ FREE_PTR(data->snmp_socket); #endif #if defined _WITH_LVS_ && defined _WITH_VRRP_ FREE_PTR(data->lvs_syncd.ifname); FREE_PTR(data->lvs_syncd.vrrp_name); #endif FREE_PTR(data->notify_fifo.name); free_notify_script(&data->notify_fifo.script); #ifdef _WITH_VRRP_ FREE_PTR(data->default_ifname); FREE_PTR(data->vrrp_notify_fifo.name); free_notify_script(&data->vrrp_notify_fifo.script); #endif #ifdef _WITH_LVS_ FREE_PTR(data->lvs_notify_fifo.name); free_notify_script(&data->lvs_notify_fifo.script); #endif FREE(data); } void dump_global_data(FILE *fp, data_t * data) { #ifdef _WITH_VRRP_ char buf[64]; #endif if (!data) return; conf_write(fp, "------< Global definitions >------"); #if HAVE_DECL_CLONE_NEWNET conf_write(fp, " Network namespace = %s", data->network_namespace ? data->network_namespace : "(default)"); #endif if (data->instance_name) conf_write(fp, " Instance name = %s", data->instance_name); if (data->router_id) conf_write(fp, " Router ID = %s", data->router_id); if (data->smtp_server.ss_family) { conf_write(fp, " Smtp server = %s", inet_sockaddrtos(&data->smtp_server)); conf_write(fp, " Smtp server port = %u", ntohs(inet_sockaddrport(&data->smtp_server))); } if (data->smtp_helo_name) conf_write(fp, " Smtp HELO name = %s" , data->smtp_helo_name); if (data->smtp_connection_to) conf_write(fp, " Smtp server connection timeout = %lu" , data->smtp_connection_to / TIMER_HZ); if (data->email_from) { conf_write(fp, " Email notification from = %s" , data->email_from); dump_list(fp, data->email); } conf_write(fp, " Default smtp_alert = %s", data->smtp_alert == -1 ? "unset" : data->smtp_alert ? "on" : "off"); #ifdef _WITH_VRRP_ conf_write(fp, " Default smtp_alert_vrrp = %s", data->smtp_alert_vrrp == -1 ? "unset" : data->smtp_alert_vrrp ? "on" : "off"); #endif #ifdef _WITH_LVS_ conf_write(fp, " Default smtp_alert_checker = %s", data->smtp_alert_checker == -1 ? "unset" : data->smtp_alert_checker ? "on" : "off"); #endif #ifdef _WITH_VRRP_ conf_write(fp, " Dynamic interfaces = %s", data->dynamic_interfaces ? "true" : "false"); if (data->dynamic_interfaces) conf_write(fp, " Allow interface changes = %s", data->allow_if_changes ? "true" : "false"); if (data->no_email_faults) conf_write(fp, " Send emails for fault transitions = off"); #endif #ifdef _WITH_LVS_ if (data->lvs_tcp_timeout) conf_write(fp, " LVS TCP timeout = %d", data->lvs_tcp_timeout); if (data->lvs_tcpfin_timeout) conf_write(fp, " LVS TCP FIN timeout = %d", data->lvs_tcpfin_timeout); if (data->lvs_udp_timeout) conf_write(fp, " LVS TCP timeout = %d", data->lvs_udp_timeout); #ifdef _WITH_VRRP_ #ifndef _DEBUG_ if (prog_type == PROG_TYPE_VRRP) #endif conf_write(fp, " Default interface = %s", data->default_ifp ? data->default_ifp->ifname : DFLT_INT); if (data->lvs_syncd.vrrp) { conf_write(fp, " LVS syncd vrrp instance = %s" , data->lvs_syncd.vrrp->iname); if (data->lvs_syncd.ifname) conf_write(fp, " LVS syncd interface = %s" , data->lvs_syncd.ifname); conf_write(fp, " LVS syncd syncid = %u" , data->lvs_syncd.syncid); #ifdef _HAVE_IPVS_SYNCD_ATTRIBUTES_ if (data->lvs_syncd.sync_maxlen) conf_write(fp, " LVS syncd maxlen = %u", data->lvs_syncd.sync_maxlen); if (data->lvs_syncd.mcast_group.ss_family != AF_UNSPEC) conf_write(fp, " LVS mcast group %s", inet_sockaddrtos(&data->lvs_syncd.mcast_group)); if (data->lvs_syncd.mcast_port) conf_write(fp, " LVS syncd mcast port = %d", data->lvs_syncd.mcast_port); if (data->lvs_syncd.mcast_ttl) conf_write(fp, " LVS syncd mcast ttl = %u", data->lvs_syncd.mcast_ttl); #endif } #endif conf_write(fp, " LVS flush = %s", data->lvs_flush ? "true" : "false"); #endif if (data->notify_fifo.name) { conf_write(fp, " Global notify fifo = %s", data->notify_fifo.name); if (data->notify_fifo.script) conf_write(fp, " Global notify fifo script = %s, uid:gid %d:%d", cmd_str(data->notify_fifo.script), data->notify_fifo.script->uid, data->notify_fifo.script->gid); } #ifdef _WITH_VRRP_ if (data->vrrp_notify_fifo.name) { conf_write(fp, " VRRP notify fifo = %s", data->vrrp_notify_fifo.name); if (data->vrrp_notify_fifo.script) conf_write(fp, " VRRP notify fifo script = %s, uid:gid %d:%d", cmd_str(data->vrrp_notify_fifo.script), data->vrrp_notify_fifo.script->uid, data->vrrp_notify_fifo.script->gid); } #endif #ifdef _WITH_LVS_ if (data->lvs_notify_fifo.name) { conf_write(fp, " LVS notify fifo = %s", data->lvs_notify_fifo.name); if (data->lvs_notify_fifo.script) conf_write(fp, " LVS notify fifo script = %s, uid:gid %d:%d", cmd_str(data->lvs_notify_fifo.script), data->lvs_notify_fifo.script->uid, data->lvs_notify_fifo.script->gid); } #endif #ifdef _WITH_VRRP_ if (data->vrrp_mcast_group4.sin_family) { conf_write(fp, " VRRP IPv4 mcast group = %s" , inet_sockaddrtos((struct sockaddr_storage *)&data->vrrp_mcast_group4)); } if (data->vrrp_mcast_group6.sin6_family) { conf_write(fp, " VRRP IPv6 mcast group = %s" , inet_sockaddrtos((struct sockaddr_storage *)&data->vrrp_mcast_group6)); } conf_write(fp, " Gratuitous ARP delay = %u", data->vrrp_garp_delay/TIMER_HZ); conf_write(fp, " Gratuitous ARP repeat = %u", data->vrrp_garp_rep); conf_write(fp, " Gratuitous ARP refresh timer = %lu", data->vrrp_garp_refresh.tv_sec); conf_write(fp, " Gratuitous ARP refresh repeat = %d", data->vrrp_garp_refresh_rep); conf_write(fp, " Gratuitous ARP lower priority delay = %d", data->vrrp_garp_lower_prio_delay == PARAMETER_UNSET ? PARAMETER_UNSET : data->vrrp_garp_lower_prio_delay / TIMER_HZ); conf_write(fp, " Gratuitous ARP lower priority repeat = %d", data->vrrp_garp_lower_prio_rep); conf_write(fp, " Send advert after receive lower priority advert = %s", data->vrrp_lower_prio_no_advert ? "false" : "true"); conf_write(fp, " Send advert after receive higher priority advert = %s", data->vrrp_higher_prio_send_advert ? "true" : "false"); conf_write(fp, " Gratuitous ARP interval = %d", data->vrrp_garp_interval); conf_write(fp, " Gratuitous NA interval = %d", data->vrrp_gna_interval); conf_write(fp, " VRRP default protocol version = %d", data->vrrp_version); if (data->vrrp_iptables_inchain[0]) conf_write(fp," Iptables input chain = %s", data->vrrp_iptables_inchain); if (data->vrrp_iptables_outchain[0]) conf_write(fp," Iptables output chain = %s", data->vrrp_iptables_outchain); #ifdef _HAVE_LIBIPSET_ conf_write(fp, " Using ipsets = %s", data->using_ipsets ? "true" : "false"); if (data->vrrp_ipset_address[0]) conf_write(fp," ipset IPv4 address set = %s", data->vrrp_ipset_address); if (data->vrrp_ipset_address6[0]) conf_write(fp," ipset IPv6 address set = %s", data->vrrp_ipset_address6); if (data->vrrp_ipset_address_iface6[0]) conf_write(fp," ipset IPv6 address,iface set = %s", data->vrrp_ipset_address_iface6); #endif conf_write(fp, " VRRP check unicast_src = %s", data->vrrp_check_unicast_src ? "true" : "false"); conf_write(fp, " VRRP skip check advert addresses = %s", data->vrrp_skip_check_adv_addr ? "true" : "false"); conf_write(fp, " VRRP strict mode = %s", data->vrrp_strict ? "true" : "false"); conf_write(fp, " VRRP process priority = %d", data->vrrp_process_priority); conf_write(fp, " VRRP don't swap = %s", data->vrrp_no_swap ? "true" : "false"); #ifdef _HAVE_SCHED_RT_ conf_write(fp, " VRRP realtime priority = %u", data->vrrp_realtime_priority); #if HAVE_DECL_RLIMIT_RTTIME conf_write(fp, " VRRP realtime limit = %lu", data->vrrp_rlimit_rt); #endif #endif #endif #ifdef _WITH_LVS_ conf_write(fp, " Checker process priority = %d", data->checker_process_priority); conf_write(fp, " Checker don't swap = %s", data->checker_no_swap ? "true" : "false"); #ifdef _HAVE_SCHED_RT_ conf_write(fp, " Checker realtime priority = %u", data->checker_realtime_priority); #if HAVE_DECL_RLIMIT_RTTIME conf_write(fp, " Checker realtime limit = %lu", data->checker_rlimit_rt); #endif #endif #endif #ifdef _WITH_BFD_ conf_write(fp, " BFD process priority = %d", data->bfd_process_priority); conf_write(fp, " BFD don't swap = %s", data->bfd_no_swap ? "true" : "false"); #ifdef _HAVE_SCHED_RT_ conf_write(fp, " BFD realtime priority = %u", data->bfd_realtime_priority); #if HAVE_DECL_RLIMIT_RTTIME conf_write(fp, " BFD realtime limit = %lu", data->bfd_rlimit_rt); #endif #endif #endif #ifdef _WITH_SNMP_VRRP_ conf_write(fp, " SNMP vrrp %s", data->enable_snmp_vrrp ? "enabled" : "disabled"); #endif #ifdef _WITH_SNMP_CHECKER_ conf_write(fp, " SNMP checker %s", data->enable_snmp_checker ? "enabled" : "disabled"); #endif #ifdef _WITH_SNMP_RFCV2_ conf_write(fp, " SNMP RFCv2 %s", data->enable_snmp_rfcv2 ? "enabled" : "disabled"); #endif #ifdef _WITH_SNMP_RFCV3_ conf_write(fp, " SNMP RFCv3 %s", data->enable_snmp_rfcv3 ? "enabled" : "disabled"); #endif #ifdef _WITH_SNMP_ conf_write(fp, " SNMP traps %s", data->enable_traps ? "enabled" : "disabled"); conf_write(fp, " SNMP socket = %s", data->snmp_socket ? data->snmp_socket : "default (unix:/var/agentx/master)"); #endif #ifdef _WITH_DBUS_ conf_write(fp, " DBus %s", data->enable_dbus ? "enabled" : "disabled"); conf_write(fp, " DBus service name = %s", data->dbus_service_name ? data->dbus_service_name : ""); #endif conf_write(fp, " Script security %s", script_security ? "enabled" : "disabled"); conf_write(fp, " Default script uid:gid %d:%d", default_script_uid, default_script_gid); #ifdef _WITH_VRRP_ conf_write(fp, " vrrp_netlink_cmd_rcv_bufs = %u", global_data->vrrp_netlink_cmd_rcv_bufs); conf_write(fp, " vrrp_netlink_cmd_rcv_bufs_force = %u", global_data->vrrp_netlink_cmd_rcv_bufs_force); conf_write(fp, " vrrp_netlink_monitor_rcv_bufs = %u", global_data->vrrp_netlink_monitor_rcv_bufs); conf_write(fp, " vrrp_netlink_monitor_rcv_bufs_force = %u", global_data->vrrp_netlink_monitor_rcv_bufs_force); #endif #ifdef _WITH_LVS_ conf_write(fp, " lvs_netlink_cmd_rcv_bufs = %u", global_data->lvs_netlink_cmd_rcv_bufs); conf_write(fp, " lvs_netlink_cmd_rcv_bufs_force = %u", global_data->lvs_netlink_cmd_rcv_bufs_force); conf_write(fp, " lvs_netlink_monitor_rcv_bufs = %u", global_data->lvs_netlink_monitor_rcv_bufs); conf_write(fp, " lvs_netlink_monitor_rcv_bufs_force = %u", global_data->lvs_netlink_monitor_rcv_bufs_force); conf_write(fp, " rs_init_notifies = %u", global_data->rs_init_notifies); conf_write(fp, " no_checker_emails = %u", global_data->no_checker_emails); #endif #ifdef _WITH_VRRP_ buf[0] = '\0'; if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_MTU) strcpy(buf, " rx_bufs_policy = MTU"); else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_POLICY_ADVERT) strcpy(buf, " rx_bufs_policy = ADVERT"); else if (global_data->vrrp_rx_bufs_policy & RX_BUFS_SIZE) sprintf(buf, " rx_bufs_size = %lu", global_data->vrrp_rx_bufs_size); if (buf[0]) conf_write(fp, "%s", buf); conf_write(fp, " rx_bufs_multiples = %u", global_data->vrrp_rx_bufs_multiples); #endif }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_438_3
crossvul-cpp_data_bad_1791_0
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2000-2001 Qualcomm Incorporated Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth SCO sockets. */ #include <linux/module.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/sco.h> static bool disable_esco; static const struct proto_ops sco_sock_ops; static struct bt_sock_list sco_sk_list = { .lock = __RW_LOCK_UNLOCKED(sco_sk_list.lock) }; /* ---- SCO connections ---- */ struct sco_conn { struct hci_conn *hcon; spinlock_t lock; struct sock *sk; unsigned int mtu; }; #define sco_conn_lock(c) spin_lock(&c->lock); #define sco_conn_unlock(c) spin_unlock(&c->lock); static void sco_sock_close(struct sock *sk); static void sco_sock_kill(struct sock *sk); /* ----- SCO socket info ----- */ #define sco_pi(sk) ((struct sco_pinfo *) sk) struct sco_pinfo { struct bt_sock bt; bdaddr_t src; bdaddr_t dst; __u32 flags; __u16 setting; struct sco_conn *conn; }; /* ---- SCO timers ---- */ #define SCO_CONN_TIMEOUT (HZ * 40) #define SCO_DISCONN_TIMEOUT (HZ * 2) static void sco_sock_timeout(unsigned long arg) { struct sock *sk = (struct sock *)arg; BT_DBG("sock %p state %d", sk, sk->sk_state); bh_lock_sock(sk); sk->sk_err = ETIMEDOUT; sk->sk_state_change(sk); bh_unlock_sock(sk); sco_sock_kill(sk); sock_put(sk); } static void sco_sock_set_timer(struct sock *sk, long timeout) { BT_DBG("sock %p state %d timeout %ld", sk, sk->sk_state, timeout); sk_reset_timer(sk, &sk->sk_timer, jiffies + timeout); } static void sco_sock_clear_timer(struct sock *sk) { BT_DBG("sock %p state %d", sk, sk->sk_state); sk_stop_timer(sk, &sk->sk_timer); } /* ---- SCO connections ---- */ static struct sco_conn *sco_conn_add(struct hci_conn *hcon) { struct hci_dev *hdev = hcon->hdev; struct sco_conn *conn = hcon->sco_data; if (conn) return conn; conn = kzalloc(sizeof(struct sco_conn), GFP_KERNEL); if (!conn) return NULL; spin_lock_init(&conn->lock); hcon->sco_data = conn; conn->hcon = hcon; if (hdev->sco_mtu > 0) conn->mtu = hdev->sco_mtu; else conn->mtu = 60; BT_DBG("hcon %p conn %p", hcon, conn); return conn; } /* Delete channel. * Must be called on the locked socket. */ static void sco_chan_del(struct sock *sk, int err) { struct sco_conn *conn; conn = sco_pi(sk)->conn; BT_DBG("sk %p, conn %p, err %d", sk, conn, err); if (conn) { sco_conn_lock(conn); conn->sk = NULL; sco_pi(sk)->conn = NULL; sco_conn_unlock(conn); if (conn->hcon) hci_conn_drop(conn->hcon); } sk->sk_state = BT_CLOSED; sk->sk_err = err; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_ZAPPED); } static void sco_conn_del(struct hci_conn *hcon, int err) { struct sco_conn *conn = hcon->sco_data; struct sock *sk; if (!conn) return; BT_DBG("hcon %p conn %p, err %d", hcon, conn, err); /* Kill socket */ sco_conn_lock(conn); sk = conn->sk; sco_conn_unlock(conn); if (sk) { sock_hold(sk); bh_lock_sock(sk); sco_sock_clear_timer(sk); sco_chan_del(sk, err); bh_unlock_sock(sk); sco_sock_kill(sk); sock_put(sk); } hcon->sco_data = NULL; kfree(conn); } static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent) { BT_DBG("conn %p", conn); sco_pi(sk)->conn = conn; conn->sk = sk; if (parent) bt_accept_enqueue(parent, sk); } static int sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent) { int err = 0; sco_conn_lock(conn); if (conn->sk) err = -EBUSY; else __sco_chan_add(conn, sk, parent); sco_conn_unlock(conn); return err; } static int sco_connect(struct sock *sk) { struct sco_conn *conn; struct hci_conn *hcon; struct hci_dev *hdev; int err, type; BT_DBG("%pMR -> %pMR", &sco_pi(sk)->src, &sco_pi(sk)->dst); hdev = hci_get_route(&sco_pi(sk)->dst, &sco_pi(sk)->src); if (!hdev) return -EHOSTUNREACH; hci_dev_lock(hdev); if (lmp_esco_capable(hdev) && !disable_esco) type = ESCO_LINK; else type = SCO_LINK; if (sco_pi(sk)->setting == BT_VOICE_TRANSPARENT && (!lmp_transp_capable(hdev) || !lmp_esco_capable(hdev))) { err = -EOPNOTSUPP; goto done; } hcon = hci_connect_sco(hdev, type, &sco_pi(sk)->dst, sco_pi(sk)->setting); if (IS_ERR(hcon)) { err = PTR_ERR(hcon); goto done; } conn = sco_conn_add(hcon); if (!conn) { hci_conn_drop(hcon); err = -ENOMEM; goto done; } /* Update source addr of the socket */ bacpy(&sco_pi(sk)->src, &hcon->src); err = sco_chan_add(conn, sk, NULL); if (err) goto done; if (hcon->state == BT_CONNECTED) { sco_sock_clear_timer(sk); sk->sk_state = BT_CONNECTED; } else { sk->sk_state = BT_CONNECT; sco_sock_set_timer(sk, sk->sk_sndtimeo); } done: hci_dev_unlock(hdev); hci_dev_put(hdev); return err; } static int sco_send_frame(struct sock *sk, struct msghdr *msg, int len) { struct sco_conn *conn = sco_pi(sk)->conn; struct sk_buff *skb; int err; /* Check outgoing MTU */ if (len > conn->mtu) return -EINVAL; BT_DBG("sk %p len %d", sk, len); skb = bt_skb_send_alloc(sk, len, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) return err; if (memcpy_from_msg(skb_put(skb, len), msg, len)) { kfree_skb(skb); return -EFAULT; } hci_send_sco(conn->hcon, skb); return len; } static void sco_recv_frame(struct sco_conn *conn, struct sk_buff *skb) { struct sock *sk; sco_conn_lock(conn); sk = conn->sk; sco_conn_unlock(conn); if (!sk) goto drop; BT_DBG("sk %p len %d", sk, skb->len); if (sk->sk_state != BT_CONNECTED) goto drop; if (!sock_queue_rcv_skb(sk, skb)) return; drop: kfree_skb(skb); } /* -------- Socket interface ---------- */ static struct sock *__sco_get_sock_listen_by_addr(bdaddr_t *ba) { struct sock *sk; sk_for_each(sk, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; if (!bacmp(&sco_pi(sk)->src, ba)) return sk; } return NULL; } /* Find socket listening on source bdaddr. * Returns closest match. */ static struct sock *sco_get_sock_listen(bdaddr_t *src) { struct sock *sk = NULL, *sk1 = NULL; read_lock(&sco_sk_list.lock); sk_for_each(sk, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; /* Exact match. */ if (!bacmp(&sco_pi(sk)->src, src)) break; /* Closest match */ if (!bacmp(&sco_pi(sk)->src, BDADDR_ANY)) sk1 = sk; } read_unlock(&sco_sk_list.lock); return sk ? sk : sk1; } static void sco_sock_destruct(struct sock *sk) { BT_DBG("sk %p", sk); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); } static void sco_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted channels */ while ((sk = bt_accept_dequeue(parent, NULL))) { sco_sock_close(sk); sco_sock_kill(sk); } parent->sk_state = BT_CLOSED; sock_set_flag(parent, SOCK_ZAPPED); } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void sco_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %d", sk, sk->sk_state); /* Kill poor orphan */ bt_sock_unlink(&sco_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static void __sco_sock_close(struct sock *sk) { BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket); switch (sk->sk_state) { case BT_LISTEN: sco_sock_cleanup_listen(sk); break; case BT_CONNECTED: case BT_CONFIG: if (sco_pi(sk)->conn->hcon) { sk->sk_state = BT_DISCONN; sco_sock_set_timer(sk, SCO_DISCONN_TIMEOUT); sco_conn_lock(sco_pi(sk)->conn); hci_conn_drop(sco_pi(sk)->conn->hcon); sco_pi(sk)->conn->hcon = NULL; sco_conn_unlock(sco_pi(sk)->conn); } else sco_chan_del(sk, ECONNRESET); break; case BT_CONNECT2: case BT_CONNECT: case BT_DISCONN: sco_chan_del(sk, ECONNRESET); break; default: sock_set_flag(sk, SOCK_ZAPPED); break; } } /* Must be called on unlocked socket. */ static void sco_sock_close(struct sock *sk) { sco_sock_clear_timer(sk); lock_sock(sk); __sco_sock_close(sk); release_sock(sk); sco_sock_kill(sk); } static void sco_sock_init(struct sock *sk, struct sock *parent) { BT_DBG("sk %p", sk); if (parent) { sk->sk_type = parent->sk_type; bt_sk(sk)->flags = bt_sk(parent)->flags; security_sk_clone(parent, sk); } } static struct proto sco_proto = { .name = "SCO", .owner = THIS_MODULE, .obj_size = sizeof(struct sco_pinfo) }; static struct sock *sco_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio, int kern) { struct sock *sk; sk = sk_alloc(net, PF_BLUETOOTH, prio, &sco_proto, kern); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); sk->sk_destruct = sco_sock_destruct; sk->sk_sndtimeo = SCO_CONN_TIMEOUT; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; sco_pi(sk)->setting = BT_VOICE_CVSD_16BIT; setup_timer(&sk->sk_timer, sco_sock_timeout, (unsigned long)sk); bt_sock_link(&sco_sk_list, sk); return sk; } static int sco_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_SEQPACKET) return -ESOCKTNOSUPPORT; sock->ops = &sco_sock_ops; sk = sco_sock_alloc(net, sock, protocol, GFP_ATOMIC, kern); if (!sk) return -ENOMEM; sco_sock_init(sk, NULL); return 0; } static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %pMR", sk, &sa->sco_bdaddr); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } bacpy(&sco_pi(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } static int sco_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err; BT_DBG("sk %p", sk); if (alen < sizeof(struct sockaddr_sco) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) return -EBADFD; if (sk->sk_type != SOCK_SEQPACKET) return -EINVAL; lock_sock(sk); /* Set destination address and psm */ bacpy(&sco_pi(sk)->dst, &sa->sco_bdaddr); err = sco_connect(sk); if (err) goto done; err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } static int sco_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; bdaddr_t *src = &sco_pi(sk)->src; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET) { err = -EINVAL; goto done; } write_lock(&sco_sk_list.lock); if (__sco_get_sock_listen_by_addr(src)) { err = -EADDRINUSE; goto unlock; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; unlock: write_unlock(&sco_sk_list.lock); done: release_sock(sk); return err; } static int sco_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DEFINE_WAIT_FUNC(wait, woken_wake_function); struct sock *sk = sock->sk, *ch; long timeo; int err = 0; lock_sock(sk); timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } ch = bt_accept_dequeue(sk, newsock); if (ch) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = wait_woken(&wait, TASK_INTERRUPTIBLE, timeo); lock_sock(sk); } remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", ch); done: release_sock(sk); return err; } static int sco_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_sco); if (peer) bacpy(&sa->sco_bdaddr, &sco_pi(sk)->dst); else bacpy(&sa->sco_bdaddr, &sco_pi(sk)->src); return 0; } static int sco_sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; lock_sock(sk); if (sk->sk_state == BT_CONNECTED) err = sco_send_frame(sk, msg, len); else err = -ENOTCONN; release_sock(sk); return err; } static void sco_conn_defer_accept(struct hci_conn *conn, u16 setting) { struct hci_dev *hdev = conn->hdev; BT_DBG("conn %p", conn); conn->state = BT_CONFIG; if (!lmp_esco_capable(hdev)) { struct hci_cp_accept_conn_req cp; bacpy(&cp.bdaddr, &conn->dst); cp.role = 0x00; /* Ignored */ hci_send_cmd(hdev, HCI_OP_ACCEPT_CONN_REQ, sizeof(cp), &cp); } else { struct hci_cp_accept_sync_conn_req cp; bacpy(&cp.bdaddr, &conn->dst); cp.pkt_type = cpu_to_le16(conn->pkt_type); cp.tx_bandwidth = cpu_to_le32(0x00001f40); cp.rx_bandwidth = cpu_to_le32(0x00001f40); cp.content_format = cpu_to_le16(setting); switch (setting & SCO_AIRMODE_MASK) { case SCO_AIRMODE_TRANSP: if (conn->pkt_type & ESCO_2EV3) cp.max_latency = cpu_to_le16(0x0008); else cp.max_latency = cpu_to_le16(0x000D); cp.retrans_effort = 0x02; break; case SCO_AIRMODE_CVSD: cp.max_latency = cpu_to_le16(0xffff); cp.retrans_effort = 0xff; break; } hci_send_cmd(hdev, HCI_OP_ACCEPT_SYNC_CONN_REQ, sizeof(cp), &cp); } } static int sco_sock_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct sco_pinfo *pi = sco_pi(sk); lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { sco_conn_defer_accept(pi->conn->hcon, pi->setting); sk->sk_state = BT_CONFIG; release_sock(sk); return 0; } release_sock(sk); return bt_sock_recvmsg(sock, msg, len, flags); } static int sco_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int len, err = 0; struct bt_voice voice; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; case BT_VOICE: if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND && sk->sk_state != BT_CONNECT2) { err = -EINVAL; break; } voice.setting = sco_pi(sk)->setting; len = min_t(unsigned int, sizeof(voice), optlen); if (copy_from_user((char *)&voice, optval, len)) { err = -EFAULT; break; } /* Explicitly check for these values */ if (voice.setting != BT_VOICE_TRANSPARENT && voice.setting != BT_VOICE_CVSD_16BIT) { err = -EINVAL; break; } sco_pi(sk)->setting = voice.setting; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct sco_options opts; struct sco_conninfo cinfo; int len, err = 0; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case SCO_OPTIONS: if (sk->sk_state != BT_CONNECTED && !(sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags))) { err = -ENOTCONN; break; } opts.mtu = sco_pi(sk)->conn->mtu; BT_DBG("mtu %d", opts.mtu); len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *)&opts, len)) err = -EFAULT; break; case SCO_CONNINFO: if (sk->sk_state != BT_CONNECTED && !(sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags))) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle; memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *)&cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int len, err = 0; struct bt_voice voice; BT_DBG("sk %p", sk); if (level == SOL_SCO) return sco_sock_getsockopt_old(sock, optname, optval, optlen); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *)optval)) err = -EFAULT; break; case BT_VOICE: voice.setting = sco_pi(sk)->setting; len = min_t(unsigned int, len, sizeof(voice)); if (copy_to_user(optval, (char *)&voice, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; sock_hold(sk); lock_sock(sk); if (!sk->sk_shutdown) { sk->sk_shutdown = SHUTDOWN_MASK; sco_sock_clear_timer(sk); __sco_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime && !(current->flags & PF_EXITING)) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } release_sock(sk); sock_put(sk); return err; } static int sco_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; sco_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime && !(current->flags & PF_EXITING)) { lock_sock(sk); err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); release_sock(sk); } sock_orphan(sk); sco_sock_kill(sk); return err; } static void sco_conn_ready(struct sco_conn *conn) { struct sock *parent; struct sock *sk = conn->sk; BT_DBG("conn %p", conn); if (sk) { sco_sock_clear_timer(sk); bh_lock_sock(sk); sk->sk_state = BT_CONNECTED; sk->sk_state_change(sk); bh_unlock_sock(sk); } else { sco_conn_lock(conn); if (!conn->hcon) { sco_conn_unlock(conn); return; } parent = sco_get_sock_listen(&conn->hcon->src); if (!parent) { sco_conn_unlock(conn); return; } bh_lock_sock(parent); sk = sco_sock_alloc(sock_net(parent), NULL, BTPROTO_SCO, GFP_ATOMIC, 0); if (!sk) { bh_unlock_sock(parent); sco_conn_unlock(conn); return; } sco_sock_init(sk, parent); bacpy(&sco_pi(sk)->src, &conn->hcon->src); bacpy(&sco_pi(sk)->dst, &conn->hcon->dst); hci_conn_hold(conn->hcon); __sco_chan_add(conn, sk, parent); if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) sk->sk_state = BT_CONNECT2; else sk->sk_state = BT_CONNECTED; /* Wake up parent */ parent->sk_data_ready(parent); bh_unlock_sock(parent); sco_conn_unlock(conn); } } /* ----- SCO interface with lower layer (HCI) ----- */ int sco_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr, __u8 *flags) { struct sock *sk; int lm = 0; BT_DBG("hdev %s, bdaddr %pMR", hdev->name, bdaddr); /* Find listening sockets */ read_lock(&sco_sk_list.lock); sk_for_each(sk, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; if (!bacmp(&sco_pi(sk)->src, &hdev->bdaddr) || !bacmp(&sco_pi(sk)->src, BDADDR_ANY)) { lm |= HCI_LM_ACCEPT; if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) *flags |= HCI_PROTO_DEFER; break; } } read_unlock(&sco_sk_list.lock); return lm; } static void sco_connect_cfm(struct hci_conn *hcon, __u8 status) { if (hcon->type != SCO_LINK && hcon->type != ESCO_LINK) return; BT_DBG("hcon %p bdaddr %pMR status %d", hcon, &hcon->dst, status); if (!status) { struct sco_conn *conn; conn = sco_conn_add(hcon); if (conn) sco_conn_ready(conn); } else sco_conn_del(hcon, bt_to_errno(status)); } static void sco_disconn_cfm(struct hci_conn *hcon, __u8 reason) { if (hcon->type != SCO_LINK && hcon->type != ESCO_LINK) return; BT_DBG("hcon %p reason %d", hcon, reason); sco_conn_del(hcon, bt_to_errno(reason)); } void sco_recv_scodata(struct hci_conn *hcon, struct sk_buff *skb) { struct sco_conn *conn = hcon->sco_data; if (!conn) goto drop; BT_DBG("conn %p len %d", conn, skb->len); if (skb->len) { sco_recv_frame(conn, skb); return; } drop: kfree_skb(skb); } static struct hci_cb sco_cb = { .name = "SCO", .connect_cfm = sco_connect_cfm, .disconn_cfm = sco_disconn_cfm, }; static int sco_debugfs_show(struct seq_file *f, void *p) { struct sock *sk; read_lock(&sco_sk_list.lock); sk_for_each(sk, &sco_sk_list.head) { seq_printf(f, "%pMR %pMR %d\n", &sco_pi(sk)->src, &sco_pi(sk)->dst, sk->sk_state); } read_unlock(&sco_sk_list.lock); return 0; } static int sco_debugfs_open(struct inode *inode, struct file *file) { return single_open(file, sco_debugfs_show, inode->i_private); } static const struct file_operations sco_debugfs_fops = { .open = sco_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *sco_debugfs; static const struct proto_ops sco_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = sco_sock_release, .bind = sco_sock_bind, .connect = sco_sock_connect, .listen = sco_sock_listen, .accept = sco_sock_accept, .getname = sco_sock_getname, .sendmsg = sco_sock_sendmsg, .recvmsg = sco_sock_recvmsg, .poll = bt_sock_poll, .ioctl = bt_sock_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = sco_sock_shutdown, .setsockopt = sco_sock_setsockopt, .getsockopt = sco_sock_getsockopt }; static const struct net_proto_family sco_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = sco_sock_create, }; int __init sco_init(void) { int err; BUILD_BUG_ON(sizeof(struct sockaddr_sco) > sizeof(struct sockaddr)); err = proto_register(&sco_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_SCO, &sco_sock_family_ops); if (err < 0) { BT_ERR("SCO socket registration failed"); goto error; } err = bt_procfs_init(&init_net, "sco", &sco_sk_list, NULL); if (err < 0) { BT_ERR("Failed to create SCO proc file"); bt_sock_unregister(BTPROTO_SCO); goto error; } BT_INFO("SCO socket layer initialized"); hci_register_cb(&sco_cb); if (IS_ERR_OR_NULL(bt_debugfs)) return 0; sco_debugfs = debugfs_create_file("sco", 0444, bt_debugfs, NULL, &sco_debugfs_fops); return 0; error: proto_unregister(&sco_proto); return err; } void sco_exit(void) { bt_procfs_cleanup(&init_net, "sco"); debugfs_remove(sco_debugfs); hci_unregister_cb(&sco_cb); bt_sock_unregister(BTPROTO_SCO); proto_unregister(&sco_proto); } module_param(disable_esco, bool, 0644); MODULE_PARM_DESC(disable_esco, "Disable eSCO connection creation");
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1791_0
crossvul-cpp_data_bad_3827_0
/* * NET An implementation of the SOCKET network access protocol. * * Version: @(#)socket.c 1.1.93 18/02/95 * * Authors: Orest Zborowski, <obz@Kodak.COM> * Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * * Fixes: * Anonymous : NOTSOCK/BADF cleanup. Error fix in * shutdown() * Alan Cox : verify_area() fixes * Alan Cox : Removed DDI * Jonathan Kamens : SOCK_DGRAM reconnect bug * Alan Cox : Moved a load of checks to the very * top level. * Alan Cox : Move address structures to/from user * mode above the protocol layers. * Rob Janssen : Allow 0 length sends. * Alan Cox : Asynchronous I/O support (cribbed from the * tty drivers). * Niibe Yutaka : Asynchronous I/O for writes (4.4BSD style) * Jeff Uphoff : Made max number of sockets command-line * configurable. * Matti Aarnio : Made the number of sockets dynamic, * to be allocated when needed, and mr. * Uphoff's max is used as max to be * allowed to allocate. * Linus : Argh. removed all the socket allocation * altogether: it's in the inode now. * Alan Cox : Made sock_alloc()/sock_release() public * for NetROM and future kernel nfsd type * stuff. * Alan Cox : sendmsg/recvmsg basics. * Tom Dyas : Export net symbols. * Marcin Dalecki : Fixed problems with CONFIG_NET="n". * Alan Cox : Added thread locking to sys_* calls * for sockets. May have errors at the * moment. * Kevin Buhr : Fixed the dumb errors in the above. * Andi Kleen : Some small cleanups, optimizations, * and fixed a copy_from_user() bug. * Tigran Aivazian : sys_send(args) calls sys_sendto(args, NULL, 0) * Tigran Aivazian : Made listen(2) backlog sanity checks * protocol-independent * * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * * This module is effectively the top level interface to the BSD socket * paradigm. * * Based upon Swansea University Computer Society NET3.039 */ #include <linux/mm.h> #include <linux/socket.h> #include <linux/file.h> #include <linux/net.h> #include <linux/interrupt.h> #include <linux/thread_info.h> #include <linux/rcupdate.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/mutex.h> #include <linux/wanrouter.h> #include <linux/if_bridge.h> #include <linux/if_frad.h> #include <linux/if_vlan.h> #include <linux/init.h> #include <linux/poll.h> #include <linux/cache.h> #include <linux/module.h> #include <linux/highmem.h> #include <linux/mount.h> #include <linux/security.h> #include <linux/syscalls.h> #include <linux/compat.h> #include <linux/kmod.h> #include <linux/audit.h> #include <linux/wireless.h> #include <linux/nsproxy.h> #include <linux/magic.h> #include <linux/slab.h> #include <asm/uaccess.h> #include <asm/unistd.h> #include <net/compat.h> #include <net/wext.h> #include <net/cls_cgroup.h> #include <net/sock.h> #include <linux/netfilter.h> #include <linux/if_tun.h> #include <linux/ipv6_route.h> #include <linux/route.h> #include <linux/sockios.h> #include <linux/atalk.h> static int sock_no_open(struct inode *irrelevant, struct file *dontcare); static ssize_t sock_aio_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos); static ssize_t sock_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos); static int sock_mmap(struct file *file, struct vm_area_struct *vma); static int sock_close(struct inode *inode, struct file *file); static unsigned int sock_poll(struct file *file, struct poll_table_struct *wait); static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #ifdef CONFIG_COMPAT static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg); #endif static int sock_fasync(int fd, struct file *filp, int on); static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more); static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags); /* * Socket files have a set of 'special' operations as well as the generic file ones. These don't appear * in the operation structures but are done directly via the socketcall() multiplexor. */ static const struct file_operations socket_file_ops = { .owner = THIS_MODULE, .llseek = no_llseek, .aio_read = sock_aio_read, .aio_write = sock_aio_write, .poll = sock_poll, .unlocked_ioctl = sock_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = compat_sock_ioctl, #endif .mmap = sock_mmap, .open = sock_no_open, /* special open code to disallow open via /proc */ .release = sock_close, .fasync = sock_fasync, .sendpage = sock_sendpage, .splice_write = generic_splice_sendpage, .splice_read = sock_splice_read, }; /* * The protocol list. Each protocol is registered in here. */ static DEFINE_SPINLOCK(net_family_lock); static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly; /* * Statistics counters of the socket lists */ static DEFINE_PER_CPU(int, sockets_in_use); /* * Support routines. * Move socket addresses back and forth across the kernel/user * divide and look after the messy bits. */ /** * move_addr_to_kernel - copy a socket address into kernel space * @uaddr: Address in user space * @kaddr: Address in kernel space * @ulen: Length in user space * * The address is copied into kernel space. If the provided address is * too long an error code of -EINVAL is returned. If the copy gives * invalid addresses -EFAULT is returned. On a success 0 is returned. */ int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr) { if (ulen < 0 || ulen > sizeof(struct sockaddr_storage)) return -EINVAL; if (ulen == 0) return 0; if (copy_from_user(kaddr, uaddr, ulen)) return -EFAULT; return audit_sockaddr(ulen, kaddr); } /** * move_addr_to_user - copy an address to user space * @kaddr: kernel space address * @klen: length of address in kernel * @uaddr: user space address * @ulen: pointer to user length field * * The value pointed to by ulen on entry is the buffer length available. * This is overwritten with the buffer space used. -EINVAL is returned * if an overlong buffer is specified or a negative buffer size. -EFAULT * is returned if either the buffer or the length field are not * accessible. * After copying the data up to the limit the user specifies, the true * length of the data is written over the length limit the user * specified. Zero is returned for a success. */ static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen, void __user *uaddr, int __user *ulen) { int err; int len; err = get_user(len, ulen); if (err) return err; if (len > klen) len = klen; if (len < 0 || len > sizeof(struct sockaddr_storage)) return -EINVAL; if (len) { if (audit_sockaddr(klen, kaddr)) return -ENOMEM; if (copy_to_user(uaddr, kaddr, len)) return -EFAULT; } /* * "fromlen shall refer to the value before truncation.." * 1003.1g */ return __put_user(klen, ulen); } static struct kmem_cache *sock_inode_cachep __read_mostly; static struct inode *sock_alloc_inode(struct super_block *sb) { struct socket_alloc *ei; struct socket_wq *wq; ei = kmem_cache_alloc(sock_inode_cachep, GFP_KERNEL); if (!ei) return NULL; wq = kmalloc(sizeof(*wq), GFP_KERNEL); if (!wq) { kmem_cache_free(sock_inode_cachep, ei); return NULL; } init_waitqueue_head(&wq->wait); wq->fasync_list = NULL; RCU_INIT_POINTER(ei->socket.wq, wq); ei->socket.state = SS_UNCONNECTED; ei->socket.flags = 0; ei->socket.ops = NULL; ei->socket.sk = NULL; ei->socket.file = NULL; return &ei->vfs_inode; } static void sock_destroy_inode(struct inode *inode) { struct socket_alloc *ei; struct socket_wq *wq; ei = container_of(inode, struct socket_alloc, vfs_inode); wq = rcu_dereference_protected(ei->socket.wq, 1); kfree_rcu(wq, rcu); kmem_cache_free(sock_inode_cachep, ei); } static void init_once(void *foo) { struct socket_alloc *ei = (struct socket_alloc *)foo; inode_init_once(&ei->vfs_inode); } static int init_inodecache(void) { sock_inode_cachep = kmem_cache_create("sock_inode_cache", sizeof(struct socket_alloc), 0, (SLAB_HWCACHE_ALIGN | SLAB_RECLAIM_ACCOUNT | SLAB_MEM_SPREAD), init_once); if (sock_inode_cachep == NULL) return -ENOMEM; return 0; } static const struct super_operations sockfs_ops = { .alloc_inode = sock_alloc_inode, .destroy_inode = sock_destroy_inode, .statfs = simple_statfs, }; /* * sockfs_dname() is called from d_path(). */ static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen) { return dynamic_dname(dentry, buffer, buflen, "socket:[%lu]", dentry->d_inode->i_ino); } static const struct dentry_operations sockfs_dentry_operations = { .d_dname = sockfs_dname, }; static struct dentry *sockfs_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_pseudo(fs_type, "socket:", &sockfs_ops, &sockfs_dentry_operations, SOCKFS_MAGIC); } static struct vfsmount *sock_mnt __read_mostly; static struct file_system_type sock_fs_type = { .name = "sockfs", .mount = sockfs_mount, .kill_sb = kill_anon_super, }; /* * Obtains the first available file descriptor and sets it up for use. * * These functions create file structures and maps them to fd space * of the current process. On success it returns file descriptor * and file struct implicitly stored in sock->file. * Note that another thread may close file descriptor before we return * from this function. We use the fact that now we do not refer * to socket after mapping. If one day we will need it, this * function will increment ref. count on file by 1. * * In any case returned fd MAY BE not valid! * This race condition is unavoidable * with shared fd spaces, we cannot solve it inside kernel, * but we take care of internal coherence yet. */ static int sock_alloc_file(struct socket *sock, struct file **f, int flags) { struct qstr name = { .name = "" }; struct path path; struct file *file; int fd; fd = get_unused_fd_flags(flags); if (unlikely(fd < 0)) return fd; path.dentry = d_alloc_pseudo(sock_mnt->mnt_sb, &name); if (unlikely(!path.dentry)) { put_unused_fd(fd); return -ENOMEM; } path.mnt = mntget(sock_mnt); d_instantiate(path.dentry, SOCK_INODE(sock)); SOCK_INODE(sock)->i_fop = &socket_file_ops; file = alloc_file(&path, FMODE_READ | FMODE_WRITE, &socket_file_ops); if (unlikely(!file)) { /* drop dentry, keep inode */ ihold(path.dentry->d_inode); path_put(&path); put_unused_fd(fd); return -ENFILE; } sock->file = file; file->f_flags = O_RDWR | (flags & O_NONBLOCK); file->f_pos = 0; file->private_data = sock; *f = file; return fd; } int sock_map_fd(struct socket *sock, int flags) { struct file *newfile; int fd = sock_alloc_file(sock, &newfile, flags); if (likely(fd >= 0)) fd_install(fd, newfile); return fd; } EXPORT_SYMBOL(sock_map_fd); struct socket *sock_from_file(struct file *file, int *err) { if (file->f_op == &socket_file_ops) return file->private_data; /* set in sock_map_fd */ *err = -ENOTSOCK; return NULL; } EXPORT_SYMBOL(sock_from_file); /** * sockfd_lookup - Go from a file number to its socket slot * @fd: file handle * @err: pointer to an error code return * * The file handle passed in is locked and the socket it is bound * too is returned. If an error occurs the err pointer is overwritten * with a negative errno code and NULL is returned. The function checks * for both invalid handles and passing a handle which is not a socket. * * On a success the socket object pointer is returned. */ struct socket *sockfd_lookup(int fd, int *err) { struct file *file; struct socket *sock; file = fget(fd); if (!file) { *err = -EBADF; return NULL; } sock = sock_from_file(file, err); if (!sock) fput(file); return sock; } EXPORT_SYMBOL(sockfd_lookup); static struct socket *sockfd_lookup_light(int fd, int *err, int *fput_needed) { struct file *file; struct socket *sock; *err = -EBADF; file = fget_light(fd, fput_needed); if (file) { sock = sock_from_file(file, err); if (sock) return sock; fput_light(file, *fput_needed); } return NULL; } /** * sock_alloc - allocate a socket * * Allocate a new inode and socket object. The two are bound together * and initialised. The socket is then returned. If we are out of inodes * NULL is returned. */ static struct socket *sock_alloc(void) { struct inode *inode; struct socket *sock; inode = new_inode_pseudo(sock_mnt->mnt_sb); if (!inode) return NULL; sock = SOCKET_I(inode); kmemcheck_annotate_bitfield(sock, type); inode->i_ino = get_next_ino(); inode->i_mode = S_IFSOCK | S_IRWXUGO; inode->i_uid = current_fsuid(); inode->i_gid = current_fsgid(); this_cpu_add(sockets_in_use, 1); return sock; } /* * In theory you can't get an open on this inode, but /proc provides * a back door. Remember to keep it shut otherwise you'll let the * creepy crawlies in. */ static int sock_no_open(struct inode *irrelevant, struct file *dontcare) { return -ENXIO; } const struct file_operations bad_sock_fops = { .owner = THIS_MODULE, .open = sock_no_open, .llseek = noop_llseek, }; /** * sock_release - close a socket * @sock: socket to close * * The socket is released from the protocol stack if it has a release * callback, and the inode is then released if the socket is bound to * an inode not a file. */ void sock_release(struct socket *sock) { if (sock->ops) { struct module *owner = sock->ops->owner; sock->ops->release(sock); sock->ops = NULL; module_put(owner); } if (rcu_dereference_protected(sock->wq, 1)->fasync_list) printk(KERN_ERR "sock_release: fasync list not empty!\n"); if (test_bit(SOCK_EXTERNALLY_ALLOCATED, &sock->flags)) return; this_cpu_sub(sockets_in_use, 1); if (!sock->file) { iput(SOCK_INODE(sock)); return; } sock->file = NULL; } EXPORT_SYMBOL(sock_release); int sock_tx_timestamp(struct sock *sk, __u8 *tx_flags) { *tx_flags = 0; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_HARDWARE)) *tx_flags |= SKBTX_HW_TSTAMP; if (sock_flag(sk, SOCK_TIMESTAMPING_TX_SOFTWARE)) *tx_flags |= SKBTX_SW_TSTAMP; if (sock_flag(sk, SOCK_WIFI_STATUS)) *tx_flags |= SKBTX_WIFI_STATUS; return 0; } EXPORT_SYMBOL(sock_tx_timestamp); static inline int __sock_sendmsg_nosec(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { struct sock_iocb *si = kiocb_to_siocb(iocb); sock_update_classid(sock->sk); si->sock = sock; si->scm = NULL; si->msg = msg; si->size = size; return sock->ops->sendmsg(iocb, sock, msg, size); } static inline int __sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size) { int err = security_socket_sendmsg(sock, msg, size); return err ?: __sock_sendmsg_nosec(iocb, sock, msg, size); } int sock_sendmsg(struct socket *sock, struct msghdr *msg, size_t size) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_sendmsg(&iocb, sock, msg, size); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } EXPORT_SYMBOL(sock_sendmsg); static int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_sendmsg_nosec(&iocb, sock, msg, size); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } int kernel_sendmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size) { mm_segment_t oldfs = get_fs(); int result; set_fs(KERNEL_DS); /* * the following is safe, since for compiler definitions of kvec and * iovec are identical, yielding the same in-core layout and alignment */ msg->msg_iov = (struct iovec *)vec; msg->msg_iovlen = num; result = sock_sendmsg(sock, msg, size); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_sendmsg); static int ktime2ts(ktime_t kt, struct timespec *ts) { if (kt.tv64) { *ts = ktime_to_timespec(kt); return 1; } else { return 0; } } /* * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP) */ void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP); struct timespec ts[3]; int empty = 1; struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb); /* Race occurred between timestamp enabling and packet receiving. Fill in the current time for now. */ if (need_software_tstamp && skb->tstamp.tv64 == 0) __net_timestamp(skb); if (need_software_tstamp) { if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) { struct timeval tv; skb_get_timestamp(skb, &tv); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(tv), &tv); } else { skb_get_timestampns(skb, &ts[0]); put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPNS, sizeof(ts[0]), &ts[0]); } } memset(ts, 0, sizeof(ts)); if (skb->tstamp.tv64 && sock_flag(sk, SOCK_TIMESTAMPING_SOFTWARE)) { skb_get_timestampns(skb, ts + 0); empty = 0; } if (shhwtstamps) { if (sock_flag(sk, SOCK_TIMESTAMPING_SYS_HARDWARE) && ktime2ts(shhwtstamps->syststamp, ts + 1)) empty = 0; if (sock_flag(sk, SOCK_TIMESTAMPING_RAW_HARDWARE) && ktime2ts(shhwtstamps->hwtstamp, ts + 2)) empty = 0; } if (!empty) put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING, sizeof(ts), &ts); } EXPORT_SYMBOL_GPL(__sock_recv_timestamp); void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { int ack; if (!sock_flag(sk, SOCK_WIFI_STATUS)) return; if (!skb->wifi_acked_valid) return; ack = skb->wifi_acked; put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack); } EXPORT_SYMBOL_GPL(__sock_recv_wifi_status); static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && skb->dropcount) put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL, sizeof(__u32), &skb->dropcount); } void __sock_recv_ts_and_drops(struct msghdr *msg, struct sock *sk, struct sk_buff *skb) { sock_recv_timestamp(msg, sk, skb); sock_recv_drops(msg, sk, skb); } EXPORT_SYMBOL_GPL(__sock_recv_ts_and_drops); static inline int __sock_recvmsg_nosec(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock_iocb *si = kiocb_to_siocb(iocb); sock_update_classid(sock->sk); si->sock = sock; si->scm = NULL; si->msg = msg; si->size = size; si->flags = flags; return sock->ops->recvmsg(iocb, sock, msg, size, flags); } static inline int __sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { int err = security_socket_recvmsg(sock, msg, size, flags); return err ?: __sock_recvmsg_nosec(iocb, sock, msg, size, flags); } int sock_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_recvmsg(&iocb, sock, msg, size, flags); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } EXPORT_SYMBOL(sock_recvmsg); static int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct kiocb iocb; struct sock_iocb siocb; int ret; init_sync_kiocb(&iocb, NULL); iocb.private = &siocb; ret = __sock_recvmsg_nosec(&iocb, sock, msg, size, flags); if (-EIOCBQUEUED == ret) ret = wait_on_sync_kiocb(&iocb); return ret; } /** * kernel_recvmsg - Receive a message from a socket (kernel space) * @sock: The socket to receive the message from * @msg: Received message * @vec: Input s/g array for message data * @num: Size of input s/g array * @size: Number of bytes to read * @flags: Message flags (MSG_DONTWAIT, etc...) * * On return the msg structure contains the scatter/gather array passed in the * vec argument. The array is modified so that it consists of the unfilled * portion of the original array. * * The returned value is the total number of bytes received, or an error. */ int kernel_recvmsg(struct socket *sock, struct msghdr *msg, struct kvec *vec, size_t num, size_t size, int flags) { mm_segment_t oldfs = get_fs(); int result; set_fs(KERNEL_DS); /* * the following is safe, since for compiler definitions of kvec and * iovec are identical, yielding the same in-core layout and alignment */ msg->msg_iov = (struct iovec *)vec, msg->msg_iovlen = num; result = sock_recvmsg(sock, msg, size, flags); set_fs(oldfs); return result; } EXPORT_SYMBOL(kernel_recvmsg); static void sock_aio_dtor(struct kiocb *iocb) { kfree(iocb->private); } static ssize_t sock_sendpage(struct file *file, struct page *page, int offset, size_t size, loff_t *ppos, int more) { struct socket *sock; int flags; sock = file->private_data; flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; /* more is a combination of MSG_MORE and MSG_SENDPAGE_NOTLAST */ flags |= more; return kernel_sendpage(sock, page, offset, size, flags); } static ssize_t sock_splice_read(struct file *file, loff_t *ppos, struct pipe_inode_info *pipe, size_t len, unsigned int flags) { struct socket *sock = file->private_data; if (unlikely(!sock->ops->splice_read)) return -EINVAL; sock_update_classid(sock->sk); return sock->ops->splice_read(sock, ppos, pipe, len, flags); } static struct sock_iocb *alloc_sock_iocb(struct kiocb *iocb, struct sock_iocb *siocb) { if (!is_sync_kiocb(iocb)) { siocb = kmalloc(sizeof(*siocb), GFP_KERNEL); if (!siocb) return NULL; iocb->ki_dtor = sock_aio_dtor; } siocb->kiocb = iocb; iocb->private = siocb; return siocb; } static ssize_t do_sock_read(struct msghdr *msg, struct kiocb *iocb, struct file *file, const struct iovec *iov, unsigned long nr_segs) { struct socket *sock = file->private_data; size_t size = 0; int i; for (i = 0; i < nr_segs; i++) size += iov[i].iov_len; msg->msg_name = NULL; msg->msg_namelen = 0; msg->msg_control = NULL; msg->msg_controllen = 0; msg->msg_iov = (struct iovec *)iov; msg->msg_iovlen = nr_segs; msg->msg_flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; return __sock_recvmsg(iocb, sock, msg, size, msg->msg_flags); } static ssize_t sock_aio_read(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct sock_iocb siocb, *x; if (pos != 0) return -ESPIPE; if (iocb->ki_left == 0) /* Match SYS5 behaviour */ return 0; x = alloc_sock_iocb(iocb, &siocb); if (!x) return -ENOMEM; return do_sock_read(&x->async_msg, iocb, iocb->ki_filp, iov, nr_segs); } static ssize_t do_sock_write(struct msghdr *msg, struct kiocb *iocb, struct file *file, const struct iovec *iov, unsigned long nr_segs) { struct socket *sock = file->private_data; size_t size = 0; int i; for (i = 0; i < nr_segs; i++) size += iov[i].iov_len; msg->msg_name = NULL; msg->msg_namelen = 0; msg->msg_control = NULL; msg->msg_controllen = 0; msg->msg_iov = (struct iovec *)iov; msg->msg_iovlen = nr_segs; msg->msg_flags = (file->f_flags & O_NONBLOCK) ? MSG_DONTWAIT : 0; if (sock->type == SOCK_SEQPACKET) msg->msg_flags |= MSG_EOR; return __sock_sendmsg(iocb, sock, msg, size); } static ssize_t sock_aio_write(struct kiocb *iocb, const struct iovec *iov, unsigned long nr_segs, loff_t pos) { struct sock_iocb siocb, *x; if (pos != 0) return -ESPIPE; x = alloc_sock_iocb(iocb, &siocb); if (!x) return -ENOMEM; return do_sock_write(&x->async_msg, iocb, iocb->ki_filp, iov, nr_segs); } /* * Atomic setting of ioctl hooks to avoid race * with module unload. */ static DEFINE_MUTEX(br_ioctl_mutex); static int (*br_ioctl_hook) (struct net *, unsigned int cmd, void __user *arg); void brioctl_set(int (*hook) (struct net *, unsigned int, void __user *)) { mutex_lock(&br_ioctl_mutex); br_ioctl_hook = hook; mutex_unlock(&br_ioctl_mutex); } EXPORT_SYMBOL(brioctl_set); static DEFINE_MUTEX(vlan_ioctl_mutex); static int (*vlan_ioctl_hook) (struct net *, void __user *arg); void vlan_ioctl_set(int (*hook) (struct net *, void __user *)) { mutex_lock(&vlan_ioctl_mutex); vlan_ioctl_hook = hook; mutex_unlock(&vlan_ioctl_mutex); } EXPORT_SYMBOL(vlan_ioctl_set); static DEFINE_MUTEX(dlci_ioctl_mutex); static int (*dlci_ioctl_hook) (unsigned int, void __user *); void dlci_ioctl_set(int (*hook) (unsigned int, void __user *)) { mutex_lock(&dlci_ioctl_mutex); dlci_ioctl_hook = hook; mutex_unlock(&dlci_ioctl_mutex); } EXPORT_SYMBOL(dlci_ioctl_set); static long sock_do_ioctl(struct net *net, struct socket *sock, unsigned int cmd, unsigned long arg) { int err; void __user *argp = (void __user *)arg; err = sock->ops->ioctl(sock, cmd, arg); /* * If this ioctl is unknown try to hand it down * to the NIC driver. */ if (err == -ENOIOCTLCMD) err = dev_ioctl(net, cmd, argp); return err; } /* * With an ioctl, arg may well be a user mode pointer, but we don't know * what to do with it - that's up to the protocol still. */ static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg) { struct socket *sock; struct sock *sk; void __user *argp = (void __user *)arg; int pid, err; struct net *net; sock = file->private_data; sk = sock->sk; net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) { err = dev_ioctl(net, cmd, argp); } else #ifdef CONFIG_WEXT_CORE if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) { err = dev_ioctl(net, cmd, argp); } else #endif switch (cmd) { case FIOSETOWN: case SIOCSPGRP: err = -EFAULT; if (get_user(pid, (int __user *)argp)) break; err = f_setown(sock->file, pid, 1); break; case FIOGETOWN: case SIOCGPGRP: err = put_user(f_getown(sock->file), (int __user *)argp); break; case SIOCGIFBR: case SIOCSIFBR: case SIOCBRADDBR: case SIOCBRDELBR: err = -ENOPKG; if (!br_ioctl_hook) request_module("bridge"); mutex_lock(&br_ioctl_mutex); if (br_ioctl_hook) err = br_ioctl_hook(net, cmd, argp); mutex_unlock(&br_ioctl_mutex); break; case SIOCGIFVLAN: case SIOCSIFVLAN: err = -ENOPKG; if (!vlan_ioctl_hook) request_module("8021q"); mutex_lock(&vlan_ioctl_mutex); if (vlan_ioctl_hook) err = vlan_ioctl_hook(net, argp); mutex_unlock(&vlan_ioctl_mutex); break; case SIOCADDDLCI: case SIOCDELDLCI: err = -ENOPKG; if (!dlci_ioctl_hook) request_module("dlci"); mutex_lock(&dlci_ioctl_mutex); if (dlci_ioctl_hook) err = dlci_ioctl_hook(cmd, argp); mutex_unlock(&dlci_ioctl_mutex); break; default: err = sock_do_ioctl(net, sock, cmd, arg); break; } return err; } int sock_create_lite(int family, int type, int protocol, struct socket **res) { int err; struct socket *sock = NULL; err = security_socket_create(family, type, protocol, 1); if (err) goto out; sock = sock_alloc(); if (!sock) { err = -ENOMEM; goto out; } sock->type = type; err = security_socket_post_create(sock, family, type, protocol, 1); if (err) goto out_release; out: *res = sock; return err; out_release: sock_release(sock); sock = NULL; goto out; } EXPORT_SYMBOL(sock_create_lite); /* No kernel lock held - perfect */ static unsigned int sock_poll(struct file *file, poll_table *wait) { struct socket *sock; /* * We can't return errors to poll, so it's either yes or no. */ sock = file->private_data; return sock->ops->poll(file, sock, wait); } static int sock_mmap(struct file *file, struct vm_area_struct *vma) { struct socket *sock = file->private_data; return sock->ops->mmap(file, sock, vma); } static int sock_close(struct inode *inode, struct file *filp) { /* * It was possible the inode is NULL we were * closing an unfinished socket. */ if (!inode) { printk(KERN_DEBUG "sock_close: NULL inode\n"); return 0; } sock_release(SOCKET_I(inode)); return 0; } /* * Update the socket async list * * Fasync_list locking strategy. * * 1. fasync_list is modified only under process context socket lock * i.e. under semaphore. * 2. fasync_list is used under read_lock(&sk->sk_callback_lock) * or under socket lock */ static int sock_fasync(int fd, struct file *filp, int on) { struct socket *sock = filp->private_data; struct sock *sk = sock->sk; struct socket_wq *wq; if (sk == NULL) return -EINVAL; lock_sock(sk); wq = rcu_dereference_protected(sock->wq, sock_owned_by_user(sk)); fasync_helper(fd, filp, on, &wq->fasync_list); if (!wq->fasync_list) sock_reset_flag(sk, SOCK_FASYNC); else sock_set_flag(sk, SOCK_FASYNC); release_sock(sk); return 0; } /* This function may be called only under socket lock or callback_lock or rcu_lock */ int sock_wake_async(struct socket *sock, int how, int band) { struct socket_wq *wq; if (!sock) return -1; rcu_read_lock(); wq = rcu_dereference(sock->wq); if (!wq || !wq->fasync_list) { rcu_read_unlock(); return -1; } switch (how) { case SOCK_WAKE_WAITD: if (test_bit(SOCK_ASYNC_WAITDATA, &sock->flags)) break; goto call_kill; case SOCK_WAKE_SPACE: if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sock->flags)) break; /* fall through */ case SOCK_WAKE_IO: call_kill: kill_fasync(&wq->fasync_list, SIGIO, band); break; case SOCK_WAKE_URG: kill_fasync(&wq->fasync_list, SIGURG, band); } rcu_read_unlock(); return 0; } EXPORT_SYMBOL(sock_wake_async); int __sock_create(struct net *net, int family, int type, int protocol, struct socket **res, int kern) { int err; struct socket *sock; const struct net_proto_family *pf; /* * Check protocol is in range */ if (family < 0 || family >= NPROTO) return -EAFNOSUPPORT; if (type < 0 || type >= SOCK_MAX) return -EINVAL; /* Compatibility. This uglymoron is moved from INET layer to here to avoid deadlock in module load. */ if (family == PF_INET && type == SOCK_PACKET) { static int warned; if (!warned) { warned = 1; printk(KERN_INFO "%s uses obsolete (PF_INET,SOCK_PACKET)\n", current->comm); } family = PF_PACKET; } err = security_socket_create(family, type, protocol, kern); if (err) return err; /* * Allocate the socket and allow the family to set things up. if * the protocol is 0, the family is instructed to select an appropriate * default. */ sock = sock_alloc(); if (!sock) { net_warn_ratelimited("socket: no more sockets\n"); return -ENFILE; /* Not exactly a match, but its the closest posix thing */ } sock->type = type; #ifdef CONFIG_MODULES /* Attempt to load a protocol module if the find failed. * * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user * requested real, full-featured networking support upon configuration. * Otherwise module support will break! */ if (rcu_access_pointer(net_families[family]) == NULL) request_module("net-pf-%d", family); #endif rcu_read_lock(); pf = rcu_dereference(net_families[family]); err = -EAFNOSUPPORT; if (!pf) goto out_release; /* * We will call the ->create function, that possibly is in a loadable * module, so we have to bump that loadable module refcnt first. */ if (!try_module_get(pf->owner)) goto out_release; /* Now protected by module ref count */ rcu_read_unlock(); err = pf->create(net, sock, protocol, kern); if (err < 0) goto out_module_put; /* * Now to bump the refcnt of the [loadable] module that owns this * socket at sock_release time we decrement its refcnt. */ if (!try_module_get(sock->ops->owner)) goto out_module_busy; /* * Now that we're done with the ->create function, the [loadable] * module can have its refcnt decremented */ module_put(pf->owner); err = security_socket_post_create(sock, family, type, protocol, kern); if (err) goto out_sock_release; *res = sock; return 0; out_module_busy: err = -EAFNOSUPPORT; out_module_put: sock->ops = NULL; module_put(pf->owner); out_sock_release: sock_release(sock); return err; out_release: rcu_read_unlock(); goto out_sock_release; } EXPORT_SYMBOL(__sock_create); int sock_create(int family, int type, int protocol, struct socket **res) { return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0); } EXPORT_SYMBOL(sock_create); int sock_create_kern(int family, int type, int protocol, struct socket **res) { return __sock_create(&init_net, family, type, protocol, res, 1); } EXPORT_SYMBOL(sock_create_kern); SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol) { int retval; struct socket *sock; int flags; /* Check the SOCK_* constants for consistency. */ BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC); BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK); BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK); flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; retval = sock_create(family, type, protocol, &sock); if (retval < 0) goto out; retval = sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK)); if (retval < 0) goto out_release; out: /* It may be already another descriptor 8) Not kernel problem. */ return retval; out_release: sock_release(sock); return retval; } /* * Create a pair of connected sockets. */ SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol, int __user *, usockvec) { struct socket *sock1, *sock2; int fd1, fd2, err; struct file *newfile1, *newfile2; int flags; flags = type & ~SOCK_TYPE_MASK; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; type &= SOCK_TYPE_MASK; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; /* * Obtain the first socket and check if the underlying protocol * supports the socketpair call. */ err = sock_create(family, type, protocol, &sock1); if (err < 0) goto out; err = sock_create(family, type, protocol, &sock2); if (err < 0) goto out_release_1; err = sock1->ops->socketpair(sock1, sock2); if (err < 0) goto out_release_both; fd1 = sock_alloc_file(sock1, &newfile1, flags); if (unlikely(fd1 < 0)) { err = fd1; goto out_release_both; } fd2 = sock_alloc_file(sock2, &newfile2, flags); if (unlikely(fd2 < 0)) { err = fd2; fput(newfile1); put_unused_fd(fd1); sock_release(sock2); goto out; } audit_fd_pair(fd1, fd2); fd_install(fd1, newfile1); fd_install(fd2, newfile2); /* fd1 and fd2 may be already another descriptors. * Not kernel problem. */ err = put_user(fd1, &usockvec[0]); if (!err) err = put_user(fd2, &usockvec[1]); if (!err) return 0; sys_close(fd2); sys_close(fd1); return err; out_release_both: sock_release(sock2); out_release_1: sock_release(sock1); out: return err; } /* * Bind a name to a socket. Nothing much to do here since it's * the protocol's responsibility to handle the local address. * * We move the socket address to kernel space before we call * the protocol layer (having also checked the address is ok). */ SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { err = move_addr_to_kernel(umyaddr, addrlen, &address); if (err >= 0) { err = security_socket_bind(sock, (struct sockaddr *)&address, addrlen); if (!err) err = sock->ops->bind(sock, (struct sockaddr *) &address, addrlen); } fput_light(sock->file, fput_needed); } return err; } /* * Perform a listen. Basically, we allow the protocol to do anything * necessary for a listen, and if that works, we mark the socket as * ready for listening. */ SYSCALL_DEFINE2(listen, int, fd, int, backlog) { struct socket *sock; int err, fput_needed; int somaxconn; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock) { somaxconn = sock_net(sock->sk)->core.sysctl_somaxconn; if ((unsigned int)backlog > somaxconn) backlog = somaxconn; err = security_socket_listen(sock, backlog); if (!err) err = sock->ops->listen(sock, backlog); fput_light(sock->file, fput_needed); } return err; } /* * For accept, we attempt to create a new socket, set up the link * with the client, wake up the client, then return the new * connected fd. We collect the address of the connector in kernel * space and move it to user at the very end. This is unclean because * we open the socket then return an error. * * 1003.1g adds the ability to recvmsg() to query connection pending * status to recvmsg. We need to add that support in a way thats * clean when we restucture accept also. */ SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen, int, flags) { struct socket *sock, *newsock; struct file *newfile; int err, len, newfd, fput_needed; struct sockaddr_storage address; if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK)) return -EINVAL; if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK)) flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = -ENFILE; newsock = sock_alloc(); if (!newsock) goto out_put; newsock->type = sock->type; newsock->ops = sock->ops; /* * We don't need try_module_get here, as the listening socket (sock) * has the protocol module (sock->ops->owner) held. */ __module_get(newsock->ops->owner); newfd = sock_alloc_file(newsock, &newfile, flags); if (unlikely(newfd < 0)) { err = newfd; sock_release(newsock); goto out_put; } err = security_socket_accept(sock, newsock); if (err) goto out_fd; err = sock->ops->accept(sock, newsock, sock->file->f_flags); if (err < 0) goto out_fd; if (upeer_sockaddr) { if (newsock->ops->getname(newsock, (struct sockaddr *)&address, &len, 2) < 0) { err = -ECONNABORTED; goto out_fd; } err = move_addr_to_user(&address, len, upeer_sockaddr, upeer_addrlen); if (err < 0) goto out_fd; } /* File flags are not inherited via accept() unlike another OSes. */ fd_install(newfd, newfile); err = newfd; out_put: fput_light(sock->file, fput_needed); out: return err; out_fd: fput(newfile); put_unused_fd(newfd); goto out_put; } SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr, int __user *, upeer_addrlen) { return sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0); } /* * Attempt to connect to a socket with the server address. The address * is in user space so we verify it is OK and move it to kernel space. * * For 1003.1g we need to add clean support for a bind to AF_UNSPEC to * break bindings * * NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and * other SEQPACKET protocols that take time to connect() as it doesn't * include the -EINPROGRESS status for such sockets. */ SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr, int, addrlen) { struct socket *sock; struct sockaddr_storage address; int err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = move_addr_to_kernel(uservaddr, addrlen, &address); if (err < 0) goto out_put; err = security_socket_connect(sock, (struct sockaddr *)&address, addrlen); if (err) goto out_put; err = sock->ops->connect(sock, (struct sockaddr *)&address, addrlen, sock->file->f_flags); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the local address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = security_socket_getsockname(sock); if (err) goto out_put; err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 0); if (err) goto out_put; err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Get the remote address ('name') of a socket object. Move the obtained * name to user space. */ SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr, int __user *, usockaddr_len) { struct socket *sock; struct sockaddr_storage address; int len, err, fput_needed; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getpeername(sock); if (err) { fput_light(sock->file, fput_needed); return err; } err = sock->ops->getname(sock, (struct sockaddr *)&address, &len, 1); if (!err) err = move_addr_to_user(&address, len, usockaddr, usockaddr_len); fput_light(sock->file, fput_needed); } return err; } /* * Send a datagram to a given address. We move the address into kernel * space and check the user space data area is readable before invoking * the protocol. */ SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len, unsigned int, flags, struct sockaddr __user *, addr, int, addr_len) { struct socket *sock; struct sockaddr_storage address; int err; struct msghdr msg; struct iovec iov; int fput_needed; if (len > INT_MAX) len = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; iov.iov_base = buff; iov.iov_len = len; msg.msg_name = NULL; msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_namelen = 0; if (addr) { err = move_addr_to_kernel(addr, addr_len, &address); if (err < 0) goto out_put; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = addr_len; } if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; msg.msg_flags = flags; err = sock_sendmsg(sock, &msg, len); out_put: fput_light(sock->file, fput_needed); out: return err; } /* * Send a datagram down a socket. */ SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len, unsigned int, flags) { return sys_sendto(fd, buff, len, flags, NULL, 0); } /* * Receive a frame from the socket and optionally record the address of the * sender. We verify the buffers are writable and if needed move the * sender address from kernel to user space. */ SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size, unsigned int, flags, struct sockaddr __user *, addr, int __user *, addr_len) { struct socket *sock; struct iovec iov; struct msghdr msg; struct sockaddr_storage address; int err, err2; int fput_needed; if (size > INT_MAX) size = INT_MAX; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; msg.msg_control = NULL; msg.msg_controllen = 0; msg.msg_iovlen = 1; msg.msg_iov = &iov; iov.iov_len = size; iov.iov_base = ubuf; msg.msg_name = (struct sockaddr *)&address; msg.msg_namelen = sizeof(address); if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = sock_recvmsg(sock, &msg, size, flags); if (err >= 0 && addr != NULL) { err2 = move_addr_to_user(&address, msg.msg_namelen, addr, addr_len); if (err2 < 0) err = err2; } fput_light(sock->file, fput_needed); out: return err; } /* * Receive a datagram from a socket. */ asmlinkage long sys_recv(int fd, void __user *ubuf, size_t size, unsigned int flags) { return sys_recvfrom(fd, ubuf, size, flags, NULL, NULL); } /* * Set a socket option. Because we don't know the option lengths we have * to pass the user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname, char __user *, optval, int, optlen) { int err, fput_needed; struct socket *sock; if (optlen < 0) return -EINVAL; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_setsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, optval, optlen); else err = sock->ops->setsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Get a socket option. Because we don't know the option lengths we have * to pass a user mode parameter for the protocols to sort out. */ SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname, char __user *, optval, int __user *, optlen) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_getsockopt(sock, level, optname); if (err) goto out_put; if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, optval, optlen); else err = sock->ops->getsockopt(sock, level, optname, optval, optlen); out_put: fput_light(sock->file, fput_needed); } return err; } /* * Shutdown a socket. */ SYSCALL_DEFINE2(shutdown, int, fd, int, how) { int err, fput_needed; struct socket *sock; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (sock != NULL) { err = security_socket_shutdown(sock, how); if (!err) err = sock->ops->shutdown(sock, how); fput_light(sock->file, fput_needed); } return err; } /* A couple of helpful macros for getting the address of the 32/64 bit * fields which are the same type (int / unsigned) on our platforms. */ #define COMPAT_MSG(msg, member) ((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member) #define COMPAT_NAMELEN(msg) COMPAT_MSG(msg, msg_namelen) #define COMPAT_FLAGS(msg) COMPAT_MSG(msg, msg_flags) struct used_address { struct sockaddr_storage name; unsigned int name_len; }; static int __sys_sendmsg(struct socket *sock, struct msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, struct used_address *used_address) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct sockaddr_storage address; struct iovec iovstack[UIO_FASTIOV], *iov = iovstack; unsigned char ctl[sizeof(struct cmsghdr) + 20] __attribute__ ((aligned(sizeof(__kernel_size_t)))); /* 20 is size of ipv6_pktinfo */ unsigned char *ctl_buf = ctl; int err, ctl_len, total_len; err = -EFAULT; if (MSG_CMSG_COMPAT & flags) { if (get_compat_msghdr(msg_sys, msg_compat)) return -EFAULT; } else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr))) return -EFAULT; if (msg_sys->msg_iovlen > UIO_FASTIOV) { err = -EMSGSIZE; if (msg_sys->msg_iovlen > UIO_MAXIOV) goto out; err = -ENOMEM; iov = kmalloc(msg_sys->msg_iovlen * sizeof(struct iovec), GFP_KERNEL); if (!iov) goto out; } /* This will also move the address data into kernel space */ if (MSG_CMSG_COMPAT & flags) { err = verify_compat_iovec(msg_sys, iov, &address, VERIFY_READ); } else err = verify_iovec(msg_sys, iov, &address, VERIFY_READ); if (err < 0) goto out_freeiov; total_len = err; err = -ENOBUFS; if (msg_sys->msg_controllen > INT_MAX) goto out_freeiov; ctl_len = msg_sys->msg_controllen; if ((MSG_CMSG_COMPAT & flags) && ctl_len) { err = cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl, sizeof(ctl)); if (err) goto out_freeiov; ctl_buf = msg_sys->msg_control; ctl_len = msg_sys->msg_controllen; } else if (ctl_len) { if (ctl_len > sizeof(ctl)) { ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL); if (ctl_buf == NULL) goto out_freeiov; } err = -EFAULT; /* * Careful! Before this, msg_sys->msg_control contains a user pointer. * Afterwards, it will be a kernel pointer. Thus the compiler-assisted * checking falls down on this. */ if (copy_from_user(ctl_buf, (void __user __force *)msg_sys->msg_control, ctl_len)) goto out_freectl; msg_sys->msg_control = ctl_buf; } msg_sys->msg_flags = flags; if (sock->file->f_flags & O_NONBLOCK) msg_sys->msg_flags |= MSG_DONTWAIT; /* * If this is sendmmsg() and current destination address is same as * previously succeeded address, omit asking LSM's decision. * used_address->name_len is initialized to UINT_MAX so that the first * destination address never matches. */ if (used_address && msg_sys->msg_name && used_address->name_len == msg_sys->msg_namelen && !memcmp(&used_address->name, msg_sys->msg_name, used_address->name_len)) { err = sock_sendmsg_nosec(sock, msg_sys, total_len); goto out_freectl; } err = sock_sendmsg(sock, msg_sys, total_len); /* * If this is sendmmsg() and sending to current destination address was * successful, remember it. */ if (used_address && err >= 0) { used_address->name_len = msg_sys->msg_namelen; if (msg_sys->msg_name) memcpy(&used_address->name, msg_sys->msg_name, used_address->name_len); } out_freectl: if (ctl_buf != ctl) sock_kfree_s(sock->sk, ctl_buf, ctl_len); out_freeiov: if (iov != iovstack) kfree(iov); out: return err; } /* * BSD sendmsg interface */ SYSCALL_DEFINE3(sendmsg, int, fd, struct msghdr __user *, msg, unsigned int, flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = __sys_sendmsg(sock, msg, &msg_sys, flags, NULL); fput_light(sock->file, fput_needed); out: return err; } /* * Linux sendmmsg interface */ int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct used_address used_address; if (vlen > UIO_MAXIOV) vlen = UIO_MAXIOV; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; used_address.name_len = UINT_MAX; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; err = 0; while (datagrams < vlen) { if (MSG_CMSG_COMPAT & flags) { err = __sys_sendmsg(sock, (struct msghdr __user *)compat_entry, &msg_sys, flags, &used_address); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = __sys_sendmsg(sock, (struct msghdr __user *)entry, &msg_sys, flags, &used_address); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; } fput_light(sock->file, fput_needed); /* We only return an error if no datagrams were able to be sent */ if (datagrams != 0) return datagrams; return err; } SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags) { return __sys_sendmmsg(fd, mmsg, vlen, flags); } static int __sys_recvmsg(struct socket *sock, struct msghdr __user *msg, struct msghdr *msg_sys, unsigned int flags, int nosec) { struct compat_msghdr __user *msg_compat = (struct compat_msghdr __user *)msg; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov = iovstack; unsigned long cmsg_ptr; int err, total_len, len; /* kernel mode address */ struct sockaddr_storage addr; /* user mode address pointers */ struct sockaddr __user *uaddr; int __user *uaddr_len; if (MSG_CMSG_COMPAT & flags) { if (get_compat_msghdr(msg_sys, msg_compat)) return -EFAULT; } else if (copy_from_user(msg_sys, msg, sizeof(struct msghdr))) return -EFAULT; if (msg_sys->msg_iovlen > UIO_FASTIOV) { err = -EMSGSIZE; if (msg_sys->msg_iovlen > UIO_MAXIOV) goto out; err = -ENOMEM; iov = kmalloc(msg_sys->msg_iovlen * sizeof(struct iovec), GFP_KERNEL); if (!iov) goto out; } /* * Save the user-mode address (verify_iovec will change the * kernel msghdr to use the kernel address space) */ uaddr = (__force void __user *)msg_sys->msg_name; uaddr_len = COMPAT_NAMELEN(msg); if (MSG_CMSG_COMPAT & flags) { err = verify_compat_iovec(msg_sys, iov, &addr, VERIFY_WRITE); } else err = verify_iovec(msg_sys, iov, &addr, VERIFY_WRITE); if (err < 0) goto out_freeiov; total_len = err; cmsg_ptr = (unsigned long)msg_sys->msg_control; msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT); if (sock->file->f_flags & O_NONBLOCK) flags |= MSG_DONTWAIT; err = (nosec ? sock_recvmsg_nosec : sock_recvmsg)(sock, msg_sys, total_len, flags); if (err < 0) goto out_freeiov; len = err; if (uaddr != NULL) { err = move_addr_to_user(&addr, msg_sys->msg_namelen, uaddr, uaddr_len); if (err < 0) goto out_freeiov; } err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT), COMPAT_FLAGS(msg)); if (err) goto out_freeiov; if (MSG_CMSG_COMPAT & flags) err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg_compat->msg_controllen); else err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr, &msg->msg_controllen); if (err) goto out_freeiov; err = len; out_freeiov: if (iov != iovstack) kfree(iov); out: return err; } /* * BSD recvmsg interface */ SYSCALL_DEFINE3(recvmsg, int, fd, struct msghdr __user *, msg, unsigned int, flags) { int fput_needed, err; struct msghdr msg_sys; struct socket *sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) goto out; err = __sys_recvmsg(sock, msg, &msg_sys, flags, 0); fput_light(sock->file, fput_needed); out: return err; } /* * Linux recvmmsg interface */ int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen, unsigned int flags, struct timespec *timeout) { int fput_needed, err, datagrams; struct socket *sock; struct mmsghdr __user *entry; struct compat_mmsghdr __user *compat_entry; struct msghdr msg_sys; struct timespec end_time; if (timeout && poll_select_set_timeout(&end_time, timeout->tv_sec, timeout->tv_nsec)) return -EINVAL; datagrams = 0; sock = sockfd_lookup_light(fd, &err, &fput_needed); if (!sock) return err; err = sock_error(sock->sk); if (err) goto out_put; entry = mmsg; compat_entry = (struct compat_mmsghdr __user *)mmsg; while (datagrams < vlen) { /* * No need to ask LSM for more than the first datagram. */ if (MSG_CMSG_COMPAT & flags) { err = __sys_recvmsg(sock, (struct msghdr __user *)compat_entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = __put_user(err, &compat_entry->msg_len); ++compat_entry; } else { err = __sys_recvmsg(sock, (struct msghdr __user *)entry, &msg_sys, flags & ~MSG_WAITFORONE, datagrams); if (err < 0) break; err = put_user(err, &entry->msg_len); ++entry; } if (err) break; ++datagrams; /* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */ if (flags & MSG_WAITFORONE) flags |= MSG_DONTWAIT; if (timeout) { ktime_get_ts(timeout); *timeout = timespec_sub(end_time, *timeout); if (timeout->tv_sec < 0) { timeout->tv_sec = timeout->tv_nsec = 0; break; } /* Timeout, return less than vlen datagrams */ if (timeout->tv_nsec == 0 && timeout->tv_sec == 0) break; } /* Out of band data, return right away */ if (msg_sys.msg_flags & MSG_OOB) break; } out_put: fput_light(sock->file, fput_needed); if (err == 0) return datagrams; if (datagrams != 0) { /* * We may return less entries than requested (vlen) if the * sock is non block and there aren't enough datagrams... */ if (err != -EAGAIN) { /* * ... or if recvmsg returns an error after we * received some datagrams, where we record the * error to return on the next call or if the * app asks about it using getsockopt(SO_ERROR). */ sock->sk->sk_err = -err; } return datagrams; } return err; } SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg, unsigned int, vlen, unsigned int, flags, struct timespec __user *, timeout) { int datagrams; struct timespec timeout_sys; if (!timeout) return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL); if (copy_from_user(&timeout_sys, timeout, sizeof(timeout_sys))) return -EFAULT; datagrams = __sys_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys); if (datagrams > 0 && copy_to_user(timeout, &timeout_sys, sizeof(timeout_sys))) datagrams = -EFAULT; return datagrams; } #ifdef __ARCH_WANT_SYS_SOCKETCALL /* Argument list sizes for sys_socketcall */ #define AL(x) ((x) * sizeof(unsigned long)) static const unsigned char nargs[21] = { AL(0), AL(3), AL(3), AL(3), AL(2), AL(3), AL(3), AL(3), AL(4), AL(4), AL(4), AL(6), AL(6), AL(2), AL(5), AL(5), AL(3), AL(3), AL(4), AL(5), AL(4) }; #undef AL /* * System call vectors. * * Argument checking cleaned up. Saved 20% in size. * This function doesn't need to set the kernel lock because * it is set by the callees. */ SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args) { unsigned long a[6]; unsigned long a0, a1; int err; unsigned int len; if (call < 1 || call > SYS_SENDMMSG) return -EINVAL; len = nargs[call]; if (len > sizeof(a)) return -EINVAL; /* copy_from_user should be SMP safe. */ if (copy_from_user(a, args, len)) return -EFAULT; audit_socketcall(nargs[call] / sizeof(unsigned long), a); a0 = a[0]; a1 = a[1]; switch (call) { case SYS_SOCKET: err = sys_socket(a0, a1, a[2]); break; case SYS_BIND: err = sys_bind(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_CONNECT: err = sys_connect(a0, (struct sockaddr __user *)a1, a[2]); break; case SYS_LISTEN: err = sys_listen(a0, a1); break; case SYS_ACCEPT: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], 0); break; case SYS_GETSOCKNAME: err = sys_getsockname(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_GETPEERNAME: err = sys_getpeername(a0, (struct sockaddr __user *)a1, (int __user *)a[2]); break; case SYS_SOCKETPAIR: err = sys_socketpair(a0, a1, a[2], (int __user *)a[3]); break; case SYS_SEND: err = sys_send(a0, (void __user *)a1, a[2], a[3]); break; case SYS_SENDTO: err = sys_sendto(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], a[5]); break; case SYS_RECV: err = sys_recv(a0, (void __user *)a1, a[2], a[3]); break; case SYS_RECVFROM: err = sys_recvfrom(a0, (void __user *)a1, a[2], a[3], (struct sockaddr __user *)a[4], (int __user *)a[5]); break; case SYS_SHUTDOWN: err = sys_shutdown(a0, a1); break; case SYS_SETSOCKOPT: err = sys_setsockopt(a0, a1, a[2], (char __user *)a[3], a[4]); break; case SYS_GETSOCKOPT: err = sys_getsockopt(a0, a1, a[2], (char __user *)a[3], (int __user *)a[4]); break; case SYS_SENDMSG: err = sys_sendmsg(a0, (struct msghdr __user *)a1, a[2]); break; case SYS_SENDMMSG: err = sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3]); break; case SYS_RECVMSG: err = sys_recvmsg(a0, (struct msghdr __user *)a1, a[2]); break; case SYS_RECVMMSG: err = sys_recvmmsg(a0, (struct mmsghdr __user *)a1, a[2], a[3], (struct timespec __user *)a[4]); break; case SYS_ACCEPT4: err = sys_accept4(a0, (struct sockaddr __user *)a1, (int __user *)a[2], a[3]); break; default: err = -EINVAL; break; } return err; } #endif /* __ARCH_WANT_SYS_SOCKETCALL */ /** * sock_register - add a socket protocol handler * @ops: description of protocol * * This function is called by a protocol handler that wants to * advertise its address family, and have it linked into the * socket interface. The value ops->family coresponds to the * socket system call protocol family. */ int sock_register(const struct net_proto_family *ops) { int err; if (ops->family >= NPROTO) { printk(KERN_CRIT "protocol %d >= NPROTO(%d)\n", ops->family, NPROTO); return -ENOBUFS; } spin_lock(&net_family_lock); if (rcu_dereference_protected(net_families[ops->family], lockdep_is_held(&net_family_lock))) err = -EEXIST; else { rcu_assign_pointer(net_families[ops->family], ops); err = 0; } spin_unlock(&net_family_lock); printk(KERN_INFO "NET: Registered protocol family %d\n", ops->family); return err; } EXPORT_SYMBOL(sock_register); /** * sock_unregister - remove a protocol handler * @family: protocol family to remove * * This function is called by a protocol handler that wants to * remove its address family, and have it unlinked from the * new socket creation. * * If protocol handler is a module, then it can use module reference * counts to protect against new references. If protocol handler is not * a module then it needs to provide its own protection in * the ops->create routine. */ void sock_unregister(int family) { BUG_ON(family < 0 || family >= NPROTO); spin_lock(&net_family_lock); RCU_INIT_POINTER(net_families[family], NULL); spin_unlock(&net_family_lock); synchronize_rcu(); printk(KERN_INFO "NET: Unregistered protocol family %d\n", family); } EXPORT_SYMBOL(sock_unregister); static int __init sock_init(void) { int err; /* * Initialize the network sysctl infrastructure. */ err = net_sysctl_init(); if (err) goto out; /* * Initialize sock SLAB cache. */ sk_init(); /* * Initialize skbuff SLAB cache */ skb_init(); /* * Initialize the protocols module. */ init_inodecache(); err = register_filesystem(&sock_fs_type); if (err) goto out_fs; sock_mnt = kern_mount(&sock_fs_type); if (IS_ERR(sock_mnt)) { err = PTR_ERR(sock_mnt); goto out_mount; } /* The real protocol initialization is performed in later initcalls. */ #ifdef CONFIG_NETFILTER netfilter_init(); #endif #ifdef CONFIG_NETWORK_PHY_TIMESTAMPING skb_timestamping_init(); #endif out: return err; out_mount: unregister_filesystem(&sock_fs_type); out_fs: goto out; } core_initcall(sock_init); /* early initcall */ #ifdef CONFIG_PROC_FS void socket_seq_show(struct seq_file *seq) { int cpu; int counter = 0; for_each_possible_cpu(cpu) counter += per_cpu(sockets_in_use, cpu); /* It can be negative, by the way. 8) */ if (counter < 0) counter = 0; seq_printf(seq, "sockets: used %d\n", counter); } #endif /* CONFIG_PROC_FS */ #ifdef CONFIG_COMPAT static int do_siocgstamp(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timeval ktv; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&ktv); set_fs(old_fs); if (!err) err = compat_put_timeval(up, &ktv); return err; } static int do_siocgstampns(struct net *net, struct socket *sock, unsigned int cmd, void __user *up) { mm_segment_t old_fs = get_fs(); struct timespec kts; int err; set_fs(KERNEL_DS); err = sock_do_ioctl(net, sock, cmd, (unsigned long)&kts); set_fs(old_fs); if (!err) err = compat_put_timespec(up, &kts); return err; } static int dev_ifname32(struct net *net, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(struct ifreq)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; err = dev_ioctl(net, SIOCGIFNAME, uifr); if (err) return err; if (copy_in_user(uifr32, uifr, sizeof(struct compat_ifreq))) return -EFAULT; return 0; } static int dev_ifconf(struct net *net, struct compat_ifconf __user *uifc32) { struct compat_ifconf ifc32; struct ifconf ifc; struct ifconf __user *uifc; struct compat_ifreq __user *ifr32; struct ifreq __user *ifr; unsigned int i, j; int err; if (copy_from_user(&ifc32, uifc32, sizeof(struct compat_ifconf))) return -EFAULT; if (ifc32.ifcbuf == 0) { ifc32.ifc_len = 0; ifc.ifc_len = 0; ifc.ifc_req = NULL; uifc = compat_alloc_user_space(sizeof(struct ifconf)); } else { size_t len = ((ifc32.ifc_len / sizeof(struct compat_ifreq)) + 1) * sizeof(struct ifreq); uifc = compat_alloc_user_space(sizeof(struct ifconf) + len); ifc.ifc_len = len; ifr = ifc.ifc_req = (void __user *)(uifc + 1); ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0; i < ifc32.ifc_len; i += sizeof(struct compat_ifreq)) { if (copy_in_user(ifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; ifr++; ifr32++; } } if (copy_to_user(uifc, &ifc, sizeof(struct ifconf))) return -EFAULT; err = dev_ioctl(net, SIOCGIFCONF, uifc); if (err) return err; if (copy_from_user(&ifc, uifc, sizeof(struct ifconf))) return -EFAULT; ifr = ifc.ifc_req; ifr32 = compat_ptr(ifc32.ifcbuf); for (i = 0, j = 0; i + sizeof(struct compat_ifreq) <= ifc32.ifc_len && j < ifc.ifc_len; i += sizeof(struct compat_ifreq), j += sizeof(struct ifreq)) { if (copy_in_user(ifr32, ifr, sizeof(struct compat_ifreq))) return -EFAULT; ifr32++; ifr++; } if (ifc32.ifcbuf == 0) { /* Translate from 64-bit structure multiple to * a 32-bit one. */ i = ifc.ifc_len; i = ((i / sizeof(struct ifreq)) * sizeof(struct compat_ifreq)); ifc32.ifc_len = i; } else { ifc32.ifc_len = i; } if (copy_to_user(uifc32, &ifc32, sizeof(struct compat_ifconf))) return -EFAULT; return 0; } static int ethtool_ioctl(struct net *net, struct compat_ifreq __user *ifr32) { struct compat_ethtool_rxnfc __user *compat_rxnfc; bool convert_in = false, convert_out = false; size_t buf_size = ALIGN(sizeof(struct ifreq), 8); struct ethtool_rxnfc __user *rxnfc; struct ifreq __user *ifr; u32 rule_cnt = 0, actual_rule_cnt; u32 ethcmd; u32 data; int ret; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; compat_rxnfc = compat_ptr(data); if (get_user(ethcmd, &compat_rxnfc->cmd)) return -EFAULT; /* Most ethtool structures are defined without padding. * Unfortunately struct ethtool_rxnfc is an exception. */ switch (ethcmd) { default: break; case ETHTOOL_GRXCLSRLALL: /* Buffer size is variable */ if (get_user(rule_cnt, &compat_rxnfc->rule_cnt)) return -EFAULT; if (rule_cnt > KMALLOC_MAX_SIZE / sizeof(u32)) return -ENOMEM; buf_size += rule_cnt * sizeof(u32); /* fall through */ case ETHTOOL_GRXRINGS: case ETHTOOL_GRXCLSRLCNT: case ETHTOOL_GRXCLSRULE: case ETHTOOL_SRXCLSRLINS: convert_out = true; /* fall through */ case ETHTOOL_SRXCLSRLDEL: buf_size += sizeof(struct ethtool_rxnfc); convert_in = true; break; } ifr = compat_alloc_user_space(buf_size); rxnfc = (void *)ifr + ALIGN(sizeof(struct ifreq), 8); if (copy_in_user(&ifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (put_user(convert_in ? rxnfc : compat_ptr(data), &ifr->ifr_ifru.ifru_data)) return -EFAULT; if (convert_in) { /* We expect there to be holes between fs.m_ext and * fs.ring_cookie and at the end of fs, but nowhere else. */ BUILD_BUG_ON(offsetof(struct compat_ethtool_rxnfc, fs.m_ext) + sizeof(compat_rxnfc->fs.m_ext) != offsetof(struct ethtool_rxnfc, fs.m_ext) + sizeof(rxnfc->fs.m_ext)); BUILD_BUG_ON( offsetof(struct compat_ethtool_rxnfc, fs.location) - offsetof(struct compat_ethtool_rxnfc, fs.ring_cookie) != offsetof(struct ethtool_rxnfc, fs.location) - offsetof(struct ethtool_rxnfc, fs.ring_cookie)); if (copy_in_user(rxnfc, compat_rxnfc, (void *)(&rxnfc->fs.m_ext + 1) - (void *)rxnfc) || copy_in_user(&rxnfc->fs.ring_cookie, &compat_rxnfc->fs.ring_cookie, (void *)(&rxnfc->fs.location + 1) - (void *)&rxnfc->fs.ring_cookie) || copy_in_user(&rxnfc->rule_cnt, &compat_rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; } ret = dev_ioctl(net, SIOCETHTOOL, ifr); if (ret) return ret; if (convert_out) { if (copy_in_user(compat_rxnfc, rxnfc, (const void *)(&rxnfc->fs.m_ext + 1) - (const void *)rxnfc) || copy_in_user(&compat_rxnfc->fs.ring_cookie, &rxnfc->fs.ring_cookie, (const void *)(&rxnfc->fs.location + 1) - (const void *)&rxnfc->fs.ring_cookie) || copy_in_user(&compat_rxnfc->rule_cnt, &rxnfc->rule_cnt, sizeof(rxnfc->rule_cnt))) return -EFAULT; if (ethcmd == ETHTOOL_GRXCLSRLALL) { /* As an optimisation, we only copy the actual * number of rules that the underlying * function returned. Since Mallory might * change the rule count in user memory, we * check that it is less than the rule count * originally given (as the user buffer size), * which has been range-checked. */ if (get_user(actual_rule_cnt, &rxnfc->rule_cnt)) return -EFAULT; if (actual_rule_cnt < rule_cnt) rule_cnt = actual_rule_cnt; if (copy_in_user(&compat_rxnfc->rule_locs[0], &rxnfc->rule_locs[0], rule_cnt * sizeof(u32))) return -EFAULT; } } return 0; } static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_settings.ifs_ifsu.raw_hdlc)) return -EFAULT; return dev_ioctl(net, SIOCWANDEV, uifr); } static int bond_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *ifr32) { struct ifreq kifr; struct ifreq __user *uifr; mm_segment_t old_fs; int err; u32 data; void __user *datap; switch (cmd) { case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDCHANGEACTIVE: if (copy_from_user(&kifr, ifr32, sizeof(struct compat_ifreq))) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (struct ifreq __user __force *) &kifr); set_fs(old_fs); return err; case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(&uifr->ifr_name, &ifr32->ifr_name, IFNAMSIZ)) return -EFAULT; if (get_user(data, &ifr32->ifr_ifru.ifru_data)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &uifr->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, uifr); default: return -ENOIOCTLCMD; } } static int siocdevprivate_ioctl(struct net *net, unsigned int cmd, struct compat_ifreq __user *u_ifreq32) { struct ifreq __user *u_ifreq64; char tmp_buf[IFNAMSIZ]; void __user *data64; u32 data32; if (copy_from_user(&tmp_buf[0], &(u_ifreq32->ifr_ifrn.ifrn_name[0]), IFNAMSIZ)) return -EFAULT; if (__get_user(data32, &u_ifreq32->ifr_ifru.ifru_data)) return -EFAULT; data64 = compat_ptr(data32); u_ifreq64 = compat_alloc_user_space(sizeof(*u_ifreq64)); /* Don't check these user accesses, just let that get trapped * in the ioctl handler instead. */ if (copy_to_user(&u_ifreq64->ifr_ifrn.ifrn_name[0], &tmp_buf[0], IFNAMSIZ)) return -EFAULT; if (__put_user(data64, &u_ifreq64->ifr_ifru.ifru_data)) return -EFAULT; return dev_ioctl(net, cmd, u_ifreq64); } static int dev_ifsioc(struct net *net, struct socket *sock, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq __user *uifr; int err; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(*uifr32))) return -EFAULT; err = sock_do_ioctl(net, sock, cmd, (unsigned long)uifr); if (!err) { switch (cmd) { case SIOCGIFFLAGS: case SIOCGIFMETRIC: case SIOCGIFMTU: case SIOCGIFMEM: case SIOCGIFHWADDR: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCGIFBRDADDR: case SIOCGIFDSTADDR: case SIOCGIFNETMASK: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCGMIIPHY: case SIOCGMIIREG: if (copy_in_user(uifr32, uifr, sizeof(*uifr32))) err = -EFAULT; break; } } return err; } static int compat_sioc_ifmap(struct net *net, unsigned int cmd, struct compat_ifreq __user *uifr32) { struct ifreq ifr; struct compat_ifmap __user *uifmap32; mm_segment_t old_fs; int err; uifmap32 = &uifr32->ifr_ifru.ifru_map; err = copy_from_user(&ifr, uifr32, sizeof(ifr.ifr_name)); err |= __get_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= __get_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= __get_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= __get_user(ifr.ifr_map.irq, &uifmap32->irq); err |= __get_user(ifr.ifr_map.dma, &uifmap32->dma); err |= __get_user(ifr.ifr_map.port, &uifmap32->port); if (err) return -EFAULT; old_fs = get_fs(); set_fs(KERNEL_DS); err = dev_ioctl(net, cmd, (void __user __force *)&ifr); set_fs(old_fs); if (cmd == SIOCGIFMAP && !err) { err = copy_to_user(uifr32, &ifr, sizeof(ifr.ifr_name)); err |= __put_user(ifr.ifr_map.mem_start, &uifmap32->mem_start); err |= __put_user(ifr.ifr_map.mem_end, &uifmap32->mem_end); err |= __put_user(ifr.ifr_map.base_addr, &uifmap32->base_addr); err |= __put_user(ifr.ifr_map.irq, &uifmap32->irq); err |= __put_user(ifr.ifr_map.dma, &uifmap32->dma); err |= __put_user(ifr.ifr_map.port, &uifmap32->port); if (err) err = -EFAULT; } return err; } static int compat_siocshwtstamp(struct net *net, struct compat_ifreq __user *uifr32) { void __user *uptr; compat_uptr_t uptr32; struct ifreq __user *uifr; uifr = compat_alloc_user_space(sizeof(*uifr)); if (copy_in_user(uifr, uifr32, sizeof(struct compat_ifreq))) return -EFAULT; if (get_user(uptr32, &uifr32->ifr_data)) return -EFAULT; uptr = compat_ptr(uptr32); if (put_user(uptr, &uifr->ifr_data)) return -EFAULT; return dev_ioctl(net, SIOCSHWTSTAMP, uifr); } struct rtentry32 { u32 rt_pad1; struct sockaddr rt_dst; /* target address */ struct sockaddr rt_gateway; /* gateway addr (RTF_GATEWAY) */ struct sockaddr rt_genmask; /* target network mask (IP) */ unsigned short rt_flags; short rt_pad2; u32 rt_pad3; unsigned char rt_tos; unsigned char rt_class; short rt_pad4; short rt_metric; /* +1 for binary compatibility! */ /* char * */ u32 rt_dev; /* forcing the device at add */ u32 rt_mtu; /* per route MTU/Window */ u32 rt_window; /* Window clamping */ unsigned short rt_irtt; /* Initial RTT */ }; struct in6_rtmsg32 { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; u32 rtmsg_type; u16 rtmsg_dst_len; u16 rtmsg_src_len; u32 rtmsg_metric; u32 rtmsg_info; u32 rtmsg_flags; s32 rtmsg_ifindex; }; static int routing_ioctl(struct net *net, struct socket *sock, unsigned int cmd, void __user *argp) { int ret; void *r = NULL; struct in6_rtmsg r6; struct rtentry r4; char devname[16]; u32 rtdev; mm_segment_t old_fs = get_fs(); if (sock && sock->sk && sock->sk->sk_family == AF_INET6) { /* ipv6 */ struct in6_rtmsg32 __user *ur6 = argp; ret = copy_from_user(&r6.rtmsg_dst, &(ur6->rtmsg_dst), 3 * sizeof(struct in6_addr)); ret |= __get_user(r6.rtmsg_type, &(ur6->rtmsg_type)); ret |= __get_user(r6.rtmsg_dst_len, &(ur6->rtmsg_dst_len)); ret |= __get_user(r6.rtmsg_src_len, &(ur6->rtmsg_src_len)); ret |= __get_user(r6.rtmsg_metric, &(ur6->rtmsg_metric)); ret |= __get_user(r6.rtmsg_info, &(ur6->rtmsg_info)); ret |= __get_user(r6.rtmsg_flags, &(ur6->rtmsg_flags)); ret |= __get_user(r6.rtmsg_ifindex, &(ur6->rtmsg_ifindex)); r = (void *) &r6; } else { /* ipv4 */ struct rtentry32 __user *ur4 = argp; ret = copy_from_user(&r4.rt_dst, &(ur4->rt_dst), 3 * sizeof(struct sockaddr)); ret |= __get_user(r4.rt_flags, &(ur4->rt_flags)); ret |= __get_user(r4.rt_metric, &(ur4->rt_metric)); ret |= __get_user(r4.rt_mtu, &(ur4->rt_mtu)); ret |= __get_user(r4.rt_window, &(ur4->rt_window)); ret |= __get_user(r4.rt_irtt, &(ur4->rt_irtt)); ret |= __get_user(rtdev, &(ur4->rt_dev)); if (rtdev) { ret |= copy_from_user(devname, compat_ptr(rtdev), 15); r4.rt_dev = (char __user __force *)devname; devname[15] = 0; } else r4.rt_dev = NULL; r = (void *) &r4; } if (ret) { ret = -EFAULT; goto out; } set_fs(KERNEL_DS); ret = sock_do_ioctl(net, sock, cmd, (unsigned long) r); set_fs(old_fs); out: return ret; } /* Since old style bridge ioctl's endup using SIOCDEVPRIVATE * for some operations; this forces use of the newer bridge-utils that * use compatible ioctls */ static int old_bridge_ioctl(compat_ulong_t __user *argp) { compat_ulong_t tmp; if (get_user(tmp, argp)) return -EFAULT; if (tmp == BRCTL_GET_VERSION) return BRCTL_VERSION + 1; return -EINVAL; } static int compat_sock_ioctl_trans(struct file *file, struct socket *sock, unsigned int cmd, unsigned long arg) { void __user *argp = compat_ptr(arg); struct sock *sk = sock->sk; struct net *net = sock_net(sk); if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15)) return siocdevprivate_ioctl(net, cmd, argp); switch (cmd) { case SIOCSIFBR: case SIOCGIFBR: return old_bridge_ioctl(argp); case SIOCGIFNAME: return dev_ifname32(net, argp); case SIOCGIFCONF: return dev_ifconf(net, argp); case SIOCETHTOOL: return ethtool_ioctl(net, argp); case SIOCWANDEV: return compat_siocwandev(net, argp); case SIOCGIFMAP: case SIOCSIFMAP: return compat_sioc_ifmap(net, cmd, argp); case SIOCBONDENSLAVE: case SIOCBONDRELEASE: case SIOCBONDSETHWADDR: case SIOCBONDSLAVEINFOQUERY: case SIOCBONDINFOQUERY: case SIOCBONDCHANGEACTIVE: return bond_ioctl(net, cmd, argp); case SIOCADDRT: case SIOCDELRT: return routing_ioctl(net, sock, cmd, argp); case SIOCGSTAMP: return do_siocgstamp(net, sock, cmd, argp); case SIOCGSTAMPNS: return do_siocgstampns(net, sock, cmd, argp); case SIOCSHWTSTAMP: return compat_siocshwtstamp(net, argp); case FIOSETOWN: case SIOCSPGRP: case FIOGETOWN: case SIOCGPGRP: case SIOCBRADDBR: case SIOCBRDELBR: case SIOCGIFVLAN: case SIOCSIFVLAN: case SIOCADDDLCI: case SIOCDELDLCI: return sock_ioctl(file, cmd, arg); case SIOCGIFFLAGS: case SIOCSIFFLAGS: case SIOCGIFMETRIC: case SIOCSIFMETRIC: case SIOCGIFMTU: case SIOCSIFMTU: case SIOCGIFMEM: case SIOCSIFMEM: case SIOCGIFHWADDR: case SIOCSIFHWADDR: case SIOCADDMULTI: case SIOCDELMULTI: case SIOCGIFINDEX: case SIOCGIFADDR: case SIOCSIFADDR: case SIOCSIFHWBROADCAST: case SIOCDIFADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCSIFPFLAGS: case SIOCGIFPFLAGS: case SIOCGIFTXQLEN: case SIOCSIFTXQLEN: case SIOCBRADDIF: case SIOCBRDELIF: case SIOCSIFNAME: case SIOCGMIIPHY: case SIOCGMIIREG: case SIOCSMIIREG: return dev_ifsioc(net, sock, cmd, argp); case SIOCSARP: case SIOCGARP: case SIOCDARP: case SIOCATMARK: return sock_do_ioctl(net, sock, cmd, arg); } return -ENOIOCTLCMD; } static long compat_sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct socket *sock = file->private_data; int ret = -ENOIOCTLCMD; struct sock *sk; struct net *net; sk = sock->sk; net = sock_net(sk); if (sock->ops->compat_ioctl) ret = sock->ops->compat_ioctl(sock, cmd, arg); if (ret == -ENOIOCTLCMD && (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST)) ret = compat_wext_handle_ioctl(net, cmd, arg); if (ret == -ENOIOCTLCMD) ret = compat_sock_ioctl_trans(file, sock, cmd, arg); return ret; } #endif int kernel_bind(struct socket *sock, struct sockaddr *addr, int addrlen) { return sock->ops->bind(sock, addr, addrlen); } EXPORT_SYMBOL(kernel_bind); int kernel_listen(struct socket *sock, int backlog) { return sock->ops->listen(sock, backlog); } EXPORT_SYMBOL(kernel_listen); int kernel_accept(struct socket *sock, struct socket **newsock, int flags) { struct sock *sk = sock->sk; int err; err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol, newsock); if (err < 0) goto done; err = sock->ops->accept(sock, *newsock, flags); if (err < 0) { sock_release(*newsock); *newsock = NULL; goto done; } (*newsock)->ops = sock->ops; __module_get((*newsock)->ops->owner); done: return err; } EXPORT_SYMBOL(kernel_accept); int kernel_connect(struct socket *sock, struct sockaddr *addr, int addrlen, int flags) { return sock->ops->connect(sock, addr, addrlen, flags); } EXPORT_SYMBOL(kernel_connect); int kernel_getsockname(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 0); } EXPORT_SYMBOL(kernel_getsockname); int kernel_getpeername(struct socket *sock, struct sockaddr *addr, int *addrlen) { return sock->ops->getname(sock, addr, addrlen, 1); } EXPORT_SYMBOL(kernel_getpeername); int kernel_getsockopt(struct socket *sock, int level, int optname, char *optval, int *optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int __user *uoptlen; int err; uoptval = (char __user __force *) optval; uoptlen = (int __user __force *) optlen; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_getsockopt(sock, level, optname, uoptval, uoptlen); else err = sock->ops->getsockopt(sock, level, optname, uoptval, uoptlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_getsockopt); int kernel_setsockopt(struct socket *sock, int level, int optname, char *optval, unsigned int optlen) { mm_segment_t oldfs = get_fs(); char __user *uoptval; int err; uoptval = (char __user __force *) optval; set_fs(KERNEL_DS); if (level == SOL_SOCKET) err = sock_setsockopt(sock, level, optname, uoptval, optlen); else err = sock->ops->setsockopt(sock, level, optname, uoptval, optlen); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_setsockopt); int kernel_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { sock_update_classid(sock->sk); if (sock->ops->sendpage) return sock->ops->sendpage(sock, page, offset, size, flags); return sock_no_sendpage(sock, page, offset, size, flags); } EXPORT_SYMBOL(kernel_sendpage); int kernel_sock_ioctl(struct socket *sock, int cmd, unsigned long arg) { mm_segment_t oldfs = get_fs(); int err; set_fs(KERNEL_DS); err = sock->ops->ioctl(sock, cmd, arg); set_fs(oldfs); return err; } EXPORT_SYMBOL(kernel_sock_ioctl); int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how) { return sock->ops->shutdown(sock, how); } EXPORT_SYMBOL(kernel_sock_shutdown);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3827_0
crossvul-cpp_data_good_3568_7
/* -*- Mode: c; c-basic-offset: 2 -*- * * raptor_option.c - Class options * * Copyright (C) 2004-2010, David Beckett http://www.dajobe.org/ * Copyright (C) 2004-2005, University of Bristol, UK http://www.bristol.ac.uk/ * * This package is Free Software and part of Redland http://librdf.org/ * * It is licensed under the following three licenses as alternatives: * 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version * 2. GNU General Public License (GPL) V2 or any newer version * 3. Apache License, V2.0 or any newer version * * You may not use this file except in compliance with at least one of * the above three licenses. * * See LICENSE.html or LICENSE.txt at the top of this package for the * complete terms and further detail along with the license texts for * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively. * * */ #ifdef HAVE_CONFIG_H #include <raptor_config.h> #endif #ifdef WIN32 #include <win32_raptor_config.h> #endif #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdarg.h> /* Raptor includes */ #include "raptor2.h" #include "raptor_internal.h" static const struct { raptor_option option; raptor_option_area area; raptor_option_value_type value_type; const char *name; const char *label; } raptor_options_list[RAPTOR_OPTION_LAST + 1] = { { RAPTOR_OPTION_SCANNING, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "scanForRDF", "RDF/XML parser scans for rdf:RDF in XML content" }, { RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "allowNonNsAttributes", "RDF/XML parser allows bare 'name' rather than namespaced 'rdf:name'" }, { RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "allowOtherParsetypes", "RDF/XML parser allows user-defined rdf:parseType values" }, { RAPTOR_OPTION_ALLOW_BAGID, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "allowBagID", "RDF/XML parser allows rdf:bagID" }, { RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "allowRDFtypeRDFlist", "RDF/XML parser generates the collection rdf:type rdf:List triple" }, { RAPTOR_OPTION_NORMALIZE_LANGUAGE, (raptor_option_area)(RAPTOR_OPTION_AREA_PARSER | RAPTOR_OPTION_AREA_SAX2), RAPTOR_OPTION_VALUE_TYPE_BOOL, "normalizeLanguage", "RDF/XML parser normalizes xml:lang values to lowercase" }, { RAPTOR_OPTION_NON_NFC_FATAL, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "nonNFCfatal", "RDF/XML parser makes non-NFC literals a fatal error" }, { RAPTOR_OPTION_WARN_OTHER_PARSETYPES, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "warnOtherParseTypes", "RDF/XML parser warns about unknown rdf:parseType values" }, { RAPTOR_OPTION_CHECK_RDF_ID, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "checkRdfID", "RDF/XML parser checks rdf:ID values for duplicates" }, { RAPTOR_OPTION_RELATIVE_URIS, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "relativeURIs", "Serializers write relative URIs wherever possible." }, { RAPTOR_OPTION_WRITER_AUTO_INDENT, (raptor_option_area)(RAPTOR_OPTION_AREA_XML_WRITER | RAPTOR_OPTION_AREA_TURTLE_WRITER), RAPTOR_OPTION_VALUE_TYPE_BOOL, "autoIndent", "Turtle and XML Writer automatically indent elements." }, { RAPTOR_OPTION_WRITER_AUTO_EMPTY, (raptor_option_area)(RAPTOR_OPTION_AREA_XML_WRITER | RAPTOR_OPTION_AREA_TURTLE_WRITER), RAPTOR_OPTION_VALUE_TYPE_BOOL, "autoEmpty", "Turtle and XML Writer automatically detect and abbreviate empty elements." }, { RAPTOR_OPTION_WRITER_INDENT_WIDTH, (raptor_option_area)(RAPTOR_OPTION_AREA_XML_WRITER | RAPTOR_OPTION_AREA_TURTLE_WRITER), RAPTOR_OPTION_VALUE_TYPE_BOOL, "indentWidth", "Turtle and XML Writer use as number of spaces to indent." }, { RAPTOR_OPTION_WRITER_XML_VERSION, (raptor_option_area)(RAPTOR_OPTION_AREA_SERIALIZER | RAPTOR_OPTION_AREA_XML_WRITER), RAPTOR_OPTION_VALUE_TYPE_INT, "xmlVersion", "Serializers and XML Writer use as XML version to write." }, { RAPTOR_OPTION_WRITER_XML_DECLARATION, (raptor_option_area)(RAPTOR_OPTION_AREA_SERIALIZER | RAPTOR_OPTION_AREA_XML_WRITER), RAPTOR_OPTION_VALUE_TYPE_BOOL, "xmlDeclaration", "Serializers and XML Writer write XML declaration." }, { RAPTOR_OPTION_NO_NET, (raptor_option_area)(RAPTOR_OPTION_AREA_PARSER | RAPTOR_OPTION_AREA_SAX2), RAPTOR_OPTION_VALUE_TYPE_BOOL, "noNet", "Parsers and SAX2 XML Parser deny internal network requests." }, { RAPTOR_OPTION_RESOURCE_BORDER, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "resourceBorder", "DOT serializer resource border color" }, { RAPTOR_OPTION_LITERAL_BORDER, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "literalBorder", "DOT serializer literal border color" }, { RAPTOR_OPTION_BNODE_BORDER, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "bnodeBorder", "DOT serializer blank node border color" }, { RAPTOR_OPTION_RESOURCE_FILL, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "resourceFill", "DOT serializer resource fill color" }, { RAPTOR_OPTION_LITERAL_FILL, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "literalFill", "DOT serializer literal fill color" }, { RAPTOR_OPTION_BNODE_FILL, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "bnodeFill", "DOT serializer blank node fill color" }, { RAPTOR_OPTION_HTML_TAG_SOUP, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "htmlTagSoup", "GRDDL parser uses a lax HTML parser" }, { RAPTOR_OPTION_MICROFORMATS, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "microformats", "GRDDL parser looks for microformats" }, { RAPTOR_OPTION_HTML_LINK, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "htmlLink", "GRDDL parser looks for <link type=\"application/rdf+xml\">" }, { RAPTOR_OPTION_WWW_TIMEOUT, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_INT, "wwwTimeout", "Parser WWW request retrieval timeout" }, { RAPTOR_OPTION_WRITE_BASE_URI, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "writeBaseURI", "Serializers write a base URI directive @base / xml:base" }, { RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_STRING, "wwwHttpCacheControl", "Parser WWW request HTTP Cache-Control: header value" }, { RAPTOR_OPTION_WWW_HTTP_USER_AGENT, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_STRING, "wwwHttpUserAgent", "Parser WWW request HTTP User-Agent: header value" }, { RAPTOR_OPTION_JSON_CALLBACK, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "jsonCallback", "JSON serializer callback function name" }, { RAPTOR_OPTION_JSON_EXTRA_DATA, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "jsonExtraData", "JSON serializer callback data parameter" }, { RAPTOR_OPTION_RSS_TRIPLES, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_STRING, "rssTriples", "Atom and RSS serializers write extra RDF triples" }, { RAPTOR_OPTION_ATOM_ENTRY_URI, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_URI, "atomEntryUri", "Atom serializer writes an atom:entry with this URI (otherwise atom:feed)" }, { RAPTOR_OPTION_PREFIX_ELEMENTS, RAPTOR_OPTION_AREA_SERIALIZER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "prefixElements", "Atom and RSS serializers write namespace-prefixed elements" }, { RAPTOR_OPTION_STRICT, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_BOOL, "strict", "Operate in strict conformance mode (otherwise lax)" }, { RAPTOR_OPTION_WWW_CERT_FILENAME, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_STRING, "wwwCertFilename", "SSL client certificate filename" }, { RAPTOR_OPTION_WWW_CERT_TYPE, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_STRING, "wwwCertType", "SSL client certificate type" }, { RAPTOR_OPTION_WWW_CERT_PASSPHRASE, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_STRING, "wwwCertPassphrase", "SSL client certificate passphrase" }, { RAPTOR_OPTION_NO_FILE, (raptor_option_area)(RAPTOR_OPTION_AREA_PARSER | RAPTOR_OPTION_AREA_SAX2), RAPTOR_OPTION_VALUE_TYPE_BOOL, "noFile", "Parsers and SAX2 deny internal file requests." }, { RAPTOR_OPTION_WWW_SSL_VERIFY_PEER, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_INT, "wwwSslVerifyPeer", "SSL verify peer certficate" }, { RAPTOR_OPTION_WWW_SSL_VERIFY_HOST, RAPTOR_OPTION_AREA_PARSER, RAPTOR_OPTION_VALUE_TYPE_INT, "wwwSslVerifyHost", "SSL verify host matching" }, { RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES, (raptor_option_area)(RAPTOR_OPTION_AREA_PARSER | RAPTOR_OPTION_AREA_SAX2), RAPTOR_OPTION_VALUE_TYPE_BOOL, "loadExternalEntities", "Parsers and SAX2 should load external entities." } }; static const char * const raptor_option_uri_prefix = "http://feature.librdf.org/raptor-"; /* NOTE: this is strlen(raptor_option_uri_prefix) */ static const int raptor_option_uri_prefix_len = 33; static raptor_option_area raptor_option_get_option_area_for_domain(raptor_domain domain) { raptor_option_area area = RAPTOR_OPTION_AREA_NONE; if(domain == RAPTOR_DOMAIN_PARSER) area = RAPTOR_OPTION_AREA_PARSER; else if(domain == RAPTOR_DOMAIN_SERIALIZER) area = RAPTOR_OPTION_AREA_SERIALIZER; else if(domain == RAPTOR_DOMAIN_SAX2) area = RAPTOR_OPTION_AREA_SAX2; else if(domain == RAPTOR_DOMAIN_XML_WRITER) area = RAPTOR_OPTION_AREA_XML_WRITER; else if(domain == RAPTOR_DOMAIN_TURTLE_WRITER) area = RAPTOR_OPTION_AREA_TURTLE_WRITER; return area; } /** * raptor_free_option_description: * @option_description: option description * * Destructor - free an option description object. */ void raptor_free_option_description(raptor_option_description* option_description) { if(!option_description) return; /* these are shared strings pointing to static data in raptor_options_list[] */ /* RAPTOR_FREE(char*, option_description->name); */ /* RAPTOR_FREE(char*, option_description->label); */ if(option_description->uri) raptor_free_uri(option_description->uri); RAPTOR_FREE(raptor_option_description, option_description); } /** * raptor_world_get_option_description: * @world: raptor world object * @domain: domain * @option: option enumeration (0+) * * Get a description of an option for a domain. * * The returned description must be freed with * raptor_free_option_description(). * * Return value: option description or NULL on failure or if option is unknown **/ raptor_option_description* raptor_world_get_option_description(raptor_world* world, const raptor_domain domain, const raptor_option option) { raptor_option_area area; raptor_option_description *option_description = NULL; raptor_uri *base_uri = NULL; int i; RAPTOR_ASSERT_OBJECT_POINTER_RETURN_VALUE(world, raptor_world, NULL); raptor_world_open(world); area = raptor_option_get_option_area_for_domain(domain); if(area == RAPTOR_OPTION_AREA_NONE) return NULL; for(i = 0; i <= RAPTOR_OPTION_LAST; i++) { if(raptor_options_list[i].option == option && (raptor_options_list[i].area & area)) break; } if(i > RAPTOR_OPTION_LAST) return NULL; option_description = RAPTOR_CALLOC(raptor_option_description*, 1, sizeof(*option_description)); if(!option_description) return NULL; option_description->domain = domain; option_description->option = option; option_description->value_type = raptor_options_list[i].value_type; option_description->name = raptor_options_list[i].name; option_description->name_len = strlen(option_description->name); option_description->label = raptor_options_list[i].label; base_uri = raptor_new_uri_from_counted_string(world, (const unsigned char*)raptor_option_uri_prefix, raptor_option_uri_prefix_len); if(!base_uri) { raptor_free_option_description(option_description); return NULL; } option_description->uri = raptor_new_uri_from_uri_local_name(world, base_uri, (const unsigned char*)raptor_options_list[i].name); raptor_free_uri(base_uri); if(!option_description->uri) { raptor_free_option_description(option_description); return NULL; } return option_description; } int raptor_option_is_valid_for_area(const raptor_option option, raptor_option_area area) { if(option > RAPTOR_OPTION_LAST) return 0; return (raptor_options_list[option].area & area) != 0; } int raptor_option_value_is_numeric(const raptor_option option) { raptor_option_value_type t = raptor_options_list[option].value_type; return t == RAPTOR_OPTION_VALUE_TYPE_BOOL || t == RAPTOR_OPTION_VALUE_TYPE_INT; } /** * raptor_world_get_option_from_uri: * @world: raptor_world instance * @uri: option URI * * Get an option ID from a URI * * Option URIs are the concatenation of the string * "http://feature.librdf.org/raptor-" plus the short name. * * They are automatically returned for any option described with * raptor_world_get_option_description(). * * Return value: < 0 if the option is unknown or on error **/ raptor_option raptor_world_get_option_from_uri(raptor_world* world, raptor_uri *uri) { unsigned char *uri_string; int i; raptor_option option = (raptor_option)-1; if(!uri) return option; RAPTOR_ASSERT_OBJECT_POINTER_RETURN_VALUE(world, raptor_world, (raptor_option)-1); raptor_world_open(world); uri_string = raptor_uri_as_string(uri); if(strncmp((const char*)uri_string, raptor_option_uri_prefix, raptor_option_uri_prefix_len)) return option; uri_string += raptor_option_uri_prefix_len; for(i = 0; i <= RAPTOR_OPTION_LAST; i++) if(!strcmp(raptor_options_list[i].name, (const char*)uri_string)) { option = (raptor_option)i; break; } return option; } /** * raptor_option_get_count: * * Get the count of options defined. * * This is prefered to the compile time-only symbol #RAPTOR_OPTION_LAST * and returns a count of the number of options which is * #RAPTOR_OPTION_LAST + 1. * * Return value: count of options in the #raptor_option enumeration **/ unsigned int raptor_option_get_count(void) { return RAPTOR_OPTION_LAST + 1; } const char* const raptor_option_value_type_labels[RAPTOR_OPTION_VALUE_TYPE_URI + 1] = { "boolean", "integer", "string", "uri" }; /** * raptor_option_get_value_type_label: * @type: value type * * Get a label for a value type * * Return value: label for type or NULL for invalid type */ const char* raptor_option_get_value_type_label(const raptor_option_value_type type) { if(type > RAPTOR_OPTION_VALUE_TYPE_LAST) return NULL; return raptor_option_value_type_labels[type]; } int raptor_object_options_copy_state(raptor_object_options* to, raptor_object_options* from) { int rc = 0; int i; to->area = from->area; for(i = 0; !rc && i <= RAPTOR_OPTION_LAST; i++) { if(raptor_option_value_is_numeric((raptor_option)i)) to->options[i].integer = from->options[i].integer; else { /* non-numeric values may need allocations */ char* string = from->options[i].string; if(string) { size_t len = strlen(string); to->options[i].string = RAPTOR_MALLOC(char*, len + 1); if(to->options[i].string) memcpy(to->options[i].string, string, len + 1); else rc = 1; } } } return rc; } void raptor_object_options_init(raptor_object_options* options, raptor_option_area area) { int i; options->area = area; for(i = 0; i <= RAPTOR_OPTION_LAST; i++) { if(raptor_option_value_is_numeric((raptor_option)i)) options->options[i].integer = 0; else options->options[i].string = NULL; } /* Initialise default options that are not 0 or NULL */ /* Emit @base directive or equivalent */ options->options[RAPTOR_OPTION_WRITE_BASE_URI].integer = 1; /* Emit relative URIs where possible */ options->options[RAPTOR_OPTION_RELATIVE_URIS].integer = 1; /* XML 1.0 output */ options->options[RAPTOR_OPTION_WRITER_XML_VERSION].integer = 10; /* Write XML declaration */ options->options[RAPTOR_OPTION_WRITER_XML_DECLARATION].integer = 1; /* Indent 2 spaces */ options->options[RAPTOR_OPTION_WRITER_INDENT_WIDTH].integer = 2; /* lax (no strict) parsing */ options->options[RAPTOR_OPTION_STRICT].integer = 0; /* SSL verify peers */ options->options[RAPTOR_OPTION_WWW_SSL_VERIFY_PEER].integer = 1; /* SSL fully verify hosts */ options->options[RAPTOR_OPTION_WWW_SSL_VERIFY_HOST].integer = 2; } void raptor_object_options_clear(raptor_object_options* options) { int i; for(i = 0; i <= RAPTOR_OPTION_LAST; i++) { if(raptor_option_value_is_numeric((raptor_option)i)) continue; if(options->options[i].string) RAPTOR_FREE(char*, options->options[i].string); } } /* * raptor_object_options_get_option: * @options: options object * @option: option to get value * @string_p: pointer to where to store string value * @integer_p: pointer to where to store integer value * * INTERNAL - get option value * * Any string value returned in *@string_p is shared and must be * copied by the caller. * * The allowed options vary by the area field of @options. * * Return value: option value or < 0 for an illegal option **/ int raptor_object_options_get_option(raptor_object_options* options, raptor_option option, char** string_p, int* integer_p) { if(!raptor_option_is_valid_for_area(option, options->area)) return 1; if(raptor_option_value_is_numeric(option)) { /* numeric options */ int value = options->options[(int)option].integer; if(integer_p) *integer_p = value; } else { /* non-numeric options */ char* string = options->options[(int)option].string; if(string_p) *string_p = string; } return 0; } /* * raptor_object_options_set_option: * @options: options object * @option: option to set * @string: string option value (or NULL) * @integer: integer option value * * INTERNAL - set option * * If @string is not NULL and the option type is numeric, the string * value is converted to an integer and used in preference to @integer. * * If @string is NULL and the option type is not numeric, an error is * returned. * * The @string values used are copied. * * The allowed options vary by the area field of @options. * * Return value: non 0 on failure or if the option is unknown **/ int raptor_object_options_set_option(raptor_object_options *options, raptor_option option, const char* string, int integer) { if(!raptor_option_is_valid_for_area(option, options->area)) return 1; if(raptor_option_value_is_numeric(option)) { /* numeric options */ if(string) integer = atoi((const char*)string); options->options[(int)option].integer = integer; return 0; } else { /* non-numeric options */ char *string_copy; size_t len = 0; if(string) len = strlen((const char*)string); string_copy = RAPTOR_MALLOC(char*, len + 1); if(!string_copy) return 1; if(len) memcpy(string_copy, string, len); string_copy[len] = '\0'; options->options[(int)option].string = string_copy; } return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3568_7
crossvul-cpp_data_good_5099_0
/* * Copyright (c) 2006 Oracle. All rights reserved. * * This software is available to you under a choice of one of two * licenses. You may choose to be licensed under the terms of the GNU * General Public License (GPL) Version 2, available from the file * COPYING in the main directory of this source tree, or the * OpenIB.org BSD license below: * * Redistribution and use in source and binary forms, with or * without modification, are permitted provided that the following * conditions are met: * * - Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. * * - Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials * provided with the distribution. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * */ #include <linux/kernel.h> #include <linux/slab.h> #include <net/sock.h> #include <linux/in.h> #include <linux/export.h> #include <linux/time.h> #include <linux/rds.h> #include "rds.h" void rds_inc_init(struct rds_incoming *inc, struct rds_connection *conn, __be32 saddr) { atomic_set(&inc->i_refcount, 1); INIT_LIST_HEAD(&inc->i_item); inc->i_conn = conn; inc->i_saddr = saddr; inc->i_rdma_cookie = 0; inc->i_rx_tstamp.tv_sec = 0; inc->i_rx_tstamp.tv_usec = 0; } EXPORT_SYMBOL_GPL(rds_inc_init); static void rds_inc_addref(struct rds_incoming *inc) { rdsdebug("addref inc %p ref %d\n", inc, atomic_read(&inc->i_refcount)); atomic_inc(&inc->i_refcount); } void rds_inc_put(struct rds_incoming *inc) { rdsdebug("put inc %p ref %d\n", inc, atomic_read(&inc->i_refcount)); if (atomic_dec_and_test(&inc->i_refcount)) { BUG_ON(!list_empty(&inc->i_item)); inc->i_conn->c_trans->inc_free(inc); } } EXPORT_SYMBOL_GPL(rds_inc_put); static void rds_recv_rcvbuf_delta(struct rds_sock *rs, struct sock *sk, struct rds_cong_map *map, int delta, __be16 port) { int now_congested; if (delta == 0) return; rs->rs_rcv_bytes += delta; now_congested = rs->rs_rcv_bytes > rds_sk_rcvbuf(rs); rdsdebug("rs %p (%pI4:%u) recv bytes %d buf %d " "now_cong %d delta %d\n", rs, &rs->rs_bound_addr, ntohs(rs->rs_bound_port), rs->rs_rcv_bytes, rds_sk_rcvbuf(rs), now_congested, delta); /* wasn't -> am congested */ if (!rs->rs_congested && now_congested) { rs->rs_congested = 1; rds_cong_set_bit(map, port); rds_cong_queue_updates(map); } /* was -> aren't congested */ /* Require more free space before reporting uncongested to prevent bouncing cong/uncong state too often */ else if (rs->rs_congested && (rs->rs_rcv_bytes < (rds_sk_rcvbuf(rs)/2))) { rs->rs_congested = 0; rds_cong_clear_bit(map, port); rds_cong_queue_updates(map); } /* do nothing if no change in cong state */ } /* * Process all extension headers that come with this message. */ static void rds_recv_incoming_exthdrs(struct rds_incoming *inc, struct rds_sock *rs) { struct rds_header *hdr = &inc->i_hdr; unsigned int pos = 0, type, len; union { struct rds_ext_header_version version; struct rds_ext_header_rdma rdma; struct rds_ext_header_rdma_dest rdma_dest; } buffer; while (1) { len = sizeof(buffer); type = rds_message_next_extension(hdr, &pos, &buffer, &len); if (type == RDS_EXTHDR_NONE) break; /* Process extension header here */ switch (type) { case RDS_EXTHDR_RDMA: rds_rdma_unuse(rs, be32_to_cpu(buffer.rdma.h_rdma_rkey), 0); break; case RDS_EXTHDR_RDMA_DEST: /* We ignore the size for now. We could stash it * somewhere and use it for error checking. */ inc->i_rdma_cookie = rds_rdma_make_cookie( be32_to_cpu(buffer.rdma_dest.h_rdma_rkey), be32_to_cpu(buffer.rdma_dest.h_rdma_offset)); break; } } } /* * The transport must make sure that this is serialized against other * rx and conn reset on this specific conn. * * We currently assert that only one fragmented message will be sent * down a connection at a time. This lets us reassemble in the conn * instead of per-flow which means that we don't have to go digging through * flows to tear down partial reassembly progress on conn failure and * we save flow lookup and locking for each frag arrival. It does mean * that small messages will wait behind large ones. Fragmenting at all * is only to reduce the memory consumption of pre-posted buffers. * * The caller passes in saddr and daddr instead of us getting it from the * conn. This lets loopback, who only has one conn for both directions, * tell us which roles the addrs in the conn are playing for this message. */ void rds_recv_incoming(struct rds_connection *conn, __be32 saddr, __be32 daddr, struct rds_incoming *inc, gfp_t gfp) { struct rds_sock *rs = NULL; struct sock *sk; unsigned long flags; inc->i_conn = conn; inc->i_rx_jiffies = jiffies; rdsdebug("conn %p next %llu inc %p seq %llu len %u sport %u dport %u " "flags 0x%x rx_jiffies %lu\n", conn, (unsigned long long)conn->c_next_rx_seq, inc, (unsigned long long)be64_to_cpu(inc->i_hdr.h_sequence), be32_to_cpu(inc->i_hdr.h_len), be16_to_cpu(inc->i_hdr.h_sport), be16_to_cpu(inc->i_hdr.h_dport), inc->i_hdr.h_flags, inc->i_rx_jiffies); /* * Sequence numbers should only increase. Messages get their * sequence number as they're queued in a sending conn. They * can be dropped, though, if the sending socket is closed before * they hit the wire. So sequence numbers can skip forward * under normal operation. They can also drop back in the conn * failover case as previously sent messages are resent down the * new instance of a conn. We drop those, otherwise we have * to assume that the next valid seq does not come after a * hole in the fragment stream. * * The headers don't give us a way to realize if fragments of * a message have been dropped. We assume that frags that arrive * to a flow are part of the current message on the flow that is * being reassembled. This means that senders can't drop messages * from the sending conn until all their frags are sent. * * XXX we could spend more on the wire to get more robust failure * detection, arguably worth it to avoid data corruption. */ if (be64_to_cpu(inc->i_hdr.h_sequence) < conn->c_next_rx_seq && (inc->i_hdr.h_flags & RDS_FLAG_RETRANSMITTED)) { rds_stats_inc(s_recv_drop_old_seq); goto out; } conn->c_next_rx_seq = be64_to_cpu(inc->i_hdr.h_sequence) + 1; if (rds_sysctl_ping_enable && inc->i_hdr.h_dport == 0) { rds_stats_inc(s_recv_ping); rds_send_pong(conn, inc->i_hdr.h_sport); goto out; } rs = rds_find_bound(daddr, inc->i_hdr.h_dport); if (!rs) { rds_stats_inc(s_recv_drop_no_sock); goto out; } /* Process extension headers */ rds_recv_incoming_exthdrs(inc, rs); /* We can be racing with rds_release() which marks the socket dead. */ sk = rds_rs_to_sk(rs); /* serialize with rds_release -> sock_orphan */ write_lock_irqsave(&rs->rs_recv_lock, flags); if (!sock_flag(sk, SOCK_DEAD)) { rdsdebug("adding inc %p to rs %p's recv queue\n", inc, rs); rds_stats_inc(s_recv_queued); rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, be32_to_cpu(inc->i_hdr.h_len), inc->i_hdr.h_dport); if (sock_flag(sk, SOCK_RCVTSTAMP)) do_gettimeofday(&inc->i_rx_tstamp); rds_inc_addref(inc); list_add_tail(&inc->i_item, &rs->rs_recv_queue); __rds_wake_sk_sleep(sk); } else { rds_stats_inc(s_recv_drop_dead_sock); } write_unlock_irqrestore(&rs->rs_recv_lock, flags); out: if (rs) rds_sock_put(rs); } EXPORT_SYMBOL_GPL(rds_recv_incoming); /* * be very careful here. This is being called as the condition in * wait_event_*() needs to cope with being called many times. */ static int rds_next_incoming(struct rds_sock *rs, struct rds_incoming **inc) { unsigned long flags; if (!*inc) { read_lock_irqsave(&rs->rs_recv_lock, flags); if (!list_empty(&rs->rs_recv_queue)) { *inc = list_entry(rs->rs_recv_queue.next, struct rds_incoming, i_item); rds_inc_addref(*inc); } read_unlock_irqrestore(&rs->rs_recv_lock, flags); } return *inc != NULL; } static int rds_still_queued(struct rds_sock *rs, struct rds_incoming *inc, int drop) { struct sock *sk = rds_rs_to_sk(rs); int ret = 0; unsigned long flags; write_lock_irqsave(&rs->rs_recv_lock, flags); if (!list_empty(&inc->i_item)) { ret = 1; if (drop) { /* XXX make sure this i_conn is reliable */ rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, -be32_to_cpu(inc->i_hdr.h_len), inc->i_hdr.h_dport); list_del_init(&inc->i_item); rds_inc_put(inc); } } write_unlock_irqrestore(&rs->rs_recv_lock, flags); rdsdebug("inc %p rs %p still %d dropped %d\n", inc, rs, ret, drop); return ret; } /* * Pull errors off the error queue. * If msghdr is NULL, we will just purge the error queue. */ int rds_notify_queue_get(struct rds_sock *rs, struct msghdr *msghdr) { struct rds_notifier *notifier; struct rds_rdma_notify cmsg = { 0 }; /* fill holes with zero */ unsigned int count = 0, max_messages = ~0U; unsigned long flags; LIST_HEAD(copy); int err = 0; /* put_cmsg copies to user space and thus may sleep. We can't do this * with rs_lock held, so first grab as many notifications as we can stuff * in the user provided cmsg buffer. We don't try to copy more, to avoid * losing notifications - except when the buffer is so small that it wouldn't * even hold a single notification. Then we give him as much of this single * msg as we can squeeze in, and set MSG_CTRUNC. */ if (msghdr) { max_messages = msghdr->msg_controllen / CMSG_SPACE(sizeof(cmsg)); if (!max_messages) max_messages = 1; } spin_lock_irqsave(&rs->rs_lock, flags); while (!list_empty(&rs->rs_notify_queue) && count < max_messages) { notifier = list_entry(rs->rs_notify_queue.next, struct rds_notifier, n_list); list_move(&notifier->n_list, &copy); count++; } spin_unlock_irqrestore(&rs->rs_lock, flags); if (!count) return 0; while (!list_empty(&copy)) { notifier = list_entry(copy.next, struct rds_notifier, n_list); if (msghdr) { cmsg.user_token = notifier->n_user_token; cmsg.status = notifier->n_status; err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_RDMA_STATUS, sizeof(cmsg), &cmsg); if (err) break; } list_del_init(&notifier->n_list); kfree(notifier); } /* If we bailed out because of an error in put_cmsg, * we may be left with one or more notifications that we * didn't process. Return them to the head of the list. */ if (!list_empty(&copy)) { spin_lock_irqsave(&rs->rs_lock, flags); list_splice(&copy, &rs->rs_notify_queue); spin_unlock_irqrestore(&rs->rs_lock, flags); } return err; } /* * Queue a congestion notification */ static int rds_notify_cong(struct rds_sock *rs, struct msghdr *msghdr) { uint64_t notify = rs->rs_cong_notify; unsigned long flags; int err; err = put_cmsg(msghdr, SOL_RDS, RDS_CMSG_CONG_UPDATE, sizeof(notify), &notify); if (err) return err; spin_lock_irqsave(&rs->rs_lock, flags); rs->rs_cong_notify &= ~notify; spin_unlock_irqrestore(&rs->rs_lock, flags); return 0; } /* * Receive any control messages. */ static int rds_cmsg_recv(struct rds_incoming *inc, struct msghdr *msg, struct rds_sock *rs) { int ret = 0; if (inc->i_rdma_cookie) { ret = put_cmsg(msg, SOL_RDS, RDS_CMSG_RDMA_DEST, sizeof(inc->i_rdma_cookie), &inc->i_rdma_cookie); if (ret) return ret; } if ((inc->i_rx_tstamp.tv_sec != 0) && sock_flag(rds_rs_to_sk(rs), SOCK_RCVTSTAMP)) { ret = put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMP, sizeof(struct timeval), &inc->i_rx_tstamp); if (ret) return ret; } return 0; } int rds_recvmsg(struct socket *sock, struct msghdr *msg, size_t size, int msg_flags) { struct sock *sk = sock->sk; struct rds_sock *rs = rds_sk_to_rs(sk); long timeo; int ret = 0, nonblock = msg_flags & MSG_DONTWAIT; DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name); struct rds_incoming *inc = NULL; /* udp_recvmsg()->sock_recvtimeo() gets away without locking too.. */ timeo = sock_rcvtimeo(sk, nonblock); rdsdebug("size %zu flags 0x%x timeo %ld\n", size, msg_flags, timeo); if (msg_flags & MSG_OOB) goto out; while (1) { struct iov_iter save; /* If there are pending notifications, do those - and nothing else */ if (!list_empty(&rs->rs_notify_queue)) { ret = rds_notify_queue_get(rs, msg); break; } if (rs->rs_cong_notify) { ret = rds_notify_cong(rs, msg); break; } if (!rds_next_incoming(rs, &inc)) { if (nonblock) { ret = -EAGAIN; break; } timeo = wait_event_interruptible_timeout(*sk_sleep(sk), (!list_empty(&rs->rs_notify_queue) || rs->rs_cong_notify || rds_next_incoming(rs, &inc)), timeo); rdsdebug("recvmsg woke inc %p timeo %ld\n", inc, timeo); if (timeo > 0 || timeo == MAX_SCHEDULE_TIMEOUT) continue; ret = timeo; if (ret == 0) ret = -ETIMEDOUT; break; } rdsdebug("copying inc %p from %pI4:%u to user\n", inc, &inc->i_conn->c_faddr, ntohs(inc->i_hdr.h_sport)); save = msg->msg_iter; ret = inc->i_conn->c_trans->inc_copy_to_user(inc, &msg->msg_iter); if (ret < 0) break; /* * if the message we just copied isn't at the head of the * recv queue then someone else raced us to return it, try * to get the next message. */ if (!rds_still_queued(rs, inc, !(msg_flags & MSG_PEEK))) { rds_inc_put(inc); inc = NULL; rds_stats_inc(s_recv_deliver_raced); msg->msg_iter = save; continue; } if (ret < be32_to_cpu(inc->i_hdr.h_len)) { if (msg_flags & MSG_TRUNC) ret = be32_to_cpu(inc->i_hdr.h_len); msg->msg_flags |= MSG_TRUNC; } if (rds_cmsg_recv(inc, msg, rs)) { ret = -EFAULT; goto out; } rds_stats_inc(s_recv_delivered); if (sin) { sin->sin_family = AF_INET; sin->sin_port = inc->i_hdr.h_sport; sin->sin_addr.s_addr = inc->i_saddr; memset(sin->sin_zero, 0, sizeof(sin->sin_zero)); msg->msg_namelen = sizeof(*sin); } break; } if (inc) rds_inc_put(inc); out: return ret; } /* * The socket is being shut down and we're asked to drop messages that were * queued for recvmsg. The caller has unbound the socket so the receive path * won't queue any more incoming fragments or messages on the socket. */ void rds_clear_recv_queue(struct rds_sock *rs) { struct sock *sk = rds_rs_to_sk(rs); struct rds_incoming *inc, *tmp; unsigned long flags; write_lock_irqsave(&rs->rs_recv_lock, flags); list_for_each_entry_safe(inc, tmp, &rs->rs_recv_queue, i_item) { rds_recv_rcvbuf_delta(rs, sk, inc->i_conn->c_lcong, -be32_to_cpu(inc->i_hdr.h_len), inc->i_hdr.h_dport); list_del_init(&inc->i_item); rds_inc_put(inc); } write_unlock_irqrestore(&rs->rs_recv_lock, flags); } /* * inc->i_saddr isn't used here because it is only set in the receive * path. */ void rds_inc_info_copy(struct rds_incoming *inc, struct rds_info_iterator *iter, __be32 saddr, __be32 daddr, int flip) { struct rds_info_message minfo; minfo.seq = be64_to_cpu(inc->i_hdr.h_sequence); minfo.len = be32_to_cpu(inc->i_hdr.h_len); if (flip) { minfo.laddr = daddr; minfo.faddr = saddr; minfo.lport = inc->i_hdr.h_dport; minfo.fport = inc->i_hdr.h_sport; } else { minfo.laddr = saddr; minfo.faddr = daddr; minfo.lport = inc->i_hdr.h_sport; minfo.fport = inc->i_hdr.h_dport; } minfo.flags = 0; rds_info_copy(iter, &minfo, sizeof(minfo)); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_5099_0
crossvul-cpp_data_bad_5050_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Routing netlink socket interface: protocol independent part. * * Authors: Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Fixes: * Vitaly E. Lavrov RTA_OK arithmetics was wrong. */ #include <linux/errno.h> #include <linux/module.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/kernel.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/fcntl.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/interrupt.h> #include <linux/capability.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/security.h> #include <linux/mutex.h> #include <linux/if_addr.h> #include <linux/if_bridge.h> #include <linux/if_vlan.h> #include <linux/pci.h> #include <linux/etherdevice.h> #include <asm/uaccess.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <net/switchdev.h> #include <net/ip.h> #include <net/protocol.h> #include <net/arp.h> #include <net/route.h> #include <net/udp.h> #include <net/tcp.h> #include <net/sock.h> #include <net/pkt_sched.h> #include <net/fib_rules.h> #include <net/rtnetlink.h> #include <net/net_namespace.h> struct rtnl_link { rtnl_doit_func doit; rtnl_dumpit_func dumpit; rtnl_calcit_func calcit; }; static DEFINE_MUTEX(rtnl_mutex); void rtnl_lock(void) { mutex_lock(&rtnl_mutex); } EXPORT_SYMBOL(rtnl_lock); void __rtnl_unlock(void) { mutex_unlock(&rtnl_mutex); } void rtnl_unlock(void) { /* This fellow will unlock it for us. */ netdev_run_todo(); } EXPORT_SYMBOL(rtnl_unlock); int rtnl_trylock(void) { return mutex_trylock(&rtnl_mutex); } EXPORT_SYMBOL(rtnl_trylock); int rtnl_is_locked(void) { return mutex_is_locked(&rtnl_mutex); } EXPORT_SYMBOL(rtnl_is_locked); #ifdef CONFIG_PROVE_LOCKING bool lockdep_rtnl_is_held(void) { return lockdep_is_held(&rtnl_mutex); } EXPORT_SYMBOL(lockdep_rtnl_is_held); #endif /* #ifdef CONFIG_PROVE_LOCKING */ static struct rtnl_link *rtnl_msg_handlers[RTNL_FAMILY_MAX + 1]; static inline int rtm_msgindex(int msgtype) { int msgindex = msgtype - RTM_BASE; /* * msgindex < 0 implies someone tried to register a netlink * control code. msgindex >= RTM_NR_MSGTYPES may indicate that * the message type has not been added to linux/rtnetlink.h */ BUG_ON(msgindex < 0 || msgindex >= RTM_NR_MSGTYPES); return msgindex; } static rtnl_doit_func rtnl_get_doit(int protocol, int msgindex) { struct rtnl_link *tab; if (protocol <= RTNL_FAMILY_MAX) tab = rtnl_msg_handlers[protocol]; else tab = NULL; if (tab == NULL || tab[msgindex].doit == NULL) tab = rtnl_msg_handlers[PF_UNSPEC]; return tab[msgindex].doit; } static rtnl_dumpit_func rtnl_get_dumpit(int protocol, int msgindex) { struct rtnl_link *tab; if (protocol <= RTNL_FAMILY_MAX) tab = rtnl_msg_handlers[protocol]; else tab = NULL; if (tab == NULL || tab[msgindex].dumpit == NULL) tab = rtnl_msg_handlers[PF_UNSPEC]; return tab[msgindex].dumpit; } static rtnl_calcit_func rtnl_get_calcit(int protocol, int msgindex) { struct rtnl_link *tab; if (protocol <= RTNL_FAMILY_MAX) tab = rtnl_msg_handlers[protocol]; else tab = NULL; if (tab == NULL || tab[msgindex].calcit == NULL) tab = rtnl_msg_handlers[PF_UNSPEC]; return tab[msgindex].calcit; } /** * __rtnl_register - Register a rtnetlink message type * @protocol: Protocol family or PF_UNSPEC * @msgtype: rtnetlink message type * @doit: Function pointer called for each request message * @dumpit: Function pointer called for each dump request (NLM_F_DUMP) message * @calcit: Function pointer to calc size of dump message * * Registers the specified function pointers (at least one of them has * to be non-NULL) to be called whenever a request message for the * specified protocol family and message type is received. * * The special protocol family PF_UNSPEC may be used to define fallback * function pointers for the case when no entry for the specific protocol * family exists. * * Returns 0 on success or a negative error code. */ int __rtnl_register(int protocol, int msgtype, rtnl_doit_func doit, rtnl_dumpit_func dumpit, rtnl_calcit_func calcit) { struct rtnl_link *tab; int msgindex; BUG_ON(protocol < 0 || protocol > RTNL_FAMILY_MAX); msgindex = rtm_msgindex(msgtype); tab = rtnl_msg_handlers[protocol]; if (tab == NULL) { tab = kcalloc(RTM_NR_MSGTYPES, sizeof(*tab), GFP_KERNEL); if (tab == NULL) return -ENOBUFS; rtnl_msg_handlers[protocol] = tab; } if (doit) tab[msgindex].doit = doit; if (dumpit) tab[msgindex].dumpit = dumpit; if (calcit) tab[msgindex].calcit = calcit; return 0; } EXPORT_SYMBOL_GPL(__rtnl_register); /** * rtnl_register - Register a rtnetlink message type * * Identical to __rtnl_register() but panics on failure. This is useful * as failure of this function is very unlikely, it can only happen due * to lack of memory when allocating the chain to store all message * handlers for a protocol. Meant for use in init functions where lack * of memory implies no sense in continuing. */ void rtnl_register(int protocol, int msgtype, rtnl_doit_func doit, rtnl_dumpit_func dumpit, rtnl_calcit_func calcit) { if (__rtnl_register(protocol, msgtype, doit, dumpit, calcit) < 0) panic("Unable to register rtnetlink message handler, " "protocol = %d, message type = %d\n", protocol, msgtype); } EXPORT_SYMBOL_GPL(rtnl_register); /** * rtnl_unregister - Unregister a rtnetlink message type * @protocol: Protocol family or PF_UNSPEC * @msgtype: rtnetlink message type * * Returns 0 on success or a negative error code. */ int rtnl_unregister(int protocol, int msgtype) { int msgindex; BUG_ON(protocol < 0 || protocol > RTNL_FAMILY_MAX); msgindex = rtm_msgindex(msgtype); if (rtnl_msg_handlers[protocol] == NULL) return -ENOENT; rtnl_msg_handlers[protocol][msgindex].doit = NULL; rtnl_msg_handlers[protocol][msgindex].dumpit = NULL; return 0; } EXPORT_SYMBOL_GPL(rtnl_unregister); /** * rtnl_unregister_all - Unregister all rtnetlink message type of a protocol * @protocol : Protocol family or PF_UNSPEC * * Identical to calling rtnl_unregster() for all registered message types * of a certain protocol family. */ void rtnl_unregister_all(int protocol) { BUG_ON(protocol < 0 || protocol > RTNL_FAMILY_MAX); kfree(rtnl_msg_handlers[protocol]); rtnl_msg_handlers[protocol] = NULL; } EXPORT_SYMBOL_GPL(rtnl_unregister_all); static LIST_HEAD(link_ops); static const struct rtnl_link_ops *rtnl_link_ops_get(const char *kind) { const struct rtnl_link_ops *ops; list_for_each_entry(ops, &link_ops, list) { if (!strcmp(ops->kind, kind)) return ops; } return NULL; } /** * __rtnl_link_register - Register rtnl_link_ops with rtnetlink. * @ops: struct rtnl_link_ops * to register * * The caller must hold the rtnl_mutex. This function should be used * by drivers that create devices during module initialization. It * must be called before registering the devices. * * Returns 0 on success or a negative error code. */ int __rtnl_link_register(struct rtnl_link_ops *ops) { if (rtnl_link_ops_get(ops->kind)) return -EEXIST; /* The check for setup is here because if ops * does not have that filled up, it is not possible * to use the ops for creating device. So do not * fill up dellink as well. That disables rtnl_dellink. */ if (ops->setup && !ops->dellink) ops->dellink = unregister_netdevice_queue; list_add_tail(&ops->list, &link_ops); return 0; } EXPORT_SYMBOL_GPL(__rtnl_link_register); /** * rtnl_link_register - Register rtnl_link_ops with rtnetlink. * @ops: struct rtnl_link_ops * to register * * Returns 0 on success or a negative error code. */ int rtnl_link_register(struct rtnl_link_ops *ops) { int err; rtnl_lock(); err = __rtnl_link_register(ops); rtnl_unlock(); return err; } EXPORT_SYMBOL_GPL(rtnl_link_register); static void __rtnl_kill_links(struct net *net, struct rtnl_link_ops *ops) { struct net_device *dev; LIST_HEAD(list_kill); for_each_netdev(net, dev) { if (dev->rtnl_link_ops == ops) ops->dellink(dev, &list_kill); } unregister_netdevice_many(&list_kill); } /** * __rtnl_link_unregister - Unregister rtnl_link_ops from rtnetlink. * @ops: struct rtnl_link_ops * to unregister * * The caller must hold the rtnl_mutex. */ void __rtnl_link_unregister(struct rtnl_link_ops *ops) { struct net *net; for_each_net(net) { __rtnl_kill_links(net, ops); } list_del(&ops->list); } EXPORT_SYMBOL_GPL(__rtnl_link_unregister); /* Return with the rtnl_lock held when there are no network * devices unregistering in any network namespace. */ static void rtnl_lock_unregistering_all(void) { struct net *net; bool unregistering; DEFINE_WAIT_FUNC(wait, woken_wake_function); add_wait_queue(&netdev_unregistering_wq, &wait); for (;;) { unregistering = false; rtnl_lock(); for_each_net(net) { if (net->dev_unreg_count > 0) { unregistering = true; break; } } if (!unregistering) break; __rtnl_unlock(); wait_woken(&wait, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT); } remove_wait_queue(&netdev_unregistering_wq, &wait); } /** * rtnl_link_unregister - Unregister rtnl_link_ops from rtnetlink. * @ops: struct rtnl_link_ops * to unregister */ void rtnl_link_unregister(struct rtnl_link_ops *ops) { /* Close the race with cleanup_net() */ mutex_lock(&net_mutex); rtnl_lock_unregistering_all(); __rtnl_link_unregister(ops); rtnl_unlock(); mutex_unlock(&net_mutex); } EXPORT_SYMBOL_GPL(rtnl_link_unregister); static size_t rtnl_link_get_slave_info_data_size(const struct net_device *dev) { struct net_device *master_dev; const struct rtnl_link_ops *ops; master_dev = netdev_master_upper_dev_get((struct net_device *) dev); if (!master_dev) return 0; ops = master_dev->rtnl_link_ops; if (!ops || !ops->get_slave_size) return 0; /* IFLA_INFO_SLAVE_DATA + nested data */ return nla_total_size(sizeof(struct nlattr)) + ops->get_slave_size(master_dev, dev); } static size_t rtnl_link_get_size(const struct net_device *dev) { const struct rtnl_link_ops *ops = dev->rtnl_link_ops; size_t size; if (!ops) return 0; size = nla_total_size(sizeof(struct nlattr)) + /* IFLA_LINKINFO */ nla_total_size(strlen(ops->kind) + 1); /* IFLA_INFO_KIND */ if (ops->get_size) /* IFLA_INFO_DATA + nested data */ size += nla_total_size(sizeof(struct nlattr)) + ops->get_size(dev); if (ops->get_xstats_size) /* IFLA_INFO_XSTATS */ size += nla_total_size(ops->get_xstats_size(dev)); size += rtnl_link_get_slave_info_data_size(dev); return size; } static LIST_HEAD(rtnl_af_ops); static const struct rtnl_af_ops *rtnl_af_lookup(const int family) { const struct rtnl_af_ops *ops; list_for_each_entry(ops, &rtnl_af_ops, list) { if (ops->family == family) return ops; } return NULL; } /** * rtnl_af_register - Register rtnl_af_ops with rtnetlink. * @ops: struct rtnl_af_ops * to register * * Returns 0 on success or a negative error code. */ void rtnl_af_register(struct rtnl_af_ops *ops) { rtnl_lock(); list_add_tail(&ops->list, &rtnl_af_ops); rtnl_unlock(); } EXPORT_SYMBOL_GPL(rtnl_af_register); /** * __rtnl_af_unregister - Unregister rtnl_af_ops from rtnetlink. * @ops: struct rtnl_af_ops * to unregister * * The caller must hold the rtnl_mutex. */ void __rtnl_af_unregister(struct rtnl_af_ops *ops) { list_del(&ops->list); } EXPORT_SYMBOL_GPL(__rtnl_af_unregister); /** * rtnl_af_unregister - Unregister rtnl_af_ops from rtnetlink. * @ops: struct rtnl_af_ops * to unregister */ void rtnl_af_unregister(struct rtnl_af_ops *ops) { rtnl_lock(); __rtnl_af_unregister(ops); rtnl_unlock(); } EXPORT_SYMBOL_GPL(rtnl_af_unregister); static size_t rtnl_link_get_af_size(const struct net_device *dev, u32 ext_filter_mask) { struct rtnl_af_ops *af_ops; size_t size; /* IFLA_AF_SPEC */ size = nla_total_size(sizeof(struct nlattr)); list_for_each_entry(af_ops, &rtnl_af_ops, list) { if (af_ops->get_link_af_size) { /* AF_* + nested data */ size += nla_total_size(sizeof(struct nlattr)) + af_ops->get_link_af_size(dev, ext_filter_mask); } } return size; } static bool rtnl_have_link_slave_info(const struct net_device *dev) { struct net_device *master_dev; master_dev = netdev_master_upper_dev_get((struct net_device *) dev); if (master_dev && master_dev->rtnl_link_ops) return true; return false; } static int rtnl_link_slave_info_fill(struct sk_buff *skb, const struct net_device *dev) { struct net_device *master_dev; const struct rtnl_link_ops *ops; struct nlattr *slave_data; int err; master_dev = netdev_master_upper_dev_get((struct net_device *) dev); if (!master_dev) return 0; ops = master_dev->rtnl_link_ops; if (!ops) return 0; if (nla_put_string(skb, IFLA_INFO_SLAVE_KIND, ops->kind) < 0) return -EMSGSIZE; if (ops->fill_slave_info) { slave_data = nla_nest_start(skb, IFLA_INFO_SLAVE_DATA); if (!slave_data) return -EMSGSIZE; err = ops->fill_slave_info(skb, master_dev, dev); if (err < 0) goto err_cancel_slave_data; nla_nest_end(skb, slave_data); } return 0; err_cancel_slave_data: nla_nest_cancel(skb, slave_data); return err; } static int rtnl_link_info_fill(struct sk_buff *skb, const struct net_device *dev) { const struct rtnl_link_ops *ops = dev->rtnl_link_ops; struct nlattr *data; int err; if (!ops) return 0; if (nla_put_string(skb, IFLA_INFO_KIND, ops->kind) < 0) return -EMSGSIZE; if (ops->fill_xstats) { err = ops->fill_xstats(skb, dev); if (err < 0) return err; } if (ops->fill_info) { data = nla_nest_start(skb, IFLA_INFO_DATA); if (data == NULL) return -EMSGSIZE; err = ops->fill_info(skb, dev); if (err < 0) goto err_cancel_data; nla_nest_end(skb, data); } return 0; err_cancel_data: nla_nest_cancel(skb, data); return err; } static int rtnl_link_fill(struct sk_buff *skb, const struct net_device *dev) { struct nlattr *linkinfo; int err = -EMSGSIZE; linkinfo = nla_nest_start(skb, IFLA_LINKINFO); if (linkinfo == NULL) goto out; err = rtnl_link_info_fill(skb, dev); if (err < 0) goto err_cancel_link; err = rtnl_link_slave_info_fill(skb, dev); if (err < 0) goto err_cancel_link; nla_nest_end(skb, linkinfo); return 0; err_cancel_link: nla_nest_cancel(skb, linkinfo); out: return err; } int rtnetlink_send(struct sk_buff *skb, struct net *net, u32 pid, unsigned int group, int echo) { struct sock *rtnl = net->rtnl; int err = 0; NETLINK_CB(skb).dst_group = group; if (echo) atomic_inc(&skb->users); netlink_broadcast(rtnl, skb, pid, group, GFP_KERNEL); if (echo) err = netlink_unicast(rtnl, skb, pid, MSG_DONTWAIT); return err; } int rtnl_unicast(struct sk_buff *skb, struct net *net, u32 pid) { struct sock *rtnl = net->rtnl; return nlmsg_unicast(rtnl, skb, pid); } EXPORT_SYMBOL(rtnl_unicast); void rtnl_notify(struct sk_buff *skb, struct net *net, u32 pid, u32 group, struct nlmsghdr *nlh, gfp_t flags) { struct sock *rtnl = net->rtnl; int report = 0; if (nlh) report = nlmsg_report(nlh); nlmsg_notify(rtnl, skb, pid, group, report, flags); } EXPORT_SYMBOL(rtnl_notify); void rtnl_set_sk_err(struct net *net, u32 group, int error) { struct sock *rtnl = net->rtnl; netlink_set_err(rtnl, 0, group, error); } EXPORT_SYMBOL(rtnl_set_sk_err); int rtnetlink_put_metrics(struct sk_buff *skb, u32 *metrics) { struct nlattr *mx; int i, valid = 0; mx = nla_nest_start(skb, RTA_METRICS); if (mx == NULL) return -ENOBUFS; for (i = 0; i < RTAX_MAX; i++) { if (metrics[i]) { if (i == RTAX_CC_ALGO - 1) { char tmp[TCP_CA_NAME_MAX], *name; name = tcp_ca_get_name_by_key(metrics[i], tmp); if (!name) continue; if (nla_put_string(skb, i + 1, name)) goto nla_put_failure; } else if (i == RTAX_FEATURES - 1) { u32 user_features = metrics[i] & RTAX_FEATURE_MASK; BUILD_BUG_ON(RTAX_FEATURE_MASK & DST_FEATURE_MASK); if (nla_put_u32(skb, i + 1, user_features)) goto nla_put_failure; } else { if (nla_put_u32(skb, i + 1, metrics[i])) goto nla_put_failure; } valid++; } } if (!valid) { nla_nest_cancel(skb, mx); return 0; } return nla_nest_end(skb, mx); nla_put_failure: nla_nest_cancel(skb, mx); return -EMSGSIZE; } EXPORT_SYMBOL(rtnetlink_put_metrics); int rtnl_put_cacheinfo(struct sk_buff *skb, struct dst_entry *dst, u32 id, long expires, u32 error) { struct rta_cacheinfo ci = { .rta_lastuse = jiffies_delta_to_clock_t(jiffies - dst->lastuse), .rta_used = dst->__use, .rta_clntref = atomic_read(&(dst->__refcnt)), .rta_error = error, .rta_id = id, }; if (expires) { unsigned long clock; clock = jiffies_to_clock_t(abs(expires)); clock = min_t(unsigned long, clock, INT_MAX); ci.rta_expires = (expires > 0) ? clock : -clock; } return nla_put(skb, RTA_CACHEINFO, sizeof(ci), &ci); } EXPORT_SYMBOL_GPL(rtnl_put_cacheinfo); static void set_operstate(struct net_device *dev, unsigned char transition) { unsigned char operstate = dev->operstate; switch (transition) { case IF_OPER_UP: if ((operstate == IF_OPER_DORMANT || operstate == IF_OPER_UNKNOWN) && !netif_dormant(dev)) operstate = IF_OPER_UP; break; case IF_OPER_DORMANT: if (operstate == IF_OPER_UP || operstate == IF_OPER_UNKNOWN) operstate = IF_OPER_DORMANT; break; } if (dev->operstate != operstate) { write_lock_bh(&dev_base_lock); dev->operstate = operstate; write_unlock_bh(&dev_base_lock); netdev_state_change(dev); } } static unsigned int rtnl_dev_get_flags(const struct net_device *dev) { return (dev->flags & ~(IFF_PROMISC | IFF_ALLMULTI)) | (dev->gflags & (IFF_PROMISC | IFF_ALLMULTI)); } static unsigned int rtnl_dev_combine_flags(const struct net_device *dev, const struct ifinfomsg *ifm) { unsigned int flags = ifm->ifi_flags; /* bugwards compatibility: ifi_change == 0 is treated as ~0 */ if (ifm->ifi_change) flags = (flags & ifm->ifi_change) | (rtnl_dev_get_flags(dev) & ~ifm->ifi_change); return flags; } static void copy_rtnl_link_stats(struct rtnl_link_stats *a, const struct rtnl_link_stats64 *b) { a->rx_packets = b->rx_packets; a->tx_packets = b->tx_packets; a->rx_bytes = b->rx_bytes; a->tx_bytes = b->tx_bytes; a->rx_errors = b->rx_errors; a->tx_errors = b->tx_errors; a->rx_dropped = b->rx_dropped; a->tx_dropped = b->tx_dropped; a->multicast = b->multicast; a->collisions = b->collisions; a->rx_length_errors = b->rx_length_errors; a->rx_over_errors = b->rx_over_errors; a->rx_crc_errors = b->rx_crc_errors; a->rx_frame_errors = b->rx_frame_errors; a->rx_fifo_errors = b->rx_fifo_errors; a->rx_missed_errors = b->rx_missed_errors; a->tx_aborted_errors = b->tx_aborted_errors; a->tx_carrier_errors = b->tx_carrier_errors; a->tx_fifo_errors = b->tx_fifo_errors; a->tx_heartbeat_errors = b->tx_heartbeat_errors; a->tx_window_errors = b->tx_window_errors; a->rx_compressed = b->rx_compressed; a->tx_compressed = b->tx_compressed; a->rx_nohandler = b->rx_nohandler; } static void copy_rtnl_link_stats64(void *v, const struct rtnl_link_stats64 *b) { memcpy(v, b, sizeof(*b)); } /* All VF info */ static inline int rtnl_vfinfo_size(const struct net_device *dev, u32 ext_filter_mask) { if (dev->dev.parent && dev_is_pci(dev->dev.parent) && (ext_filter_mask & RTEXT_FILTER_VF)) { int num_vfs = dev_num_vf(dev->dev.parent); size_t size = nla_total_size(sizeof(struct nlattr)); size += nla_total_size(num_vfs * sizeof(struct nlattr)); size += num_vfs * (nla_total_size(sizeof(struct ifla_vf_mac)) + nla_total_size(sizeof(struct ifla_vf_vlan)) + nla_total_size(sizeof(struct ifla_vf_spoofchk)) + nla_total_size(sizeof(struct ifla_vf_rate)) + nla_total_size(sizeof(struct ifla_vf_link_state)) + nla_total_size(sizeof(struct ifla_vf_rss_query_en)) + /* IFLA_VF_STATS_RX_PACKETS */ nla_total_size(sizeof(__u64)) + /* IFLA_VF_STATS_TX_PACKETS */ nla_total_size(sizeof(__u64)) + /* IFLA_VF_STATS_RX_BYTES */ nla_total_size(sizeof(__u64)) + /* IFLA_VF_STATS_TX_BYTES */ nla_total_size(sizeof(__u64)) + /* IFLA_VF_STATS_BROADCAST */ nla_total_size(sizeof(__u64)) + /* IFLA_VF_STATS_MULTICAST */ nla_total_size(sizeof(__u64)) + nla_total_size(sizeof(struct ifla_vf_trust))); return size; } else return 0; } static size_t rtnl_port_size(const struct net_device *dev, u32 ext_filter_mask) { size_t port_size = nla_total_size(4) /* PORT_VF */ + nla_total_size(PORT_PROFILE_MAX) /* PORT_PROFILE */ + nla_total_size(sizeof(struct ifla_port_vsi)) /* PORT_VSI_TYPE */ + nla_total_size(PORT_UUID_MAX) /* PORT_INSTANCE_UUID */ + nla_total_size(PORT_UUID_MAX) /* PORT_HOST_UUID */ + nla_total_size(1) /* PROT_VDP_REQUEST */ + nla_total_size(2); /* PORT_VDP_RESPONSE */ size_t vf_ports_size = nla_total_size(sizeof(struct nlattr)); size_t vf_port_size = nla_total_size(sizeof(struct nlattr)) + port_size; size_t port_self_size = nla_total_size(sizeof(struct nlattr)) + port_size; if (!dev->netdev_ops->ndo_get_vf_port || !dev->dev.parent || !(ext_filter_mask & RTEXT_FILTER_VF)) return 0; if (dev_num_vf(dev->dev.parent)) return port_self_size + vf_ports_size + vf_port_size * dev_num_vf(dev->dev.parent); else return port_self_size; } static noinline size_t if_nlmsg_size(const struct net_device *dev, u32 ext_filter_mask) { return NLMSG_ALIGN(sizeof(struct ifinfomsg)) + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */ + nla_total_size(IFALIASZ) /* IFLA_IFALIAS */ + nla_total_size(IFNAMSIZ) /* IFLA_QDISC */ + nla_total_size(sizeof(struct rtnl_link_ifmap)) + nla_total_size(sizeof(struct rtnl_link_stats)) + nla_total_size(sizeof(struct rtnl_link_stats64)) + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */ + nla_total_size(MAX_ADDR_LEN) /* IFLA_BROADCAST */ + nla_total_size(4) /* IFLA_TXQLEN */ + nla_total_size(4) /* IFLA_WEIGHT */ + nla_total_size(4) /* IFLA_MTU */ + nla_total_size(4) /* IFLA_LINK */ + nla_total_size(4) /* IFLA_MASTER */ + nla_total_size(1) /* IFLA_CARRIER */ + nla_total_size(4) /* IFLA_PROMISCUITY */ + nla_total_size(4) /* IFLA_NUM_TX_QUEUES */ + nla_total_size(4) /* IFLA_NUM_RX_QUEUES */ + nla_total_size(4) /* IFLA_MAX_GSO_SEGS */ + nla_total_size(4) /* IFLA_MAX_GSO_SIZE */ + nla_total_size(1) /* IFLA_OPERSTATE */ + nla_total_size(1) /* IFLA_LINKMODE */ + nla_total_size(4) /* IFLA_CARRIER_CHANGES */ + nla_total_size(4) /* IFLA_LINK_NETNSID */ + nla_total_size(ext_filter_mask & RTEXT_FILTER_VF ? 4 : 0) /* IFLA_NUM_VF */ + rtnl_vfinfo_size(dev, ext_filter_mask) /* IFLA_VFINFO_LIST */ + rtnl_port_size(dev, ext_filter_mask) /* IFLA_VF_PORTS + IFLA_PORT_SELF */ + rtnl_link_get_size(dev) /* IFLA_LINKINFO */ + rtnl_link_get_af_size(dev, ext_filter_mask) /* IFLA_AF_SPEC */ + nla_total_size(MAX_PHYS_ITEM_ID_LEN) /* IFLA_PHYS_PORT_ID */ + nla_total_size(MAX_PHYS_ITEM_ID_LEN) /* IFLA_PHYS_SWITCH_ID */ + nla_total_size(IFNAMSIZ) /* IFLA_PHYS_PORT_NAME */ + nla_total_size(1); /* IFLA_PROTO_DOWN */ } static int rtnl_vf_ports_fill(struct sk_buff *skb, struct net_device *dev) { struct nlattr *vf_ports; struct nlattr *vf_port; int vf; int err; vf_ports = nla_nest_start(skb, IFLA_VF_PORTS); if (!vf_ports) return -EMSGSIZE; for (vf = 0; vf < dev_num_vf(dev->dev.parent); vf++) { vf_port = nla_nest_start(skb, IFLA_VF_PORT); if (!vf_port) goto nla_put_failure; if (nla_put_u32(skb, IFLA_PORT_VF, vf)) goto nla_put_failure; err = dev->netdev_ops->ndo_get_vf_port(dev, vf, skb); if (err == -EMSGSIZE) goto nla_put_failure; if (err) { nla_nest_cancel(skb, vf_port); continue; } nla_nest_end(skb, vf_port); } nla_nest_end(skb, vf_ports); return 0; nla_put_failure: nla_nest_cancel(skb, vf_ports); return -EMSGSIZE; } static int rtnl_port_self_fill(struct sk_buff *skb, struct net_device *dev) { struct nlattr *port_self; int err; port_self = nla_nest_start(skb, IFLA_PORT_SELF); if (!port_self) return -EMSGSIZE; err = dev->netdev_ops->ndo_get_vf_port(dev, PORT_SELF_VF, skb); if (err) { nla_nest_cancel(skb, port_self); return (err == -EMSGSIZE) ? err : 0; } nla_nest_end(skb, port_self); return 0; } static int rtnl_port_fill(struct sk_buff *skb, struct net_device *dev, u32 ext_filter_mask) { int err; if (!dev->netdev_ops->ndo_get_vf_port || !dev->dev.parent || !(ext_filter_mask & RTEXT_FILTER_VF)) return 0; err = rtnl_port_self_fill(skb, dev); if (err) return err; if (dev_num_vf(dev->dev.parent)) { err = rtnl_vf_ports_fill(skb, dev); if (err) return err; } return 0; } static int rtnl_phys_port_id_fill(struct sk_buff *skb, struct net_device *dev) { int err; struct netdev_phys_item_id ppid; err = dev_get_phys_port_id(dev, &ppid); if (err) { if (err == -EOPNOTSUPP) return 0; return err; } if (nla_put(skb, IFLA_PHYS_PORT_ID, ppid.id_len, ppid.id)) return -EMSGSIZE; return 0; } static int rtnl_phys_port_name_fill(struct sk_buff *skb, struct net_device *dev) { char name[IFNAMSIZ]; int err; err = dev_get_phys_port_name(dev, name, sizeof(name)); if (err) { if (err == -EOPNOTSUPP) return 0; return err; } if (nla_put(skb, IFLA_PHYS_PORT_NAME, strlen(name), name)) return -EMSGSIZE; return 0; } static int rtnl_phys_switch_id_fill(struct sk_buff *skb, struct net_device *dev) { int err; struct switchdev_attr attr = { .orig_dev = dev, .id = SWITCHDEV_ATTR_ID_PORT_PARENT_ID, .flags = SWITCHDEV_F_NO_RECURSE, }; err = switchdev_port_attr_get(dev, &attr); if (err) { if (err == -EOPNOTSUPP) return 0; return err; } if (nla_put(skb, IFLA_PHYS_SWITCH_ID, attr.u.ppid.id_len, attr.u.ppid.id)) return -EMSGSIZE; return 0; } static noinline_for_stack int rtnl_fill_stats(struct sk_buff *skb, struct net_device *dev) { const struct rtnl_link_stats64 *stats; struct rtnl_link_stats64 temp; struct nlattr *attr; stats = dev_get_stats(dev, &temp); attr = nla_reserve(skb, IFLA_STATS, sizeof(struct rtnl_link_stats)); if (!attr) return -EMSGSIZE; copy_rtnl_link_stats(nla_data(attr), stats); attr = nla_reserve(skb, IFLA_STATS64, sizeof(struct rtnl_link_stats64)); if (!attr) return -EMSGSIZE; copy_rtnl_link_stats64(nla_data(attr), stats); return 0; } static noinline_for_stack int rtnl_fill_vfinfo(struct sk_buff *skb, struct net_device *dev, int vfs_num, struct nlattr *vfinfo) { struct ifla_vf_rss_query_en vf_rss_query_en; struct ifla_vf_link_state vf_linkstate; struct ifla_vf_spoofchk vf_spoofchk; struct ifla_vf_tx_rate vf_tx_rate; struct ifla_vf_stats vf_stats; struct ifla_vf_trust vf_trust; struct ifla_vf_vlan vf_vlan; struct ifla_vf_rate vf_rate; struct nlattr *vf, *vfstats; struct ifla_vf_mac vf_mac; struct ifla_vf_info ivi; /* Not all SR-IOV capable drivers support the * spoofcheck and "RSS query enable" query. Preset to * -1 so the user space tool can detect that the driver * didn't report anything. */ ivi.spoofchk = -1; ivi.rss_query_en = -1; ivi.trusted = -1; memset(ivi.mac, 0, sizeof(ivi.mac)); /* The default value for VF link state is "auto" * IFLA_VF_LINK_STATE_AUTO which equals zero */ ivi.linkstate = 0; if (dev->netdev_ops->ndo_get_vf_config(dev, vfs_num, &ivi)) return 0; vf_mac.vf = vf_vlan.vf = vf_rate.vf = vf_tx_rate.vf = vf_spoofchk.vf = vf_linkstate.vf = vf_rss_query_en.vf = vf_trust.vf = ivi.vf; memcpy(vf_mac.mac, ivi.mac, sizeof(ivi.mac)); vf_vlan.vlan = ivi.vlan; vf_vlan.qos = ivi.qos; vf_tx_rate.rate = ivi.max_tx_rate; vf_rate.min_tx_rate = ivi.min_tx_rate; vf_rate.max_tx_rate = ivi.max_tx_rate; vf_spoofchk.setting = ivi.spoofchk; vf_linkstate.link_state = ivi.linkstate; vf_rss_query_en.setting = ivi.rss_query_en; vf_trust.setting = ivi.trusted; vf = nla_nest_start(skb, IFLA_VF_INFO); if (!vf) { nla_nest_cancel(skb, vfinfo); return -EMSGSIZE; } if (nla_put(skb, IFLA_VF_MAC, sizeof(vf_mac), &vf_mac) || nla_put(skb, IFLA_VF_VLAN, sizeof(vf_vlan), &vf_vlan) || nla_put(skb, IFLA_VF_RATE, sizeof(vf_rate), &vf_rate) || nla_put(skb, IFLA_VF_TX_RATE, sizeof(vf_tx_rate), &vf_tx_rate) || nla_put(skb, IFLA_VF_SPOOFCHK, sizeof(vf_spoofchk), &vf_spoofchk) || nla_put(skb, IFLA_VF_LINK_STATE, sizeof(vf_linkstate), &vf_linkstate) || nla_put(skb, IFLA_VF_RSS_QUERY_EN, sizeof(vf_rss_query_en), &vf_rss_query_en) || nla_put(skb, IFLA_VF_TRUST, sizeof(vf_trust), &vf_trust)) return -EMSGSIZE; memset(&vf_stats, 0, sizeof(vf_stats)); if (dev->netdev_ops->ndo_get_vf_stats) dev->netdev_ops->ndo_get_vf_stats(dev, vfs_num, &vf_stats); vfstats = nla_nest_start(skb, IFLA_VF_STATS); if (!vfstats) { nla_nest_cancel(skb, vf); nla_nest_cancel(skb, vfinfo); return -EMSGSIZE; } if (nla_put_u64(skb, IFLA_VF_STATS_RX_PACKETS, vf_stats.rx_packets) || nla_put_u64(skb, IFLA_VF_STATS_TX_PACKETS, vf_stats.tx_packets) || nla_put_u64(skb, IFLA_VF_STATS_RX_BYTES, vf_stats.rx_bytes) || nla_put_u64(skb, IFLA_VF_STATS_TX_BYTES, vf_stats.tx_bytes) || nla_put_u64(skb, IFLA_VF_STATS_BROADCAST, vf_stats.broadcast) || nla_put_u64(skb, IFLA_VF_STATS_MULTICAST, vf_stats.multicast)) return -EMSGSIZE; nla_nest_end(skb, vfstats); nla_nest_end(skb, vf); return 0; } static int rtnl_fill_link_ifmap(struct sk_buff *skb, struct net_device *dev) { struct rtnl_link_ifmap map = { .mem_start = dev->mem_start, .mem_end = dev->mem_end, .base_addr = dev->base_addr, .irq = dev->irq, .dma = dev->dma, .port = dev->if_port, }; if (nla_put(skb, IFLA_MAP, sizeof(map), &map)) return -EMSGSIZE; return 0; } static int rtnl_fill_ifinfo(struct sk_buff *skb, struct net_device *dev, int type, u32 pid, u32 seq, u32 change, unsigned int flags, u32 ext_filter_mask) { struct ifinfomsg *ifm; struct nlmsghdr *nlh; struct nlattr *af_spec; struct rtnl_af_ops *af_ops; struct net_device *upper_dev = netdev_master_upper_dev_get(dev); ASSERT_RTNL(); nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ifm), flags); if (nlh == NULL) return -EMSGSIZE; ifm = nlmsg_data(nlh); ifm->ifi_family = AF_UNSPEC; ifm->__ifi_pad = 0; ifm->ifi_type = dev->type; ifm->ifi_index = dev->ifindex; ifm->ifi_flags = dev_get_flags(dev); ifm->ifi_change = change; if (nla_put_string(skb, IFLA_IFNAME, dev->name) || nla_put_u32(skb, IFLA_TXQLEN, dev->tx_queue_len) || nla_put_u8(skb, IFLA_OPERSTATE, netif_running(dev) ? dev->operstate : IF_OPER_DOWN) || nla_put_u8(skb, IFLA_LINKMODE, dev->link_mode) || nla_put_u32(skb, IFLA_MTU, dev->mtu) || nla_put_u32(skb, IFLA_GROUP, dev->group) || nla_put_u32(skb, IFLA_PROMISCUITY, dev->promiscuity) || nla_put_u32(skb, IFLA_NUM_TX_QUEUES, dev->num_tx_queues) || nla_put_u32(skb, IFLA_GSO_MAX_SEGS, dev->gso_max_segs) || nla_put_u32(skb, IFLA_GSO_MAX_SIZE, dev->gso_max_size) || #ifdef CONFIG_RPS nla_put_u32(skb, IFLA_NUM_RX_QUEUES, dev->num_rx_queues) || #endif (dev->ifindex != dev_get_iflink(dev) && nla_put_u32(skb, IFLA_LINK, dev_get_iflink(dev))) || (upper_dev && nla_put_u32(skb, IFLA_MASTER, upper_dev->ifindex)) || nla_put_u8(skb, IFLA_CARRIER, netif_carrier_ok(dev)) || (dev->qdisc && nla_put_string(skb, IFLA_QDISC, dev->qdisc->ops->id)) || (dev->ifalias && nla_put_string(skb, IFLA_IFALIAS, dev->ifalias)) || nla_put_u32(skb, IFLA_CARRIER_CHANGES, atomic_read(&dev->carrier_changes)) || nla_put_u8(skb, IFLA_PROTO_DOWN, dev->proto_down)) goto nla_put_failure; if (rtnl_fill_link_ifmap(skb, dev)) goto nla_put_failure; if (dev->addr_len) { if (nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr) || nla_put(skb, IFLA_BROADCAST, dev->addr_len, dev->broadcast)) goto nla_put_failure; } if (rtnl_phys_port_id_fill(skb, dev)) goto nla_put_failure; if (rtnl_phys_port_name_fill(skb, dev)) goto nla_put_failure; if (rtnl_phys_switch_id_fill(skb, dev)) goto nla_put_failure; if (rtnl_fill_stats(skb, dev)) goto nla_put_failure; if (dev->dev.parent && (ext_filter_mask & RTEXT_FILTER_VF) && nla_put_u32(skb, IFLA_NUM_VF, dev_num_vf(dev->dev.parent))) goto nla_put_failure; if (dev->netdev_ops->ndo_get_vf_config && dev->dev.parent && ext_filter_mask & RTEXT_FILTER_VF) { int i; struct nlattr *vfinfo; int num_vfs = dev_num_vf(dev->dev.parent); vfinfo = nla_nest_start(skb, IFLA_VFINFO_LIST); if (!vfinfo) goto nla_put_failure; for (i = 0; i < num_vfs; i++) { if (rtnl_fill_vfinfo(skb, dev, i, vfinfo)) goto nla_put_failure; } nla_nest_end(skb, vfinfo); } if (rtnl_port_fill(skb, dev, ext_filter_mask)) goto nla_put_failure; if (dev->rtnl_link_ops || rtnl_have_link_slave_info(dev)) { if (rtnl_link_fill(skb, dev) < 0) goto nla_put_failure; } if (dev->rtnl_link_ops && dev->rtnl_link_ops->get_link_net) { struct net *link_net = dev->rtnl_link_ops->get_link_net(dev); if (!net_eq(dev_net(dev), link_net)) { int id = peernet2id_alloc(dev_net(dev), link_net); if (nla_put_s32(skb, IFLA_LINK_NETNSID, id)) goto nla_put_failure; } } if (!(af_spec = nla_nest_start(skb, IFLA_AF_SPEC))) goto nla_put_failure; list_for_each_entry(af_ops, &rtnl_af_ops, list) { if (af_ops->fill_link_af) { struct nlattr *af; int err; if (!(af = nla_nest_start(skb, af_ops->family))) goto nla_put_failure; err = af_ops->fill_link_af(skb, dev, ext_filter_mask); /* * Caller may return ENODATA to indicate that there * was no data to be dumped. This is not an error, it * means we should trim the attribute header and * continue. */ if (err == -ENODATA) nla_nest_cancel(skb, af); else if (err < 0) goto nla_put_failure; nla_nest_end(skb, af); } } nla_nest_end(skb, af_spec); nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static const struct nla_policy ifla_policy[IFLA_MAX+1] = { [IFLA_IFNAME] = { .type = NLA_STRING, .len = IFNAMSIZ-1 }, [IFLA_ADDRESS] = { .type = NLA_BINARY, .len = MAX_ADDR_LEN }, [IFLA_BROADCAST] = { .type = NLA_BINARY, .len = MAX_ADDR_LEN }, [IFLA_MAP] = { .len = sizeof(struct rtnl_link_ifmap) }, [IFLA_MTU] = { .type = NLA_U32 }, [IFLA_LINK] = { .type = NLA_U32 }, [IFLA_MASTER] = { .type = NLA_U32 }, [IFLA_CARRIER] = { .type = NLA_U8 }, [IFLA_TXQLEN] = { .type = NLA_U32 }, [IFLA_WEIGHT] = { .type = NLA_U32 }, [IFLA_OPERSTATE] = { .type = NLA_U8 }, [IFLA_LINKMODE] = { .type = NLA_U8 }, [IFLA_LINKINFO] = { .type = NLA_NESTED }, [IFLA_NET_NS_PID] = { .type = NLA_U32 }, [IFLA_NET_NS_FD] = { .type = NLA_U32 }, [IFLA_IFALIAS] = { .type = NLA_STRING, .len = IFALIASZ-1 }, [IFLA_VFINFO_LIST] = {. type = NLA_NESTED }, [IFLA_VF_PORTS] = { .type = NLA_NESTED }, [IFLA_PORT_SELF] = { .type = NLA_NESTED }, [IFLA_AF_SPEC] = { .type = NLA_NESTED }, [IFLA_EXT_MASK] = { .type = NLA_U32 }, [IFLA_PROMISCUITY] = { .type = NLA_U32 }, [IFLA_NUM_TX_QUEUES] = { .type = NLA_U32 }, [IFLA_NUM_RX_QUEUES] = { .type = NLA_U32 }, [IFLA_PHYS_PORT_ID] = { .type = NLA_BINARY, .len = MAX_PHYS_ITEM_ID_LEN }, [IFLA_CARRIER_CHANGES] = { .type = NLA_U32 }, /* ignored */ [IFLA_PHYS_SWITCH_ID] = { .type = NLA_BINARY, .len = MAX_PHYS_ITEM_ID_LEN }, [IFLA_LINK_NETNSID] = { .type = NLA_S32 }, [IFLA_PROTO_DOWN] = { .type = NLA_U8 }, }; static const struct nla_policy ifla_info_policy[IFLA_INFO_MAX+1] = { [IFLA_INFO_KIND] = { .type = NLA_STRING }, [IFLA_INFO_DATA] = { .type = NLA_NESTED }, [IFLA_INFO_SLAVE_KIND] = { .type = NLA_STRING }, [IFLA_INFO_SLAVE_DATA] = { .type = NLA_NESTED }, }; static const struct nla_policy ifla_vf_policy[IFLA_VF_MAX+1] = { [IFLA_VF_MAC] = { .len = sizeof(struct ifla_vf_mac) }, [IFLA_VF_VLAN] = { .len = sizeof(struct ifla_vf_vlan) }, [IFLA_VF_TX_RATE] = { .len = sizeof(struct ifla_vf_tx_rate) }, [IFLA_VF_SPOOFCHK] = { .len = sizeof(struct ifla_vf_spoofchk) }, [IFLA_VF_RATE] = { .len = sizeof(struct ifla_vf_rate) }, [IFLA_VF_LINK_STATE] = { .len = sizeof(struct ifla_vf_link_state) }, [IFLA_VF_RSS_QUERY_EN] = { .len = sizeof(struct ifla_vf_rss_query_en) }, [IFLA_VF_STATS] = { .type = NLA_NESTED }, [IFLA_VF_TRUST] = { .len = sizeof(struct ifla_vf_trust) }, [IFLA_VF_IB_NODE_GUID] = { .len = sizeof(struct ifla_vf_guid) }, [IFLA_VF_IB_PORT_GUID] = { .len = sizeof(struct ifla_vf_guid) }, }; static const struct nla_policy ifla_port_policy[IFLA_PORT_MAX+1] = { [IFLA_PORT_VF] = { .type = NLA_U32 }, [IFLA_PORT_PROFILE] = { .type = NLA_STRING, .len = PORT_PROFILE_MAX }, [IFLA_PORT_VSI_TYPE] = { .type = NLA_BINARY, .len = sizeof(struct ifla_port_vsi)}, [IFLA_PORT_INSTANCE_UUID] = { .type = NLA_BINARY, .len = PORT_UUID_MAX }, [IFLA_PORT_HOST_UUID] = { .type = NLA_STRING, .len = PORT_UUID_MAX }, [IFLA_PORT_REQUEST] = { .type = NLA_U8, }, [IFLA_PORT_RESPONSE] = { .type = NLA_U16, }, }; static const struct rtnl_link_ops *linkinfo_to_kind_ops(const struct nlattr *nla) { const struct rtnl_link_ops *ops = NULL; struct nlattr *linfo[IFLA_INFO_MAX + 1]; if (nla_parse_nested(linfo, IFLA_INFO_MAX, nla, ifla_info_policy) < 0) return NULL; if (linfo[IFLA_INFO_KIND]) { char kind[MODULE_NAME_LEN]; nla_strlcpy(kind, linfo[IFLA_INFO_KIND], sizeof(kind)); ops = rtnl_link_ops_get(kind); } return ops; } static bool link_master_filtered(struct net_device *dev, int master_idx) { struct net_device *master; if (!master_idx) return false; master = netdev_master_upper_dev_get(dev); if (!master || master->ifindex != master_idx) return true; return false; } static bool link_kind_filtered(const struct net_device *dev, const struct rtnl_link_ops *kind_ops) { if (kind_ops && dev->rtnl_link_ops != kind_ops) return true; return false; } static bool link_dump_filtered(struct net_device *dev, int master_idx, const struct rtnl_link_ops *kind_ops) { if (link_master_filtered(dev, master_idx) || link_kind_filtered(dev, kind_ops)) return true; return false; } static int rtnl_dump_ifinfo(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); int h, s_h; int idx = 0, s_idx; struct net_device *dev; struct hlist_head *head; struct nlattr *tb[IFLA_MAX+1]; u32 ext_filter_mask = 0; const struct rtnl_link_ops *kind_ops = NULL; unsigned int flags = NLM_F_MULTI; int master_idx = 0; int err; int hdrlen; s_h = cb->args[0]; s_idx = cb->args[1]; cb->seq = net->dev_base_seq; /* A hack to preserve kernel<->userspace interface. * The correct header is ifinfomsg. It is consistent with rtnl_getlink. * However, before Linux v3.9 the code here assumed rtgenmsg and that's * what iproute2 < v3.9.0 used. * We can detect the old iproute2. Even including the IFLA_EXT_MASK * attribute, its netlink message is shorter than struct ifinfomsg. */ hdrlen = nlmsg_len(cb->nlh) < sizeof(struct ifinfomsg) ? sizeof(struct rtgenmsg) : sizeof(struct ifinfomsg); if (nlmsg_parse(cb->nlh, hdrlen, tb, IFLA_MAX, ifla_policy) >= 0) { if (tb[IFLA_EXT_MASK]) ext_filter_mask = nla_get_u32(tb[IFLA_EXT_MASK]); if (tb[IFLA_MASTER]) master_idx = nla_get_u32(tb[IFLA_MASTER]); if (tb[IFLA_LINKINFO]) kind_ops = linkinfo_to_kind_ops(tb[IFLA_LINKINFO]); if (master_idx || kind_ops) flags |= NLM_F_DUMP_FILTERED; } for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) { idx = 0; head = &net->dev_index_head[h]; hlist_for_each_entry(dev, head, index_hlist) { if (link_dump_filtered(dev, master_idx, kind_ops)) continue; if (idx < s_idx) goto cont; err = rtnl_fill_ifinfo(skb, dev, RTM_NEWLINK, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq, 0, flags, ext_filter_mask); /* If we ran out of room on the first message, * we're in trouble */ WARN_ON((err == -EMSGSIZE) && (skb->len == 0)); if (err < 0) goto out; nl_dump_check_consistent(cb, nlmsg_hdr(skb)); cont: idx++; } } out: cb->args[1] = idx; cb->args[0] = h; return skb->len; } int rtnl_nla_parse_ifla(struct nlattr **tb, const struct nlattr *head, int len) { return nla_parse(tb, IFLA_MAX, head, len, ifla_policy); } EXPORT_SYMBOL(rtnl_nla_parse_ifla); struct net *rtnl_link_get_net(struct net *src_net, struct nlattr *tb[]) { struct net *net; /* Examine the link attributes and figure out which * network namespace we are talking about. */ if (tb[IFLA_NET_NS_PID]) net = get_net_ns_by_pid(nla_get_u32(tb[IFLA_NET_NS_PID])); else if (tb[IFLA_NET_NS_FD]) net = get_net_ns_by_fd(nla_get_u32(tb[IFLA_NET_NS_FD])); else net = get_net(src_net); return net; } EXPORT_SYMBOL(rtnl_link_get_net); static int validate_linkmsg(struct net_device *dev, struct nlattr *tb[]) { if (dev) { if (tb[IFLA_ADDRESS] && nla_len(tb[IFLA_ADDRESS]) < dev->addr_len) return -EINVAL; if (tb[IFLA_BROADCAST] && nla_len(tb[IFLA_BROADCAST]) < dev->addr_len) return -EINVAL; } if (tb[IFLA_AF_SPEC]) { struct nlattr *af; int rem, err; nla_for_each_nested(af, tb[IFLA_AF_SPEC], rem) { const struct rtnl_af_ops *af_ops; if (!(af_ops = rtnl_af_lookup(nla_type(af)))) return -EAFNOSUPPORT; if (!af_ops->set_link_af) return -EOPNOTSUPP; if (af_ops->validate_link_af) { err = af_ops->validate_link_af(dev, af); if (err < 0) return err; } } } return 0; } static int handle_infiniband_guid(struct net_device *dev, struct ifla_vf_guid *ivt, int guid_type) { const struct net_device_ops *ops = dev->netdev_ops; return ops->ndo_set_vf_guid(dev, ivt->vf, ivt->guid, guid_type); } static int handle_vf_guid(struct net_device *dev, struct ifla_vf_guid *ivt, int guid_type) { if (dev->type != ARPHRD_INFINIBAND) return -EOPNOTSUPP; return handle_infiniband_guid(dev, ivt, guid_type); } static int do_setvfinfo(struct net_device *dev, struct nlattr **tb) { const struct net_device_ops *ops = dev->netdev_ops; int err = -EINVAL; if (tb[IFLA_VF_MAC]) { struct ifla_vf_mac *ivm = nla_data(tb[IFLA_VF_MAC]); err = -EOPNOTSUPP; if (ops->ndo_set_vf_mac) err = ops->ndo_set_vf_mac(dev, ivm->vf, ivm->mac); if (err < 0) return err; } if (tb[IFLA_VF_VLAN]) { struct ifla_vf_vlan *ivv = nla_data(tb[IFLA_VF_VLAN]); err = -EOPNOTSUPP; if (ops->ndo_set_vf_vlan) err = ops->ndo_set_vf_vlan(dev, ivv->vf, ivv->vlan, ivv->qos); if (err < 0) return err; } if (tb[IFLA_VF_TX_RATE]) { struct ifla_vf_tx_rate *ivt = nla_data(tb[IFLA_VF_TX_RATE]); struct ifla_vf_info ivf; err = -EOPNOTSUPP; if (ops->ndo_get_vf_config) err = ops->ndo_get_vf_config(dev, ivt->vf, &ivf); if (err < 0) return err; err = -EOPNOTSUPP; if (ops->ndo_set_vf_rate) err = ops->ndo_set_vf_rate(dev, ivt->vf, ivf.min_tx_rate, ivt->rate); if (err < 0) return err; } if (tb[IFLA_VF_RATE]) { struct ifla_vf_rate *ivt = nla_data(tb[IFLA_VF_RATE]); err = -EOPNOTSUPP; if (ops->ndo_set_vf_rate) err = ops->ndo_set_vf_rate(dev, ivt->vf, ivt->min_tx_rate, ivt->max_tx_rate); if (err < 0) return err; } if (tb[IFLA_VF_SPOOFCHK]) { struct ifla_vf_spoofchk *ivs = nla_data(tb[IFLA_VF_SPOOFCHK]); err = -EOPNOTSUPP; if (ops->ndo_set_vf_spoofchk) err = ops->ndo_set_vf_spoofchk(dev, ivs->vf, ivs->setting); if (err < 0) return err; } if (tb[IFLA_VF_LINK_STATE]) { struct ifla_vf_link_state *ivl = nla_data(tb[IFLA_VF_LINK_STATE]); err = -EOPNOTSUPP; if (ops->ndo_set_vf_link_state) err = ops->ndo_set_vf_link_state(dev, ivl->vf, ivl->link_state); if (err < 0) return err; } if (tb[IFLA_VF_RSS_QUERY_EN]) { struct ifla_vf_rss_query_en *ivrssq_en; err = -EOPNOTSUPP; ivrssq_en = nla_data(tb[IFLA_VF_RSS_QUERY_EN]); if (ops->ndo_set_vf_rss_query_en) err = ops->ndo_set_vf_rss_query_en(dev, ivrssq_en->vf, ivrssq_en->setting); if (err < 0) return err; } if (tb[IFLA_VF_TRUST]) { struct ifla_vf_trust *ivt = nla_data(tb[IFLA_VF_TRUST]); err = -EOPNOTSUPP; if (ops->ndo_set_vf_trust) err = ops->ndo_set_vf_trust(dev, ivt->vf, ivt->setting); if (err < 0) return err; } if (tb[IFLA_VF_IB_NODE_GUID]) { struct ifla_vf_guid *ivt = nla_data(tb[IFLA_VF_IB_NODE_GUID]); if (!ops->ndo_set_vf_guid) return -EOPNOTSUPP; return handle_vf_guid(dev, ivt, IFLA_VF_IB_NODE_GUID); } if (tb[IFLA_VF_IB_PORT_GUID]) { struct ifla_vf_guid *ivt = nla_data(tb[IFLA_VF_IB_PORT_GUID]); if (!ops->ndo_set_vf_guid) return -EOPNOTSUPP; return handle_vf_guid(dev, ivt, IFLA_VF_IB_PORT_GUID); } return err; } static int do_set_master(struct net_device *dev, int ifindex) { struct net_device *upper_dev = netdev_master_upper_dev_get(dev); const struct net_device_ops *ops; int err; if (upper_dev) { if (upper_dev->ifindex == ifindex) return 0; ops = upper_dev->netdev_ops; if (ops->ndo_del_slave) { err = ops->ndo_del_slave(upper_dev, dev); if (err) return err; } else { return -EOPNOTSUPP; } } if (ifindex) { upper_dev = __dev_get_by_index(dev_net(dev), ifindex); if (!upper_dev) return -EINVAL; ops = upper_dev->netdev_ops; if (ops->ndo_add_slave) { err = ops->ndo_add_slave(upper_dev, dev); if (err) return err; } else { return -EOPNOTSUPP; } } return 0; } #define DO_SETLINK_MODIFIED 0x01 /* notify flag means notify + modified. */ #define DO_SETLINK_NOTIFY 0x03 static int do_setlink(const struct sk_buff *skb, struct net_device *dev, struct ifinfomsg *ifm, struct nlattr **tb, char *ifname, int status) { const struct net_device_ops *ops = dev->netdev_ops; int err; if (tb[IFLA_NET_NS_PID] || tb[IFLA_NET_NS_FD]) { struct net *net = rtnl_link_get_net(dev_net(dev), tb); if (IS_ERR(net)) { err = PTR_ERR(net); goto errout; } if (!netlink_ns_capable(skb, net->user_ns, CAP_NET_ADMIN)) { put_net(net); err = -EPERM; goto errout; } err = dev_change_net_namespace(dev, net, ifname); put_net(net); if (err) goto errout; status |= DO_SETLINK_MODIFIED; } if (tb[IFLA_MAP]) { struct rtnl_link_ifmap *u_map; struct ifmap k_map; if (!ops->ndo_set_config) { err = -EOPNOTSUPP; goto errout; } if (!netif_device_present(dev)) { err = -ENODEV; goto errout; } u_map = nla_data(tb[IFLA_MAP]); k_map.mem_start = (unsigned long) u_map->mem_start; k_map.mem_end = (unsigned long) u_map->mem_end; k_map.base_addr = (unsigned short) u_map->base_addr; k_map.irq = (unsigned char) u_map->irq; k_map.dma = (unsigned char) u_map->dma; k_map.port = (unsigned char) u_map->port; err = ops->ndo_set_config(dev, &k_map); if (err < 0) goto errout; status |= DO_SETLINK_NOTIFY; } if (tb[IFLA_ADDRESS]) { struct sockaddr *sa; int len; len = sizeof(sa_family_t) + dev->addr_len; sa = kmalloc(len, GFP_KERNEL); if (!sa) { err = -ENOMEM; goto errout; } sa->sa_family = dev->type; memcpy(sa->sa_data, nla_data(tb[IFLA_ADDRESS]), dev->addr_len); err = dev_set_mac_address(dev, sa); kfree(sa); if (err) goto errout; status |= DO_SETLINK_MODIFIED; } if (tb[IFLA_MTU]) { err = dev_set_mtu(dev, nla_get_u32(tb[IFLA_MTU])); if (err < 0) goto errout; status |= DO_SETLINK_MODIFIED; } if (tb[IFLA_GROUP]) { dev_set_group(dev, nla_get_u32(tb[IFLA_GROUP])); status |= DO_SETLINK_NOTIFY; } /* * Interface selected by interface index but interface * name provided implies that a name change has been * requested. */ if (ifm->ifi_index > 0 && ifname[0]) { err = dev_change_name(dev, ifname); if (err < 0) goto errout; status |= DO_SETLINK_MODIFIED; } if (tb[IFLA_IFALIAS]) { err = dev_set_alias(dev, nla_data(tb[IFLA_IFALIAS]), nla_len(tb[IFLA_IFALIAS])); if (err < 0) goto errout; status |= DO_SETLINK_NOTIFY; } if (tb[IFLA_BROADCAST]) { nla_memcpy(dev->broadcast, tb[IFLA_BROADCAST], dev->addr_len); call_netdevice_notifiers(NETDEV_CHANGEADDR, dev); } if (ifm->ifi_flags || ifm->ifi_change) { err = dev_change_flags(dev, rtnl_dev_combine_flags(dev, ifm)); if (err < 0) goto errout; } if (tb[IFLA_MASTER]) { err = do_set_master(dev, nla_get_u32(tb[IFLA_MASTER])); if (err) goto errout; status |= DO_SETLINK_MODIFIED; } if (tb[IFLA_CARRIER]) { err = dev_change_carrier(dev, nla_get_u8(tb[IFLA_CARRIER])); if (err) goto errout; status |= DO_SETLINK_MODIFIED; } if (tb[IFLA_TXQLEN]) { unsigned long value = nla_get_u32(tb[IFLA_TXQLEN]); if (dev->tx_queue_len ^ value) status |= DO_SETLINK_NOTIFY; dev->tx_queue_len = value; } if (tb[IFLA_OPERSTATE]) set_operstate(dev, nla_get_u8(tb[IFLA_OPERSTATE])); if (tb[IFLA_LINKMODE]) { unsigned char value = nla_get_u8(tb[IFLA_LINKMODE]); write_lock_bh(&dev_base_lock); if (dev->link_mode ^ value) status |= DO_SETLINK_NOTIFY; dev->link_mode = value; write_unlock_bh(&dev_base_lock); } if (tb[IFLA_VFINFO_LIST]) { struct nlattr *vfinfo[IFLA_VF_MAX + 1]; struct nlattr *attr; int rem; nla_for_each_nested(attr, tb[IFLA_VFINFO_LIST], rem) { if (nla_type(attr) != IFLA_VF_INFO || nla_len(attr) < NLA_HDRLEN) { err = -EINVAL; goto errout; } err = nla_parse_nested(vfinfo, IFLA_VF_MAX, attr, ifla_vf_policy); if (err < 0) goto errout; err = do_setvfinfo(dev, vfinfo); if (err < 0) goto errout; status |= DO_SETLINK_NOTIFY; } } err = 0; if (tb[IFLA_VF_PORTS]) { struct nlattr *port[IFLA_PORT_MAX+1]; struct nlattr *attr; int vf; int rem; err = -EOPNOTSUPP; if (!ops->ndo_set_vf_port) goto errout; nla_for_each_nested(attr, tb[IFLA_VF_PORTS], rem) { if (nla_type(attr) != IFLA_VF_PORT || nla_len(attr) < NLA_HDRLEN) { err = -EINVAL; goto errout; } err = nla_parse_nested(port, IFLA_PORT_MAX, attr, ifla_port_policy); if (err < 0) goto errout; if (!port[IFLA_PORT_VF]) { err = -EOPNOTSUPP; goto errout; } vf = nla_get_u32(port[IFLA_PORT_VF]); err = ops->ndo_set_vf_port(dev, vf, port); if (err < 0) goto errout; status |= DO_SETLINK_NOTIFY; } } err = 0; if (tb[IFLA_PORT_SELF]) { struct nlattr *port[IFLA_PORT_MAX+1]; err = nla_parse_nested(port, IFLA_PORT_MAX, tb[IFLA_PORT_SELF], ifla_port_policy); if (err < 0) goto errout; err = -EOPNOTSUPP; if (ops->ndo_set_vf_port) err = ops->ndo_set_vf_port(dev, PORT_SELF_VF, port); if (err < 0) goto errout; status |= DO_SETLINK_NOTIFY; } if (tb[IFLA_AF_SPEC]) { struct nlattr *af; int rem; nla_for_each_nested(af, tb[IFLA_AF_SPEC], rem) { const struct rtnl_af_ops *af_ops; if (!(af_ops = rtnl_af_lookup(nla_type(af)))) BUG(); err = af_ops->set_link_af(dev, af); if (err < 0) goto errout; status |= DO_SETLINK_NOTIFY; } } err = 0; if (tb[IFLA_PROTO_DOWN]) { err = dev_change_proto_down(dev, nla_get_u8(tb[IFLA_PROTO_DOWN])); if (err) goto errout; status |= DO_SETLINK_NOTIFY; } errout: if (status & DO_SETLINK_MODIFIED) { if (status & DO_SETLINK_NOTIFY) netdev_state_change(dev); if (err < 0) net_warn_ratelimited("A link change request failed with some changes committed already. Interface %s may have been left with an inconsistent configuration, please check.\n", dev->name); } return err; } static int rtnl_setlink(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct ifinfomsg *ifm; struct net_device *dev; int err; struct nlattr *tb[IFLA_MAX+1]; char ifname[IFNAMSIZ]; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy); if (err < 0) goto errout; if (tb[IFLA_IFNAME]) nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ); else ifname[0] = '\0'; err = -EINVAL; ifm = nlmsg_data(nlh); if (ifm->ifi_index > 0) dev = __dev_get_by_index(net, ifm->ifi_index); else if (tb[IFLA_IFNAME]) dev = __dev_get_by_name(net, ifname); else goto errout; if (dev == NULL) { err = -ENODEV; goto errout; } err = validate_linkmsg(dev, tb); if (err < 0) goto errout; err = do_setlink(skb, dev, ifm, tb, ifname, 0); errout: return err; } static int rtnl_group_dellink(const struct net *net, int group) { struct net_device *dev, *aux; LIST_HEAD(list_kill); bool found = false; if (!group) return -EPERM; for_each_netdev(net, dev) { if (dev->group == group) { const struct rtnl_link_ops *ops; found = true; ops = dev->rtnl_link_ops; if (!ops || !ops->dellink) return -EOPNOTSUPP; } } if (!found) return -ENODEV; for_each_netdev_safe(net, dev, aux) { if (dev->group == group) { const struct rtnl_link_ops *ops; ops = dev->rtnl_link_ops; ops->dellink(dev, &list_kill); } } unregister_netdevice_many(&list_kill); return 0; } int rtnl_delete_link(struct net_device *dev) { const struct rtnl_link_ops *ops; LIST_HEAD(list_kill); ops = dev->rtnl_link_ops; if (!ops || !ops->dellink) return -EOPNOTSUPP; ops->dellink(dev, &list_kill); unregister_netdevice_many(&list_kill); return 0; } EXPORT_SYMBOL_GPL(rtnl_delete_link); static int rtnl_dellink(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct net_device *dev; struct ifinfomsg *ifm; char ifname[IFNAMSIZ]; struct nlattr *tb[IFLA_MAX+1]; int err; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy); if (err < 0) return err; if (tb[IFLA_IFNAME]) nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ); ifm = nlmsg_data(nlh); if (ifm->ifi_index > 0) dev = __dev_get_by_index(net, ifm->ifi_index); else if (tb[IFLA_IFNAME]) dev = __dev_get_by_name(net, ifname); else if (tb[IFLA_GROUP]) return rtnl_group_dellink(net, nla_get_u32(tb[IFLA_GROUP])); else return -EINVAL; if (!dev) return -ENODEV; return rtnl_delete_link(dev); } int rtnl_configure_link(struct net_device *dev, const struct ifinfomsg *ifm) { unsigned int old_flags; int err; old_flags = dev->flags; if (ifm && (ifm->ifi_flags || ifm->ifi_change)) { err = __dev_change_flags(dev, rtnl_dev_combine_flags(dev, ifm)); if (err < 0) return err; } dev->rtnl_link_state = RTNL_LINK_INITIALIZED; __dev_notify_flags(dev, old_flags, ~0U); return 0; } EXPORT_SYMBOL(rtnl_configure_link); struct net_device *rtnl_create_link(struct net *net, const char *ifname, unsigned char name_assign_type, const struct rtnl_link_ops *ops, struct nlattr *tb[]) { int err; struct net_device *dev; unsigned int num_tx_queues = 1; unsigned int num_rx_queues = 1; if (tb[IFLA_NUM_TX_QUEUES]) num_tx_queues = nla_get_u32(tb[IFLA_NUM_TX_QUEUES]); else if (ops->get_num_tx_queues) num_tx_queues = ops->get_num_tx_queues(); if (tb[IFLA_NUM_RX_QUEUES]) num_rx_queues = nla_get_u32(tb[IFLA_NUM_RX_QUEUES]); else if (ops->get_num_rx_queues) num_rx_queues = ops->get_num_rx_queues(); err = -ENOMEM; dev = alloc_netdev_mqs(ops->priv_size, ifname, name_assign_type, ops->setup, num_tx_queues, num_rx_queues); if (!dev) goto err; dev_net_set(dev, net); dev->rtnl_link_ops = ops; dev->rtnl_link_state = RTNL_LINK_INITIALIZING; if (tb[IFLA_MTU]) dev->mtu = nla_get_u32(tb[IFLA_MTU]); if (tb[IFLA_ADDRESS]) { memcpy(dev->dev_addr, nla_data(tb[IFLA_ADDRESS]), nla_len(tb[IFLA_ADDRESS])); dev->addr_assign_type = NET_ADDR_SET; } if (tb[IFLA_BROADCAST]) memcpy(dev->broadcast, nla_data(tb[IFLA_BROADCAST]), nla_len(tb[IFLA_BROADCAST])); if (tb[IFLA_TXQLEN]) dev->tx_queue_len = nla_get_u32(tb[IFLA_TXQLEN]); if (tb[IFLA_OPERSTATE]) set_operstate(dev, nla_get_u8(tb[IFLA_OPERSTATE])); if (tb[IFLA_LINKMODE]) dev->link_mode = nla_get_u8(tb[IFLA_LINKMODE]); if (tb[IFLA_GROUP]) dev_set_group(dev, nla_get_u32(tb[IFLA_GROUP])); return dev; err: return ERR_PTR(err); } EXPORT_SYMBOL(rtnl_create_link); static int rtnl_group_changelink(const struct sk_buff *skb, struct net *net, int group, struct ifinfomsg *ifm, struct nlattr **tb) { struct net_device *dev, *aux; int err; for_each_netdev_safe(net, dev, aux) { if (dev->group == group) { err = do_setlink(skb, dev, ifm, tb, NULL, 0); if (err < 0) return err; } } return 0; } static int rtnl_newlink(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); const struct rtnl_link_ops *ops; const struct rtnl_link_ops *m_ops = NULL; struct net_device *dev; struct net_device *master_dev = NULL; struct ifinfomsg *ifm; char kind[MODULE_NAME_LEN]; char ifname[IFNAMSIZ]; struct nlattr *tb[IFLA_MAX+1]; struct nlattr *linkinfo[IFLA_INFO_MAX+1]; unsigned char name_assign_type = NET_NAME_USER; int err; #ifdef CONFIG_MODULES replay: #endif err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy); if (err < 0) return err; if (tb[IFLA_IFNAME]) nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ); else ifname[0] = '\0'; ifm = nlmsg_data(nlh); if (ifm->ifi_index > 0) dev = __dev_get_by_index(net, ifm->ifi_index); else { if (ifname[0]) dev = __dev_get_by_name(net, ifname); else dev = NULL; } if (dev) { master_dev = netdev_master_upper_dev_get(dev); if (master_dev) m_ops = master_dev->rtnl_link_ops; } err = validate_linkmsg(dev, tb); if (err < 0) return err; if (tb[IFLA_LINKINFO]) { err = nla_parse_nested(linkinfo, IFLA_INFO_MAX, tb[IFLA_LINKINFO], ifla_info_policy); if (err < 0) return err; } else memset(linkinfo, 0, sizeof(linkinfo)); if (linkinfo[IFLA_INFO_KIND]) { nla_strlcpy(kind, linkinfo[IFLA_INFO_KIND], sizeof(kind)); ops = rtnl_link_ops_get(kind); } else { kind[0] = '\0'; ops = NULL; } if (1) { struct nlattr *attr[ops ? ops->maxtype + 1 : 1]; struct nlattr *slave_attr[m_ops ? m_ops->slave_maxtype + 1 : 1]; struct nlattr **data = NULL; struct nlattr **slave_data = NULL; struct net *dest_net, *link_net = NULL; if (ops) { if (ops->maxtype && linkinfo[IFLA_INFO_DATA]) { err = nla_parse_nested(attr, ops->maxtype, linkinfo[IFLA_INFO_DATA], ops->policy); if (err < 0) return err; data = attr; } if (ops->validate) { err = ops->validate(tb, data); if (err < 0) return err; } } if (m_ops) { if (m_ops->slave_maxtype && linkinfo[IFLA_INFO_SLAVE_DATA]) { err = nla_parse_nested(slave_attr, m_ops->slave_maxtype, linkinfo[IFLA_INFO_SLAVE_DATA], m_ops->slave_policy); if (err < 0) return err; slave_data = slave_attr; } if (m_ops->slave_validate) { err = m_ops->slave_validate(tb, slave_data); if (err < 0) return err; } } if (dev) { int status = 0; if (nlh->nlmsg_flags & NLM_F_EXCL) return -EEXIST; if (nlh->nlmsg_flags & NLM_F_REPLACE) return -EOPNOTSUPP; if (linkinfo[IFLA_INFO_DATA]) { if (!ops || ops != dev->rtnl_link_ops || !ops->changelink) return -EOPNOTSUPP; err = ops->changelink(dev, tb, data); if (err < 0) return err; status |= DO_SETLINK_NOTIFY; } if (linkinfo[IFLA_INFO_SLAVE_DATA]) { if (!m_ops || !m_ops->slave_changelink) return -EOPNOTSUPP; err = m_ops->slave_changelink(master_dev, dev, tb, slave_data); if (err < 0) return err; status |= DO_SETLINK_NOTIFY; } return do_setlink(skb, dev, ifm, tb, ifname, status); } if (!(nlh->nlmsg_flags & NLM_F_CREATE)) { if (ifm->ifi_index == 0 && tb[IFLA_GROUP]) return rtnl_group_changelink(skb, net, nla_get_u32(tb[IFLA_GROUP]), ifm, tb); return -ENODEV; } if (tb[IFLA_MAP] || tb[IFLA_MASTER] || tb[IFLA_PROTINFO]) return -EOPNOTSUPP; if (!ops) { #ifdef CONFIG_MODULES if (kind[0]) { __rtnl_unlock(); request_module("rtnl-link-%s", kind); rtnl_lock(); ops = rtnl_link_ops_get(kind); if (ops) goto replay; } #endif return -EOPNOTSUPP; } if (!ops->setup) return -EOPNOTSUPP; if (!ifname[0]) { snprintf(ifname, IFNAMSIZ, "%s%%d", ops->kind); name_assign_type = NET_NAME_ENUM; } dest_net = rtnl_link_get_net(net, tb); if (IS_ERR(dest_net)) return PTR_ERR(dest_net); err = -EPERM; if (!netlink_ns_capable(skb, dest_net->user_ns, CAP_NET_ADMIN)) goto out; if (tb[IFLA_LINK_NETNSID]) { int id = nla_get_s32(tb[IFLA_LINK_NETNSID]); link_net = get_net_ns_by_id(dest_net, id); if (!link_net) { err = -EINVAL; goto out; } err = -EPERM; if (!netlink_ns_capable(skb, link_net->user_ns, CAP_NET_ADMIN)) goto out; } dev = rtnl_create_link(link_net ? : dest_net, ifname, name_assign_type, ops, tb); if (IS_ERR(dev)) { err = PTR_ERR(dev); goto out; } dev->ifindex = ifm->ifi_index; if (ops->newlink) { err = ops->newlink(link_net ? : net, dev, tb, data); /* Drivers should call free_netdev() in ->destructor * and unregister it on failure after registration * so that device could be finally freed in rtnl_unlock. */ if (err < 0) { /* If device is not registered at all, free it now */ if (dev->reg_state == NETREG_UNINITIALIZED) free_netdev(dev); goto out; } } else { err = register_netdevice(dev); if (err < 0) { free_netdev(dev); goto out; } } err = rtnl_configure_link(dev, ifm); if (err < 0) goto out_unregister; if (link_net) { err = dev_change_net_namespace(dev, dest_net, ifname); if (err < 0) goto out_unregister; } out: if (link_net) put_net(link_net); put_net(dest_net); return err; out_unregister: if (ops->newlink) { LIST_HEAD(list_kill); ops->dellink(dev, &list_kill); unregister_netdevice_many(&list_kill); } else { unregister_netdevice(dev); } goto out; } } static int rtnl_getlink(struct sk_buff *skb, struct nlmsghdr* nlh) { struct net *net = sock_net(skb->sk); struct ifinfomsg *ifm; char ifname[IFNAMSIZ]; struct nlattr *tb[IFLA_MAX+1]; struct net_device *dev = NULL; struct sk_buff *nskb; int err; u32 ext_filter_mask = 0; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFLA_MAX, ifla_policy); if (err < 0) return err; if (tb[IFLA_IFNAME]) nla_strlcpy(ifname, tb[IFLA_IFNAME], IFNAMSIZ); if (tb[IFLA_EXT_MASK]) ext_filter_mask = nla_get_u32(tb[IFLA_EXT_MASK]); ifm = nlmsg_data(nlh); if (ifm->ifi_index > 0) dev = __dev_get_by_index(net, ifm->ifi_index); else if (tb[IFLA_IFNAME]) dev = __dev_get_by_name(net, ifname); else return -EINVAL; if (dev == NULL) return -ENODEV; nskb = nlmsg_new(if_nlmsg_size(dev, ext_filter_mask), GFP_KERNEL); if (nskb == NULL) return -ENOBUFS; err = rtnl_fill_ifinfo(nskb, dev, RTM_NEWLINK, NETLINK_CB(skb).portid, nlh->nlmsg_seq, 0, 0, ext_filter_mask); if (err < 0) { /* -EMSGSIZE implies BUG in if_nlmsg_size */ WARN_ON(err == -EMSGSIZE); kfree_skb(nskb); } else err = rtnl_unicast(nskb, net, NETLINK_CB(skb).portid); return err; } static u16 rtnl_calcit(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct net_device *dev; struct nlattr *tb[IFLA_MAX+1]; u32 ext_filter_mask = 0; u16 min_ifinfo_dump_size = 0; int hdrlen; /* Same kernel<->userspace interface hack as in rtnl_dump_ifinfo. */ hdrlen = nlmsg_len(nlh) < sizeof(struct ifinfomsg) ? sizeof(struct rtgenmsg) : sizeof(struct ifinfomsg); if (nlmsg_parse(nlh, hdrlen, tb, IFLA_MAX, ifla_policy) >= 0) { if (tb[IFLA_EXT_MASK]) ext_filter_mask = nla_get_u32(tb[IFLA_EXT_MASK]); } if (!ext_filter_mask) return NLMSG_GOODSIZE; /* * traverse the list of net devices and compute the minimum * buffer size based upon the filter mask. */ list_for_each_entry(dev, &net->dev_base_head, dev_list) { min_ifinfo_dump_size = max_t(u16, min_ifinfo_dump_size, if_nlmsg_size(dev, ext_filter_mask)); } return min_ifinfo_dump_size; } static int rtnl_dump_all(struct sk_buff *skb, struct netlink_callback *cb) { int idx; int s_idx = cb->family; if (s_idx == 0) s_idx = 1; for (idx = 1; idx <= RTNL_FAMILY_MAX; idx++) { int type = cb->nlh->nlmsg_type-RTM_BASE; if (idx < s_idx || idx == PF_PACKET) continue; if (rtnl_msg_handlers[idx] == NULL || rtnl_msg_handlers[idx][type].dumpit == NULL) continue; if (idx > s_idx) { memset(&cb->args[0], 0, sizeof(cb->args)); cb->prev_seq = 0; cb->seq = 0; } if (rtnl_msg_handlers[idx][type].dumpit(skb, cb)) break; } cb->family = idx; return skb->len; } struct sk_buff *rtmsg_ifinfo_build_skb(int type, struct net_device *dev, unsigned int change, gfp_t flags) { struct net *net = dev_net(dev); struct sk_buff *skb; int err = -ENOBUFS; size_t if_info_size; skb = nlmsg_new((if_info_size = if_nlmsg_size(dev, 0)), flags); if (skb == NULL) goto errout; err = rtnl_fill_ifinfo(skb, dev, type, 0, 0, change, 0, 0); if (err < 0) { /* -EMSGSIZE implies BUG in if_nlmsg_size() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } return skb; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_LINK, err); return NULL; } void rtmsg_ifinfo_send(struct sk_buff *skb, struct net_device *dev, gfp_t flags) { struct net *net = dev_net(dev); rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, flags); } void rtmsg_ifinfo(int type, struct net_device *dev, unsigned int change, gfp_t flags) { struct sk_buff *skb; if (dev->reg_state != NETREG_REGISTERED) return; skb = rtmsg_ifinfo_build_skb(type, dev, change, flags); if (skb) rtmsg_ifinfo_send(skb, dev, flags); } EXPORT_SYMBOL(rtmsg_ifinfo); static int nlmsg_populate_fdb_fill(struct sk_buff *skb, struct net_device *dev, u8 *addr, u16 vid, u32 pid, u32 seq, int type, unsigned int flags, int nlflags, u16 ndm_state) { struct nlmsghdr *nlh; struct ndmsg *ndm; nlh = nlmsg_put(skb, pid, seq, type, sizeof(*ndm), nlflags); if (!nlh) return -EMSGSIZE; ndm = nlmsg_data(nlh); ndm->ndm_family = AF_BRIDGE; ndm->ndm_pad1 = 0; ndm->ndm_pad2 = 0; ndm->ndm_flags = flags; ndm->ndm_type = 0; ndm->ndm_ifindex = dev->ifindex; ndm->ndm_state = ndm_state; if (nla_put(skb, NDA_LLADDR, ETH_ALEN, addr)) goto nla_put_failure; if (vid) if (nla_put(skb, NDA_VLAN, sizeof(u16), &vid)) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static inline size_t rtnl_fdb_nlmsg_size(void) { return NLMSG_ALIGN(sizeof(struct ndmsg)) + nla_total_size(ETH_ALEN); } static void rtnl_fdb_notify(struct net_device *dev, u8 *addr, u16 vid, int type, u16 ndm_state) { struct net *net = dev_net(dev); struct sk_buff *skb; int err = -ENOBUFS; skb = nlmsg_new(rtnl_fdb_nlmsg_size(), GFP_ATOMIC); if (!skb) goto errout; err = nlmsg_populate_fdb_fill(skb, dev, addr, vid, 0, 0, type, NTF_SELF, 0, ndm_state); if (err < 0) { kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_NEIGH, NULL, GFP_ATOMIC); return; errout: rtnl_set_sk_err(net, RTNLGRP_NEIGH, err); } /** * ndo_dflt_fdb_add - default netdevice operation to add an FDB entry */ int ndo_dflt_fdb_add(struct ndmsg *ndm, struct nlattr *tb[], struct net_device *dev, const unsigned char *addr, u16 vid, u16 flags) { int err = -EINVAL; /* If aging addresses are supported device will need to * implement its own handler for this. */ if (ndm->ndm_state && !(ndm->ndm_state & NUD_PERMANENT)) { pr_info("%s: FDB only supports static addresses\n", dev->name); return err; } if (vid) { pr_info("%s: vlans aren't supported yet for dev_uc|mc_add()\n", dev->name); return err; } if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr)) err = dev_uc_add_excl(dev, addr); else if (is_multicast_ether_addr(addr)) err = dev_mc_add_excl(dev, addr); /* Only return duplicate errors if NLM_F_EXCL is set */ if (err == -EEXIST && !(flags & NLM_F_EXCL)) err = 0; return err; } EXPORT_SYMBOL(ndo_dflt_fdb_add); static int fdb_vid_parse(struct nlattr *vlan_attr, u16 *p_vid) { u16 vid = 0; if (vlan_attr) { if (nla_len(vlan_attr) != sizeof(u16)) { pr_info("PF_BRIDGE: RTM_NEWNEIGH with invalid vlan\n"); return -EINVAL; } vid = nla_get_u16(vlan_attr); if (!vid || vid >= VLAN_VID_MASK) { pr_info("PF_BRIDGE: RTM_NEWNEIGH with invalid vlan id %d\n", vid); return -EINVAL; } } *p_vid = vid; return 0; } static int rtnl_fdb_add(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct ndmsg *ndm; struct nlattr *tb[NDA_MAX+1]; struct net_device *dev; u8 *addr; u16 vid; int err; err = nlmsg_parse(nlh, sizeof(*ndm), tb, NDA_MAX, NULL); if (err < 0) return err; ndm = nlmsg_data(nlh); if (ndm->ndm_ifindex == 0) { pr_info("PF_BRIDGE: RTM_NEWNEIGH with invalid ifindex\n"); return -EINVAL; } dev = __dev_get_by_index(net, ndm->ndm_ifindex); if (dev == NULL) { pr_info("PF_BRIDGE: RTM_NEWNEIGH with unknown ifindex\n"); return -ENODEV; } if (!tb[NDA_LLADDR] || nla_len(tb[NDA_LLADDR]) != ETH_ALEN) { pr_info("PF_BRIDGE: RTM_NEWNEIGH with invalid address\n"); return -EINVAL; } addr = nla_data(tb[NDA_LLADDR]); err = fdb_vid_parse(tb[NDA_VLAN], &vid); if (err) return err; err = -EOPNOTSUPP; /* Support fdb on master device the net/bridge default case */ if ((!ndm->ndm_flags || ndm->ndm_flags & NTF_MASTER) && (dev->priv_flags & IFF_BRIDGE_PORT)) { struct net_device *br_dev = netdev_master_upper_dev_get(dev); const struct net_device_ops *ops = br_dev->netdev_ops; err = ops->ndo_fdb_add(ndm, tb, dev, addr, vid, nlh->nlmsg_flags); if (err) goto out; else ndm->ndm_flags &= ~NTF_MASTER; } /* Embedded bridge, macvlan, and any other device support */ if ((ndm->ndm_flags & NTF_SELF)) { if (dev->netdev_ops->ndo_fdb_add) err = dev->netdev_ops->ndo_fdb_add(ndm, tb, dev, addr, vid, nlh->nlmsg_flags); else err = ndo_dflt_fdb_add(ndm, tb, dev, addr, vid, nlh->nlmsg_flags); if (!err) { rtnl_fdb_notify(dev, addr, vid, RTM_NEWNEIGH, ndm->ndm_state); ndm->ndm_flags &= ~NTF_SELF; } } out: return err; } /** * ndo_dflt_fdb_del - default netdevice operation to delete an FDB entry */ int ndo_dflt_fdb_del(struct ndmsg *ndm, struct nlattr *tb[], struct net_device *dev, const unsigned char *addr, u16 vid) { int err = -EINVAL; /* If aging addresses are supported device will need to * implement its own handler for this. */ if (!(ndm->ndm_state & NUD_PERMANENT)) { pr_info("%s: FDB only supports static addresses\n", dev->name); return err; } if (is_unicast_ether_addr(addr) || is_link_local_ether_addr(addr)) err = dev_uc_del(dev, addr); else if (is_multicast_ether_addr(addr)) err = dev_mc_del(dev, addr); return err; } EXPORT_SYMBOL(ndo_dflt_fdb_del); static int rtnl_fdb_del(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct ndmsg *ndm; struct nlattr *tb[NDA_MAX+1]; struct net_device *dev; int err = -EINVAL; __u8 *addr; u16 vid; if (!netlink_capable(skb, CAP_NET_ADMIN)) return -EPERM; err = nlmsg_parse(nlh, sizeof(*ndm), tb, NDA_MAX, NULL); if (err < 0) return err; ndm = nlmsg_data(nlh); if (ndm->ndm_ifindex == 0) { pr_info("PF_BRIDGE: RTM_DELNEIGH with invalid ifindex\n"); return -EINVAL; } dev = __dev_get_by_index(net, ndm->ndm_ifindex); if (dev == NULL) { pr_info("PF_BRIDGE: RTM_DELNEIGH with unknown ifindex\n"); return -ENODEV; } if (!tb[NDA_LLADDR] || nla_len(tb[NDA_LLADDR]) != ETH_ALEN) { pr_info("PF_BRIDGE: RTM_DELNEIGH with invalid address\n"); return -EINVAL; } addr = nla_data(tb[NDA_LLADDR]); err = fdb_vid_parse(tb[NDA_VLAN], &vid); if (err) return err; err = -EOPNOTSUPP; /* Support fdb on master device the net/bridge default case */ if ((!ndm->ndm_flags || ndm->ndm_flags & NTF_MASTER) && (dev->priv_flags & IFF_BRIDGE_PORT)) { struct net_device *br_dev = netdev_master_upper_dev_get(dev); const struct net_device_ops *ops = br_dev->netdev_ops; if (ops->ndo_fdb_del) err = ops->ndo_fdb_del(ndm, tb, dev, addr, vid); if (err) goto out; else ndm->ndm_flags &= ~NTF_MASTER; } /* Embedded bridge, macvlan, and any other device support */ if (ndm->ndm_flags & NTF_SELF) { if (dev->netdev_ops->ndo_fdb_del) err = dev->netdev_ops->ndo_fdb_del(ndm, tb, dev, addr, vid); else err = ndo_dflt_fdb_del(ndm, tb, dev, addr, vid); if (!err) { rtnl_fdb_notify(dev, addr, vid, RTM_DELNEIGH, ndm->ndm_state); ndm->ndm_flags &= ~NTF_SELF; } } out: return err; } static int nlmsg_populate_fdb(struct sk_buff *skb, struct netlink_callback *cb, struct net_device *dev, int *idx, struct netdev_hw_addr_list *list) { struct netdev_hw_addr *ha; int err; u32 portid, seq; portid = NETLINK_CB(cb->skb).portid; seq = cb->nlh->nlmsg_seq; list_for_each_entry(ha, &list->list, list) { if (*idx < cb->args[0]) goto skip; err = nlmsg_populate_fdb_fill(skb, dev, ha->addr, 0, portid, seq, RTM_NEWNEIGH, NTF_SELF, NLM_F_MULTI, NUD_PERMANENT); if (err < 0) return err; skip: *idx += 1; } return 0; } /** * ndo_dflt_fdb_dump - default netdevice operation to dump an FDB table. * @nlh: netlink message header * @dev: netdevice * * Default netdevice operation to dump the existing unicast address list. * Returns number of addresses from list put in skb. */ int ndo_dflt_fdb_dump(struct sk_buff *skb, struct netlink_callback *cb, struct net_device *dev, struct net_device *filter_dev, int idx) { int err; netif_addr_lock_bh(dev); err = nlmsg_populate_fdb(skb, cb, dev, &idx, &dev->uc); if (err) goto out; nlmsg_populate_fdb(skb, cb, dev, &idx, &dev->mc); out: netif_addr_unlock_bh(dev); cb->args[1] = err; return idx; } EXPORT_SYMBOL(ndo_dflt_fdb_dump); static int rtnl_fdb_dump(struct sk_buff *skb, struct netlink_callback *cb) { struct net_device *dev; struct nlattr *tb[IFLA_MAX+1]; struct net_device *br_dev = NULL; const struct net_device_ops *ops = NULL; const struct net_device_ops *cops = NULL; struct ifinfomsg *ifm = nlmsg_data(cb->nlh); struct net *net = sock_net(skb->sk); int brport_idx = 0; int br_idx = 0; int idx = 0; if (nlmsg_parse(cb->nlh, sizeof(struct ifinfomsg), tb, IFLA_MAX, ifla_policy) == 0) { if (tb[IFLA_MASTER]) br_idx = nla_get_u32(tb[IFLA_MASTER]); } brport_idx = ifm->ifi_index; if (br_idx) { br_dev = __dev_get_by_index(net, br_idx); if (!br_dev) return -ENODEV; ops = br_dev->netdev_ops; } cb->args[1] = 0; for_each_netdev(net, dev) { if (brport_idx && (dev->ifindex != brport_idx)) continue; if (!br_idx) { /* user did not specify a specific bridge */ if (dev->priv_flags & IFF_BRIDGE_PORT) { br_dev = netdev_master_upper_dev_get(dev); cops = br_dev->netdev_ops; } } else { if (dev != br_dev && !(dev->priv_flags & IFF_BRIDGE_PORT)) continue; if (br_dev != netdev_master_upper_dev_get(dev) && !(dev->priv_flags & IFF_EBRIDGE)) continue; cops = ops; } if (dev->priv_flags & IFF_BRIDGE_PORT) { if (cops && cops->ndo_fdb_dump) idx = cops->ndo_fdb_dump(skb, cb, br_dev, dev, idx); } if (cb->args[1] == -EMSGSIZE) break; if (dev->netdev_ops->ndo_fdb_dump) idx = dev->netdev_ops->ndo_fdb_dump(skb, cb, dev, NULL, idx); else idx = ndo_dflt_fdb_dump(skb, cb, dev, NULL, idx); if (cb->args[1] == -EMSGSIZE) break; cops = NULL; } cb->args[0] = idx; return skb->len; } static int brport_nla_put_flag(struct sk_buff *skb, u32 flags, u32 mask, unsigned int attrnum, unsigned int flag) { if (mask & flag) return nla_put_u8(skb, attrnum, !!(flags & flag)); return 0; } int ndo_dflt_bridge_getlink(struct sk_buff *skb, u32 pid, u32 seq, struct net_device *dev, u16 mode, u32 flags, u32 mask, int nlflags, u32 filter_mask, int (*vlan_fill)(struct sk_buff *skb, struct net_device *dev, u32 filter_mask)) { struct nlmsghdr *nlh; struct ifinfomsg *ifm; struct nlattr *br_afspec; struct nlattr *protinfo; u8 operstate = netif_running(dev) ? dev->operstate : IF_OPER_DOWN; struct net_device *br_dev = netdev_master_upper_dev_get(dev); int err = 0; nlh = nlmsg_put(skb, pid, seq, RTM_NEWLINK, sizeof(*ifm), nlflags); if (nlh == NULL) return -EMSGSIZE; ifm = nlmsg_data(nlh); ifm->ifi_family = AF_BRIDGE; ifm->__ifi_pad = 0; ifm->ifi_type = dev->type; ifm->ifi_index = dev->ifindex; ifm->ifi_flags = dev_get_flags(dev); ifm->ifi_change = 0; if (nla_put_string(skb, IFLA_IFNAME, dev->name) || nla_put_u32(skb, IFLA_MTU, dev->mtu) || nla_put_u8(skb, IFLA_OPERSTATE, operstate) || (br_dev && nla_put_u32(skb, IFLA_MASTER, br_dev->ifindex)) || (dev->addr_len && nla_put(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr)) || (dev->ifindex != dev_get_iflink(dev) && nla_put_u32(skb, IFLA_LINK, dev_get_iflink(dev)))) goto nla_put_failure; br_afspec = nla_nest_start(skb, IFLA_AF_SPEC); if (!br_afspec) goto nla_put_failure; if (nla_put_u16(skb, IFLA_BRIDGE_FLAGS, BRIDGE_FLAGS_SELF)) { nla_nest_cancel(skb, br_afspec); goto nla_put_failure; } if (mode != BRIDGE_MODE_UNDEF) { if (nla_put_u16(skb, IFLA_BRIDGE_MODE, mode)) { nla_nest_cancel(skb, br_afspec); goto nla_put_failure; } } if (vlan_fill) { err = vlan_fill(skb, dev, filter_mask); if (err) { nla_nest_cancel(skb, br_afspec); goto nla_put_failure; } } nla_nest_end(skb, br_afspec); protinfo = nla_nest_start(skb, IFLA_PROTINFO | NLA_F_NESTED); if (!protinfo) goto nla_put_failure; if (brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_MODE, BR_HAIRPIN_MODE) || brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_GUARD, BR_BPDU_GUARD) || brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_FAST_LEAVE, BR_MULTICAST_FAST_LEAVE) || brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_PROTECT, BR_ROOT_BLOCK) || brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_LEARNING, BR_LEARNING) || brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_LEARNING_SYNC, BR_LEARNING_SYNC) || brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_UNICAST_FLOOD, BR_FLOOD) || brport_nla_put_flag(skb, flags, mask, IFLA_BRPORT_PROXYARP, BR_PROXYARP)) { nla_nest_cancel(skb, protinfo); goto nla_put_failure; } nla_nest_end(skb, protinfo); nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return err ? err : -EMSGSIZE; } EXPORT_SYMBOL_GPL(ndo_dflt_bridge_getlink); static int rtnl_bridge_getlink(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct net_device *dev; int idx = 0; u32 portid = NETLINK_CB(cb->skb).portid; u32 seq = cb->nlh->nlmsg_seq; u32 filter_mask = 0; int err; if (nlmsg_len(cb->nlh) > sizeof(struct ifinfomsg)) { struct nlattr *extfilt; extfilt = nlmsg_find_attr(cb->nlh, sizeof(struct ifinfomsg), IFLA_EXT_MASK); if (extfilt) { if (nla_len(extfilt) < sizeof(filter_mask)) return -EINVAL; filter_mask = nla_get_u32(extfilt); } } rcu_read_lock(); for_each_netdev_rcu(net, dev) { const struct net_device_ops *ops = dev->netdev_ops; struct net_device *br_dev = netdev_master_upper_dev_get(dev); if (br_dev && br_dev->netdev_ops->ndo_bridge_getlink) { if (idx >= cb->args[0]) { err = br_dev->netdev_ops->ndo_bridge_getlink( skb, portid, seq, dev, filter_mask, NLM_F_MULTI); if (err < 0 && err != -EOPNOTSUPP) break; } idx++; } if (ops->ndo_bridge_getlink) { if (idx >= cb->args[0]) { err = ops->ndo_bridge_getlink(skb, portid, seq, dev, filter_mask, NLM_F_MULTI); if (err < 0 && err != -EOPNOTSUPP) break; } idx++; } } rcu_read_unlock(); cb->args[0] = idx; return skb->len; } static inline size_t bridge_nlmsg_size(void) { return NLMSG_ALIGN(sizeof(struct ifinfomsg)) + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */ + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */ + nla_total_size(sizeof(u32)) /* IFLA_MASTER */ + nla_total_size(sizeof(u32)) /* IFLA_MTU */ + nla_total_size(sizeof(u32)) /* IFLA_LINK */ + nla_total_size(sizeof(u32)) /* IFLA_OPERSTATE */ + nla_total_size(sizeof(u8)) /* IFLA_PROTINFO */ + nla_total_size(sizeof(struct nlattr)) /* IFLA_AF_SPEC */ + nla_total_size(sizeof(u16)) /* IFLA_BRIDGE_FLAGS */ + nla_total_size(sizeof(u16)); /* IFLA_BRIDGE_MODE */ } static int rtnl_bridge_notify(struct net_device *dev) { struct net *net = dev_net(dev); struct sk_buff *skb; int err = -EOPNOTSUPP; if (!dev->netdev_ops->ndo_bridge_getlink) return 0; skb = nlmsg_new(bridge_nlmsg_size(), GFP_ATOMIC); if (!skb) { err = -ENOMEM; goto errout; } err = dev->netdev_ops->ndo_bridge_getlink(skb, 0, 0, dev, 0, 0); if (err < 0) goto errout; if (!skb->len) goto errout; rtnl_notify(skb, net, 0, RTNLGRP_LINK, NULL, GFP_ATOMIC); return 0; errout: WARN_ON(err == -EMSGSIZE); kfree_skb(skb); if (err) rtnl_set_sk_err(net, RTNLGRP_LINK, err); return err; } static int rtnl_bridge_setlink(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct ifinfomsg *ifm; struct net_device *dev; struct nlattr *br_spec, *attr = NULL; int rem, err = -EOPNOTSUPP; u16 flags = 0; bool have_flags = false; if (nlmsg_len(nlh) < sizeof(*ifm)) return -EINVAL; ifm = nlmsg_data(nlh); if (ifm->ifi_family != AF_BRIDGE) return -EPFNOSUPPORT; dev = __dev_get_by_index(net, ifm->ifi_index); if (!dev) { pr_info("PF_BRIDGE: RTM_SETLINK with unknown ifindex\n"); return -ENODEV; } br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC); if (br_spec) { nla_for_each_nested(attr, br_spec, rem) { if (nla_type(attr) == IFLA_BRIDGE_FLAGS) { if (nla_len(attr) < sizeof(flags)) return -EINVAL; have_flags = true; flags = nla_get_u16(attr); break; } } } if (!flags || (flags & BRIDGE_FLAGS_MASTER)) { struct net_device *br_dev = netdev_master_upper_dev_get(dev); if (!br_dev || !br_dev->netdev_ops->ndo_bridge_setlink) { err = -EOPNOTSUPP; goto out; } err = br_dev->netdev_ops->ndo_bridge_setlink(dev, nlh, flags); if (err) goto out; flags &= ~BRIDGE_FLAGS_MASTER; } if ((flags & BRIDGE_FLAGS_SELF)) { if (!dev->netdev_ops->ndo_bridge_setlink) err = -EOPNOTSUPP; else err = dev->netdev_ops->ndo_bridge_setlink(dev, nlh, flags); if (!err) { flags &= ~BRIDGE_FLAGS_SELF; /* Generate event to notify upper layer of bridge * change */ err = rtnl_bridge_notify(dev); } } if (have_flags) memcpy(nla_data(attr), &flags, sizeof(flags)); out: return err; } static int rtnl_bridge_dellink(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct ifinfomsg *ifm; struct net_device *dev; struct nlattr *br_spec, *attr = NULL; int rem, err = -EOPNOTSUPP; u16 flags = 0; bool have_flags = false; if (nlmsg_len(nlh) < sizeof(*ifm)) return -EINVAL; ifm = nlmsg_data(nlh); if (ifm->ifi_family != AF_BRIDGE) return -EPFNOSUPPORT; dev = __dev_get_by_index(net, ifm->ifi_index); if (!dev) { pr_info("PF_BRIDGE: RTM_SETLINK with unknown ifindex\n"); return -ENODEV; } br_spec = nlmsg_find_attr(nlh, sizeof(struct ifinfomsg), IFLA_AF_SPEC); if (br_spec) { nla_for_each_nested(attr, br_spec, rem) { if (nla_type(attr) == IFLA_BRIDGE_FLAGS) { if (nla_len(attr) < sizeof(flags)) return -EINVAL; have_flags = true; flags = nla_get_u16(attr); break; } } } if (!flags || (flags & BRIDGE_FLAGS_MASTER)) { struct net_device *br_dev = netdev_master_upper_dev_get(dev); if (!br_dev || !br_dev->netdev_ops->ndo_bridge_dellink) { err = -EOPNOTSUPP; goto out; } err = br_dev->netdev_ops->ndo_bridge_dellink(dev, nlh, flags); if (err) goto out; flags &= ~BRIDGE_FLAGS_MASTER; } if ((flags & BRIDGE_FLAGS_SELF)) { if (!dev->netdev_ops->ndo_bridge_dellink) err = -EOPNOTSUPP; else err = dev->netdev_ops->ndo_bridge_dellink(dev, nlh, flags); if (!err) { flags &= ~BRIDGE_FLAGS_SELF; /* Generate event to notify upper layer of bridge * change */ err = rtnl_bridge_notify(dev); } } if (have_flags) memcpy(nla_data(attr), &flags, sizeof(flags)); out: return err; } /* Process one rtnetlink message. */ static int rtnetlink_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); rtnl_doit_func doit; int kind; int family; int type; int err; type = nlh->nlmsg_type; if (type > RTM_MAX) return -EOPNOTSUPP; type -= RTM_BASE; /* All the messages must have at least 1 byte length */ if (nlmsg_len(nlh) < sizeof(struct rtgenmsg)) return 0; family = ((struct rtgenmsg *)nlmsg_data(nlh))->rtgen_family; kind = type&3; if (kind != 2 && !netlink_net_capable(skb, CAP_NET_ADMIN)) return -EPERM; if (kind == 2 && nlh->nlmsg_flags&NLM_F_DUMP) { struct sock *rtnl; rtnl_dumpit_func dumpit; rtnl_calcit_func calcit; u16 min_dump_alloc = 0; dumpit = rtnl_get_dumpit(family, type); if (dumpit == NULL) return -EOPNOTSUPP; calcit = rtnl_get_calcit(family, type); if (calcit) min_dump_alloc = calcit(skb, nlh); __rtnl_unlock(); rtnl = net->rtnl; { struct netlink_dump_control c = { .dump = dumpit, .min_dump_alloc = min_dump_alloc, }; err = netlink_dump_start(rtnl, skb, nlh, &c); } rtnl_lock(); return err; } doit = rtnl_get_doit(family, type); if (doit == NULL) return -EOPNOTSUPP; return doit(skb, nlh); } static void rtnetlink_rcv(struct sk_buff *skb) { rtnl_lock(); netlink_rcv_skb(skb, &rtnetlink_rcv_msg); rtnl_unlock(); } static int rtnetlink_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = netdev_notifier_info_to_dev(ptr); switch (event) { case NETDEV_UP: case NETDEV_DOWN: case NETDEV_PRE_UP: case NETDEV_POST_INIT: case NETDEV_REGISTER: case NETDEV_CHANGE: case NETDEV_PRE_TYPE_CHANGE: case NETDEV_GOING_DOWN: case NETDEV_UNREGISTER: case NETDEV_UNREGISTER_FINAL: case NETDEV_RELEASE: case NETDEV_JOIN: case NETDEV_BONDING_INFO: break; default: rtmsg_ifinfo(RTM_NEWLINK, dev, 0, GFP_KERNEL); break; } return NOTIFY_DONE; } static struct notifier_block rtnetlink_dev_notifier = { .notifier_call = rtnetlink_event, }; static int __net_init rtnetlink_net_init(struct net *net) { struct sock *sk; struct netlink_kernel_cfg cfg = { .groups = RTNLGRP_MAX, .input = rtnetlink_rcv, .cb_mutex = &rtnl_mutex, .flags = NL_CFG_F_NONROOT_RECV, }; sk = netlink_kernel_create(net, NETLINK_ROUTE, &cfg); if (!sk) return -ENOMEM; net->rtnl = sk; return 0; } static void __net_exit rtnetlink_net_exit(struct net *net) { netlink_kernel_release(net->rtnl); net->rtnl = NULL; } static struct pernet_operations rtnetlink_net_ops = { .init = rtnetlink_net_init, .exit = rtnetlink_net_exit, }; void __init rtnetlink_init(void) { if (register_pernet_subsys(&rtnetlink_net_ops)) panic("rtnetlink_init: cannot initialize rtnetlink\n"); register_netdevice_notifier(&rtnetlink_dev_notifier); rtnl_register(PF_UNSPEC, RTM_GETLINK, rtnl_getlink, rtnl_dump_ifinfo, rtnl_calcit); rtnl_register(PF_UNSPEC, RTM_SETLINK, rtnl_setlink, NULL, NULL); rtnl_register(PF_UNSPEC, RTM_NEWLINK, rtnl_newlink, NULL, NULL); rtnl_register(PF_UNSPEC, RTM_DELLINK, rtnl_dellink, NULL, NULL); rtnl_register(PF_UNSPEC, RTM_GETADDR, NULL, rtnl_dump_all, NULL); rtnl_register(PF_UNSPEC, RTM_GETROUTE, NULL, rtnl_dump_all, NULL); rtnl_register(PF_BRIDGE, RTM_NEWNEIGH, rtnl_fdb_add, NULL, NULL); rtnl_register(PF_BRIDGE, RTM_DELNEIGH, rtnl_fdb_del, NULL, NULL); rtnl_register(PF_BRIDGE, RTM_GETNEIGH, NULL, rtnl_fdb_dump, NULL); rtnl_register(PF_BRIDGE, RTM_GETLINK, NULL, rtnl_bridge_getlink, NULL); rtnl_register(PF_BRIDGE, RTM_DELLINK, rtnl_bridge_dellink, NULL, NULL); rtnl_register(PF_BRIDGE, RTM_SETLINK, rtnl_bridge_setlink, NULL, NULL); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5050_0
crossvul-cpp_data_bad_5340_0
/* Netfilter messages via netlink socket. Allows for user space * protocol helpers and general trouble making from userspace. * * (C) 2001 by Jay Schulist <jschlst@samba.org>, * (C) 2002-2005 by Harald Welte <laforge@gnumonks.org> * (C) 2005,2007 by Pablo Neira Ayuso <pablo@netfilter.org> * * Initial netfilter messages via netlink development funded and * generally made possible by Network Robots, Inc. (www.networkrobots.com) * * Further development of this code funded by Astaro AG (http://www.astaro.com) * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. */ #include <linux/module.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/skbuff.h> #include <asm/uaccess.h> #include <net/sock.h> #include <linux/init.h> #include <net/netlink.h> #include <linux/netfilter/nfnetlink.h> MODULE_LICENSE("GPL"); MODULE_AUTHOR("Harald Welte <laforge@netfilter.org>"); MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_NETFILTER); #define nfnl_dereference_protected(id) \ rcu_dereference_protected(table[(id)].subsys, \ lockdep_nfnl_is_held((id))) static char __initdata nfversion[] = "0.30"; static struct { struct mutex mutex; const struct nfnetlink_subsystem __rcu *subsys; } table[NFNL_SUBSYS_COUNT]; static const int nfnl_group2type[NFNLGRP_MAX+1] = { [NFNLGRP_CONNTRACK_NEW] = NFNL_SUBSYS_CTNETLINK, [NFNLGRP_CONNTRACK_UPDATE] = NFNL_SUBSYS_CTNETLINK, [NFNLGRP_CONNTRACK_DESTROY] = NFNL_SUBSYS_CTNETLINK, [NFNLGRP_CONNTRACK_EXP_NEW] = NFNL_SUBSYS_CTNETLINK_EXP, [NFNLGRP_CONNTRACK_EXP_UPDATE] = NFNL_SUBSYS_CTNETLINK_EXP, [NFNLGRP_CONNTRACK_EXP_DESTROY] = NFNL_SUBSYS_CTNETLINK_EXP, [NFNLGRP_NFTABLES] = NFNL_SUBSYS_NFTABLES, [NFNLGRP_ACCT_QUOTA] = NFNL_SUBSYS_ACCT, [NFNLGRP_NFTRACE] = NFNL_SUBSYS_NFTABLES, }; void nfnl_lock(__u8 subsys_id) { mutex_lock(&table[subsys_id].mutex); } EXPORT_SYMBOL_GPL(nfnl_lock); void nfnl_unlock(__u8 subsys_id) { mutex_unlock(&table[subsys_id].mutex); } EXPORT_SYMBOL_GPL(nfnl_unlock); #ifdef CONFIG_PROVE_LOCKING bool lockdep_nfnl_is_held(u8 subsys_id) { return lockdep_is_held(&table[subsys_id].mutex); } EXPORT_SYMBOL_GPL(lockdep_nfnl_is_held); #endif int nfnetlink_subsys_register(const struct nfnetlink_subsystem *n) { nfnl_lock(n->subsys_id); if (table[n->subsys_id].subsys) { nfnl_unlock(n->subsys_id); return -EBUSY; } rcu_assign_pointer(table[n->subsys_id].subsys, n); nfnl_unlock(n->subsys_id); return 0; } EXPORT_SYMBOL_GPL(nfnetlink_subsys_register); int nfnetlink_subsys_unregister(const struct nfnetlink_subsystem *n) { nfnl_lock(n->subsys_id); table[n->subsys_id].subsys = NULL; nfnl_unlock(n->subsys_id); synchronize_rcu(); return 0; } EXPORT_SYMBOL_GPL(nfnetlink_subsys_unregister); static inline const struct nfnetlink_subsystem *nfnetlink_get_subsys(u_int16_t type) { u_int8_t subsys_id = NFNL_SUBSYS_ID(type); if (subsys_id >= NFNL_SUBSYS_COUNT) return NULL; return rcu_dereference(table[subsys_id].subsys); } static inline const struct nfnl_callback * nfnetlink_find_client(u_int16_t type, const struct nfnetlink_subsystem *ss) { u_int8_t cb_id = NFNL_MSG_TYPE(type); if (cb_id >= ss->cb_count) return NULL; return &ss->cb[cb_id]; } int nfnetlink_has_listeners(struct net *net, unsigned int group) { return netlink_has_listeners(net->nfnl, group); } EXPORT_SYMBOL_GPL(nfnetlink_has_listeners); struct sk_buff *nfnetlink_alloc_skb(struct net *net, unsigned int size, u32 dst_portid, gfp_t gfp_mask) { return netlink_alloc_skb(net->nfnl, size, dst_portid, gfp_mask); } EXPORT_SYMBOL_GPL(nfnetlink_alloc_skb); int nfnetlink_send(struct sk_buff *skb, struct net *net, u32 portid, unsigned int group, int echo, gfp_t flags) { return nlmsg_notify(net->nfnl, skb, portid, group, echo, flags); } EXPORT_SYMBOL_GPL(nfnetlink_send); int nfnetlink_set_err(struct net *net, u32 portid, u32 group, int error) { return netlink_set_err(net->nfnl, portid, group, error); } EXPORT_SYMBOL_GPL(nfnetlink_set_err); int nfnetlink_unicast(struct sk_buff *skb, struct net *net, u32 portid, int flags) { return netlink_unicast(net->nfnl, skb, portid, flags); } EXPORT_SYMBOL_GPL(nfnetlink_unicast); /* Process one complete nfnetlink message. */ static int nfnetlink_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); const struct nfnl_callback *nc; const struct nfnetlink_subsystem *ss; int type, err; /* All the messages must at least contain nfgenmsg */ if (nlmsg_len(nlh) < sizeof(struct nfgenmsg)) return 0; type = nlh->nlmsg_type; replay: rcu_read_lock(); ss = nfnetlink_get_subsys(type); if (!ss) { #ifdef CONFIG_MODULES rcu_read_unlock(); request_module("nfnetlink-subsys-%d", NFNL_SUBSYS_ID(type)); rcu_read_lock(); ss = nfnetlink_get_subsys(type); if (!ss) #endif { rcu_read_unlock(); return -EINVAL; } } nc = nfnetlink_find_client(type, ss); if (!nc) { rcu_read_unlock(); return -EINVAL; } { int min_len = nlmsg_total_size(sizeof(struct nfgenmsg)); u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type); struct nlattr *cda[ss->cb[cb_id].attr_count + 1]; struct nlattr *attr = (void *)nlh + min_len; int attrlen = nlh->nlmsg_len - min_len; __u8 subsys_id = NFNL_SUBSYS_ID(type); err = nla_parse(cda, ss->cb[cb_id].attr_count, attr, attrlen, ss->cb[cb_id].policy); if (err < 0) { rcu_read_unlock(); return err; } if (nc->call_rcu) { err = nc->call_rcu(net, net->nfnl, skb, nlh, (const struct nlattr **)cda); rcu_read_unlock(); } else { rcu_read_unlock(); nfnl_lock(subsys_id); if (nfnl_dereference_protected(subsys_id) != ss || nfnetlink_find_client(type, ss) != nc) err = -EAGAIN; else if (nc->call) err = nc->call(net, net->nfnl, skb, nlh, (const struct nlattr **)cda); else err = -EINVAL; nfnl_unlock(subsys_id); } if (err == -EAGAIN) goto replay; return err; } } struct nfnl_err { struct list_head head; struct nlmsghdr *nlh; int err; }; static int nfnl_err_add(struct list_head *list, struct nlmsghdr *nlh, int err) { struct nfnl_err *nfnl_err; nfnl_err = kmalloc(sizeof(struct nfnl_err), GFP_KERNEL); if (nfnl_err == NULL) return -ENOMEM; nfnl_err->nlh = nlh; nfnl_err->err = err; list_add_tail(&nfnl_err->head, list); return 0; } static void nfnl_err_del(struct nfnl_err *nfnl_err) { list_del(&nfnl_err->head); kfree(nfnl_err); } static void nfnl_err_reset(struct list_head *err_list) { struct nfnl_err *nfnl_err, *next; list_for_each_entry_safe(nfnl_err, next, err_list, head) nfnl_err_del(nfnl_err); } static void nfnl_err_deliver(struct list_head *err_list, struct sk_buff *skb) { struct nfnl_err *nfnl_err, *next; list_for_each_entry_safe(nfnl_err, next, err_list, head) { netlink_ack(skb, nfnl_err->nlh, nfnl_err->err); nfnl_err_del(nfnl_err); } } enum { NFNL_BATCH_FAILURE = (1 << 0), NFNL_BATCH_DONE = (1 << 1), NFNL_BATCH_REPLAY = (1 << 2), }; static void nfnetlink_rcv_batch(struct sk_buff *skb, struct nlmsghdr *nlh, u_int16_t subsys_id) { struct sk_buff *oskb = skb; struct net *net = sock_net(skb->sk); const struct nfnetlink_subsystem *ss; const struct nfnl_callback *nc; static LIST_HEAD(err_list); u32 status; int err; if (subsys_id >= NFNL_SUBSYS_COUNT) return netlink_ack(skb, nlh, -EINVAL); replay: status = 0; skb = netlink_skb_clone(oskb, GFP_KERNEL); if (!skb) return netlink_ack(oskb, nlh, -ENOMEM); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) { #ifdef CONFIG_MODULES nfnl_unlock(subsys_id); request_module("nfnetlink-subsys-%d", subsys_id); nfnl_lock(subsys_id); ss = nfnl_dereference_protected(subsys_id); if (!ss) #endif { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } } if (!ss->commit || !ss->abort) { nfnl_unlock(subsys_id); netlink_ack(oskb, nlh, -EOPNOTSUPP); return kfree_skb(skb); } while (skb->len >= nlmsg_total_size(0)) { int msglen, type; nlh = nlmsg_hdr(skb); err = 0; if (nlmsg_len(nlh) < sizeof(struct nfgenmsg) || skb->len < nlh->nlmsg_len) { err = -EINVAL; goto ack; } /* Only requests are handled by the kernel */ if (!(nlh->nlmsg_flags & NLM_F_REQUEST)) { err = -EINVAL; goto ack; } type = nlh->nlmsg_type; if (type == NFNL_MSG_BATCH_BEGIN) { /* Malformed: Batch begin twice */ nfnl_err_reset(&err_list); status |= NFNL_BATCH_FAILURE; goto done; } else if (type == NFNL_MSG_BATCH_END) { status |= NFNL_BATCH_DONE; goto done; } else if (type < NLMSG_MIN_TYPE) { err = -EINVAL; goto ack; } /* We only accept a batch with messages for the same * subsystem. */ if (NFNL_SUBSYS_ID(type) != subsys_id) { err = -EINVAL; goto ack; } nc = nfnetlink_find_client(type, ss); if (!nc) { err = -EINVAL; goto ack; } { int min_len = nlmsg_total_size(sizeof(struct nfgenmsg)); u_int8_t cb_id = NFNL_MSG_TYPE(nlh->nlmsg_type); struct nlattr *cda[ss->cb[cb_id].attr_count + 1]; struct nlattr *attr = (void *)nlh + min_len; int attrlen = nlh->nlmsg_len - min_len; err = nla_parse(cda, ss->cb[cb_id].attr_count, attr, attrlen, ss->cb[cb_id].policy); if (err < 0) goto ack; if (nc->call_batch) { err = nc->call_batch(net, net->nfnl, skb, nlh, (const struct nlattr **)cda); } /* The lock was released to autoload some module, we * have to abort and start from scratch using the * original skb. */ if (err == -EAGAIN) { status |= NFNL_BATCH_REPLAY; goto next; } } ack: if (nlh->nlmsg_flags & NLM_F_ACK || err) { /* Errors are delivered once the full batch has been * processed, this avoids that the same error is * reported several times when replaying the batch. */ if (nfnl_err_add(&err_list, nlh, err) < 0) { /* We failed to enqueue an error, reset the * list of errors and send OOM to userspace * pointing to the batch header. */ nfnl_err_reset(&err_list); netlink_ack(oskb, nlmsg_hdr(oskb), -ENOMEM); status |= NFNL_BATCH_FAILURE; goto done; } /* We don't stop processing the batch on errors, thus, * userspace gets all the errors that the batch * triggers. */ if (err) status |= NFNL_BATCH_FAILURE; } next: msglen = NLMSG_ALIGN(nlh->nlmsg_len); if (msglen > skb->len) msglen = skb->len; skb_pull(skb, msglen); } done: if (status & NFNL_BATCH_REPLAY) { ss->abort(net, oskb); nfnl_err_reset(&err_list); nfnl_unlock(subsys_id); kfree_skb(skb); goto replay; } else if (status == NFNL_BATCH_DONE) { ss->commit(net, oskb); } else { ss->abort(net, oskb); } nfnl_err_deliver(&err_list, oskb); nfnl_unlock(subsys_id); kfree_skb(skb); } static void nfnetlink_rcv(struct sk_buff *skb) { struct nlmsghdr *nlh = nlmsg_hdr(skb); u_int16_t res_id; int msglen; if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < nlh->nlmsg_len) return; if (!netlink_net_capable(skb, CAP_NET_ADMIN)) { netlink_ack(skb, nlh, -EPERM); return; } if (nlh->nlmsg_type == NFNL_MSG_BATCH_BEGIN) { struct nfgenmsg *nfgenmsg; msglen = NLMSG_ALIGN(nlh->nlmsg_len); if (msglen > skb->len) msglen = skb->len; if (nlh->nlmsg_len < NLMSG_HDRLEN || skb->len < NLMSG_HDRLEN + sizeof(struct nfgenmsg)) return; nfgenmsg = nlmsg_data(nlh); skb_pull(skb, msglen); /* Work around old nft using host byte order */ if (nfgenmsg->res_id == NFNL_SUBSYS_NFTABLES) res_id = NFNL_SUBSYS_NFTABLES; else res_id = ntohs(nfgenmsg->res_id); nfnetlink_rcv_batch(skb, nlh, res_id); } else { netlink_rcv_skb(skb, &nfnetlink_rcv_msg); } } #ifdef CONFIG_MODULES static int nfnetlink_bind(struct net *net, int group) { const struct nfnetlink_subsystem *ss; int type; if (group <= NFNLGRP_NONE || group > NFNLGRP_MAX) return 0; type = nfnl_group2type[group]; rcu_read_lock(); ss = nfnetlink_get_subsys(type << 8); rcu_read_unlock(); if (!ss) request_module("nfnetlink-subsys-%d", type); return 0; } #endif static int __net_init nfnetlink_net_init(struct net *net) { struct sock *nfnl; struct netlink_kernel_cfg cfg = { .groups = NFNLGRP_MAX, .input = nfnetlink_rcv, #ifdef CONFIG_MODULES .bind = nfnetlink_bind, #endif }; nfnl = netlink_kernel_create(net, NETLINK_NETFILTER, &cfg); if (!nfnl) return -ENOMEM; net->nfnl_stash = nfnl; rcu_assign_pointer(net->nfnl, nfnl); return 0; } static void __net_exit nfnetlink_net_exit_batch(struct list_head *net_exit_list) { struct net *net; list_for_each_entry(net, net_exit_list, exit_list) RCU_INIT_POINTER(net->nfnl, NULL); synchronize_net(); list_for_each_entry(net, net_exit_list, exit_list) netlink_kernel_release(net->nfnl_stash); } static struct pernet_operations nfnetlink_net_ops = { .init = nfnetlink_net_init, .exit_batch = nfnetlink_net_exit_batch, }; static int __init nfnetlink_init(void) { int i; for (i = NFNLGRP_NONE + 1; i <= NFNLGRP_MAX; i++) BUG_ON(nfnl_group2type[i] == NFNL_SUBSYS_NONE); for (i=0; i<NFNL_SUBSYS_COUNT; i++) mutex_init(&table[i].mutex); pr_info("Netfilter messages via NETLINK v%s.\n", nfversion); return register_pernet_subsys(&nfnetlink_net_ops); } static void __exit nfnetlink_exit(void) { pr_info("Removing netfilter NETLINK layer.\n"); unregister_pernet_subsys(&nfnetlink_net_ops); } module_init(nfnetlink_init); module_exit(nfnetlink_exit);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5340_0
crossvul-cpp_data_bad_1766_0
/* * Copyright 2003 Digi International (www.digi.com) * Scott H Kilau <Scott_Kilau at digi dot com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2, or (at your option) * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. */ /************************************************************************ * * This file implements the mgmt functionality for the * Neo and ClassicBoard based product lines. * ************************************************************************ */ #include <linux/kernel.h> #include <linux/ctype.h> #include <linux/sched.h> /* For jiffies, task states */ #include <linux/interrupt.h> /* For tasklet and interrupt structs/defines */ #include <linux/serial_reg.h> #include <linux/termios.h> #include <linux/uaccess.h> /* For copy_from_user/copy_to_user */ #include "dgnc_driver.h" #include "dgnc_pci.h" #include "dgnc_mgmt.h" /* Our "in use" variables, to enforce 1 open only */ static int dgnc_mgmt_in_use[MAXMGMTDEVICES]; /* * dgnc_mgmt_open() * * Open the mgmt/downld/dpa device */ int dgnc_mgmt_open(struct inode *inode, struct file *file) { unsigned long flags; unsigned int minor = iminor(inode); spin_lock_irqsave(&dgnc_global_lock, flags); /* mgmt device */ if (minor < MAXMGMTDEVICES) { /* Only allow 1 open at a time on mgmt device */ if (dgnc_mgmt_in_use[minor]) { spin_unlock_irqrestore(&dgnc_global_lock, flags); return -EBUSY; } dgnc_mgmt_in_use[minor]++; } else { spin_unlock_irqrestore(&dgnc_global_lock, flags); return -ENXIO; } spin_unlock_irqrestore(&dgnc_global_lock, flags); return 0; } /* * dgnc_mgmt_close() * * Open the mgmt/dpa device */ int dgnc_mgmt_close(struct inode *inode, struct file *file) { unsigned long flags; unsigned int minor = iminor(inode); spin_lock_irqsave(&dgnc_global_lock, flags); /* mgmt device */ if (minor < MAXMGMTDEVICES) { if (dgnc_mgmt_in_use[minor]) dgnc_mgmt_in_use[minor] = 0; } spin_unlock_irqrestore(&dgnc_global_lock, flags); return 0; } /* * dgnc_mgmt_ioctl() * * ioctl the mgmt/dpa device */ long dgnc_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { unsigned long flags; void __user *uarg = (void __user *)arg; switch (cmd) { case DIGI_GETDD: { /* * This returns the total number of boards * in the system, as well as driver version * and has space for a reserved entry */ struct digi_dinfo ddi; spin_lock_irqsave(&dgnc_global_lock, flags); ddi.dinfo_nboards = dgnc_NumBoards; sprintf(ddi.dinfo_version, "%s", DG_PART); spin_unlock_irqrestore(&dgnc_global_lock, flags); if (copy_to_user(uarg, &ddi, sizeof(ddi))) return -EFAULT; break; } case DIGI_GETBD: { int brd; struct digi_info di; if (copy_from_user(&brd, uarg, sizeof(int))) return -EFAULT; if (brd < 0 || brd >= dgnc_NumBoards) return -ENODEV; memset(&di, 0, sizeof(di)); di.info_bdnum = brd; spin_lock_irqsave(&dgnc_Board[brd]->bd_lock, flags); di.info_bdtype = dgnc_Board[brd]->dpatype; di.info_bdstate = dgnc_Board[brd]->dpastatus; di.info_ioport = 0; di.info_physaddr = (ulong)dgnc_Board[brd]->membase; di.info_physsize = (ulong)dgnc_Board[brd]->membase - dgnc_Board[brd]->membase_end; if (dgnc_Board[brd]->state != BOARD_FAILED) di.info_nports = dgnc_Board[brd]->nasync; else di.info_nports = 0; spin_unlock_irqrestore(&dgnc_Board[brd]->bd_lock, flags); if (copy_to_user(uarg, &di, sizeof(di))) return -EFAULT; break; } case DIGI_GET_NI_INFO: { struct channel_t *ch; struct ni_info ni; unsigned char mstat = 0; uint board = 0; uint channel = 0; if (copy_from_user(&ni, uarg, sizeof(ni))) return -EFAULT; board = ni.board; channel = ni.channel; /* Verify boundaries on board */ if (board >= dgnc_NumBoards) return -ENODEV; /* Verify boundaries on channel */ if (channel >= dgnc_Board[board]->nasync) return -ENODEV; ch = dgnc_Board[board]->channels[channel]; if (!ch || ch->magic != DGNC_CHANNEL_MAGIC) return -ENODEV; memset(&ni, 0, sizeof(ni)); ni.board = board; ni.channel = channel; spin_lock_irqsave(&ch->ch_lock, flags); mstat = (ch->ch_mostat | ch->ch_mistat); if (mstat & UART_MCR_DTR) { ni.mstat |= TIOCM_DTR; ni.dtr = TIOCM_DTR; } if (mstat & UART_MCR_RTS) { ni.mstat |= TIOCM_RTS; ni.rts = TIOCM_RTS; } if (mstat & UART_MSR_CTS) { ni.mstat |= TIOCM_CTS; ni.cts = TIOCM_CTS; } if (mstat & UART_MSR_RI) { ni.mstat |= TIOCM_RI; ni.ri = TIOCM_RI; } if (mstat & UART_MSR_DCD) { ni.mstat |= TIOCM_CD; ni.dcd = TIOCM_CD; } if (mstat & UART_MSR_DSR) ni.mstat |= TIOCM_DSR; ni.iflag = ch->ch_c_iflag; ni.oflag = ch->ch_c_oflag; ni.cflag = ch->ch_c_cflag; ni.lflag = ch->ch_c_lflag; if (ch->ch_digi.digi_flags & CTSPACE || ch->ch_c_cflag & CRTSCTS) ni.hflow = 1; else ni.hflow = 0; if ((ch->ch_flags & CH_STOPI) || (ch->ch_flags & CH_FORCED_STOPI)) ni.recv_stopped = 1; else ni.recv_stopped = 0; if ((ch->ch_flags & CH_STOP) || (ch->ch_flags & CH_FORCED_STOP)) ni.xmit_stopped = 1; else ni.xmit_stopped = 0; ni.curtx = ch->ch_txcount; ni.currx = ch->ch_rxcount; ni.baud = ch->ch_old_baud; spin_unlock_irqrestore(&ch->ch_lock, flags); if (copy_to_user(uarg, &ni, sizeof(ni))) return -EFAULT; break; } } return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1766_0
crossvul-cpp_data_bad_5049_0
/* * af_llc.c - LLC User Interface SAPs * Description: * Functions in this module are implementation of socket based llc * communications for the Linux operating system. Support of llc class * one and class two is provided via SOCK_DGRAM and SOCK_STREAM * respectively. * * An llc2 connection is (mac + sap), only one llc2 sap connection * is allowed per mac. Though one sap may have multiple mac + sap * connections. * * Copyright (c) 2001 by Jay Schulist <jschlst@samba.org> * 2002-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * This program can be redistributed or modified under the terms of the * GNU General Public License as published by the Free Software Foundation. * This program is distributed without any warranty or implied warranty * of merchantability or fitness for a particular purpose. * * See the GNU General Public License for more details. */ #include <linux/compiler.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/init.h> #include <linux/slab.h> #include <net/llc.h> #include <net/llc_sap.h> #include <net/llc_pdu.h> #include <net/llc_conn.h> #include <net/tcp_states.h> /* remember: uninitialized global data is zeroed because its in .bss */ static u16 llc_ui_sap_last_autoport = LLC_SAP_DYN_START; static u16 llc_ui_sap_link_no_max[256]; static struct sockaddr_llc llc_ui_addrnull; static const struct proto_ops llc_ui_ops; static long llc_ui_wait_for_conn(struct sock *sk, long timeout); static int llc_ui_wait_for_disc(struct sock *sk, long timeout); static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout); #if 0 #define dprintk(args...) printk(KERN_DEBUG args) #else #define dprintk(args...) #endif /* Maybe we'll add some more in the future. */ #define LLC_CMSG_PKTINFO 1 /** * llc_ui_next_link_no - return the next unused link number for a sap * @sap: Address of sap to get link number from. * * Return the next unused link number for a given sap. */ static inline u16 llc_ui_next_link_no(int sap) { return llc_ui_sap_link_no_max[sap]++; } /** * llc_proto_type - return eth protocol for ARP header type * @arphrd: ARP header type. * * Given an ARP header type return the corresponding ethernet protocol. */ static inline __be16 llc_proto_type(u16 arphrd) { return htons(ETH_P_802_2); } /** * llc_ui_addr_null - determines if a address structure is null * @addr: Address to test if null. */ static inline u8 llc_ui_addr_null(struct sockaddr_llc *addr) { return !memcmp(addr, &llc_ui_addrnull, sizeof(*addr)); } /** * llc_ui_header_len - return length of llc header based on operation * @sk: Socket which contains a valid llc socket type. * @addr: Complete sockaddr_llc structure received from the user. * * Provide the length of the llc header depending on what kind of * operation the user would like to perform and the type of socket. * Returns the correct llc header length. */ static inline u8 llc_ui_header_len(struct sock *sk, struct sockaddr_llc *addr) { u8 rc = LLC_PDU_LEN_U; if (addr->sllc_test || addr->sllc_xid) rc = LLC_PDU_LEN_U; else if (sk->sk_type == SOCK_STREAM) rc = LLC_PDU_LEN_I; return rc; } /** * llc_ui_send_data - send data via reliable llc2 connection * @sk: Connection the socket is using. * @skb: Data the user wishes to send. * @noblock: can we block waiting for data? * * Send data via reliable llc2 connection. * Returns 0 upon success, non-zero if action did not succeed. */ static int llc_ui_send_data(struct sock* sk, struct sk_buff *skb, int noblock) { struct llc_sock* llc = llc_sk(sk); int rc = 0; if (unlikely(llc_data_accept_state(llc->state) || llc->remote_busy_flag || llc->p_flag)) { long timeout = sock_sndtimeo(sk, noblock); rc = llc_ui_wait_for_busy_core(sk, timeout); } if (unlikely(!rc)) rc = llc_build_and_send_pkt(sk, skb); return rc; } static void llc_ui_sk_init(struct socket *sock, struct sock *sk) { sock_graft(sk, sock); sk->sk_type = sock->type; sock->ops = &llc_ui_ops; } static struct proto llc_proto = { .name = "LLC", .owner = THIS_MODULE, .obj_size = sizeof(struct llc_sock), .slab_flags = SLAB_DESTROY_BY_RCU, }; /** * llc_ui_create - alloc and init a new llc_ui socket * @net: network namespace (must be default network) * @sock: Socket to initialize and attach allocated sk to. * @protocol: Unused. * @kern: on behalf of kernel or userspace * * Allocate and initialize a new llc_ui socket, validate the user wants a * socket type we have available. * Returns 0 upon success, negative upon failure. */ static int llc_ui_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; int rc = -ESOCKTNOSUPPORT; if (!ns_capable(net->user_ns, CAP_NET_RAW)) return -EPERM; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; if (likely(sock->type == SOCK_DGRAM || sock->type == SOCK_STREAM)) { rc = -ENOMEM; sk = llc_sk_alloc(net, PF_LLC, GFP_KERNEL, &llc_proto, kern); if (sk) { rc = 0; llc_ui_sk_init(sock, sk); } } return rc; } /** * llc_ui_release - shutdown socket * @sock: Socket to release. * * Shutdown and deallocate an existing socket. */ static int llc_ui_release(struct socket *sock) { struct sock *sk = sock->sk; struct llc_sock *llc; if (unlikely(sk == NULL)) goto out; sock_hold(sk); lock_sock(sk); llc = llc_sk(sk); dprintk("%s: closing local(%02X) remote(%02X)\n", __func__, llc->laddr.lsap, llc->daddr.lsap); if (!llc_send_disc(sk)) llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo); if (!sock_flag(sk, SOCK_ZAPPED)) llc_sap_remove_socket(llc->sap, sk); release_sock(sk); if (llc->dev) dev_put(llc->dev); sock_put(sk); llc_sk_free(sk); out: return 0; } /** * llc_ui_autoport - provide dynamically allocate SAP number * * Provide the caller with a dynamically allocated SAP number according * to the rules that are set in this function. Returns: 0, upon failure, * SAP number otherwise. */ static int llc_ui_autoport(void) { struct llc_sap *sap; int i, tries = 0; while (tries < LLC_SAP_DYN_TRIES) { for (i = llc_ui_sap_last_autoport; i < LLC_SAP_DYN_STOP; i += 2) { sap = llc_sap_find(i); if (!sap) { llc_ui_sap_last_autoport = i + 2; goto out; } llc_sap_put(sap); } llc_ui_sap_last_autoport = LLC_SAP_DYN_START; tries++; } i = 0; out: return i; } /** * llc_ui_autobind - automatically bind a socket to a sap * @sock: socket to bind * @addr: address to connect to * * Used by llc_ui_connect and llc_ui_sendmsg when the user hasn't * specifically used llc_ui_bind to bind to an specific address/sap * * Returns: 0 upon success, negative otherwise. */ static int llc_ui_autobind(struct socket *sock, struct sockaddr_llc *addr) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct llc_sap *sap; int rc = -EINVAL; if (!sock_flag(sk, SOCK_ZAPPED)) goto out; rc = -ENODEV; if (sk->sk_bound_dev_if) { llc->dev = dev_get_by_index(&init_net, sk->sk_bound_dev_if); if (llc->dev && addr->sllc_arphrd != llc->dev->type) { dev_put(llc->dev); llc->dev = NULL; } } else llc->dev = dev_getfirstbyhwtype(&init_net, addr->sllc_arphrd); if (!llc->dev) goto out; rc = -EUSERS; llc->laddr.lsap = llc_ui_autoport(); if (!llc->laddr.lsap) goto out; rc = -EBUSY; /* some other network layer is using the sap */ sap = llc_sap_open(llc->laddr.lsap, NULL); if (!sap) goto out; memcpy(llc->laddr.mac, llc->dev->dev_addr, IFHWADDRLEN); memcpy(&llc->addr, addr, sizeof(llc->addr)); /* assign new connection to its SAP */ llc_sap_add_socket(sap, sk); sock_reset_flag(sk, SOCK_ZAPPED); rc = 0; out: return rc; } /** * llc_ui_bind - bind a socket to a specific address. * @sock: Socket to bind an address to. * @uaddr: Address the user wants the socket bound to. * @addrlen: Length of the uaddr structure. * * Bind a socket to a specific address. For llc a user is able to bind to * a specific sap only or mac + sap. * If the user desires to bind to a specific mac + sap, it is possible to * have multiple sap connections via multiple macs. * Bind and autobind for that matter must enforce the correct sap usage * otherwise all hell will break loose. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_bind(struct socket *sock, struct sockaddr *uaddr, int addrlen) { struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct llc_sap *sap; int rc = -EINVAL; dprintk("%s: binding %02X\n", __func__, addr->sllc_sap); if (unlikely(!sock_flag(sk, SOCK_ZAPPED) || addrlen != sizeof(*addr))) goto out; rc = -EAFNOSUPPORT; if (unlikely(addr->sllc_family != AF_LLC)) goto out; rc = -ENODEV; rcu_read_lock(); if (sk->sk_bound_dev_if) { llc->dev = dev_get_by_index_rcu(&init_net, sk->sk_bound_dev_if); if (llc->dev) { if (!addr->sllc_arphrd) addr->sllc_arphrd = llc->dev->type; if (is_zero_ether_addr(addr->sllc_mac)) memcpy(addr->sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); if (addr->sllc_arphrd != llc->dev->type || !ether_addr_equal(addr->sllc_mac, llc->dev->dev_addr)) { rc = -EINVAL; llc->dev = NULL; } } } else llc->dev = dev_getbyhwaddr_rcu(&init_net, addr->sllc_arphrd, addr->sllc_mac); if (llc->dev) dev_hold(llc->dev); rcu_read_unlock(); if (!llc->dev) goto out; if (!addr->sllc_sap) { rc = -EUSERS; addr->sllc_sap = llc_ui_autoport(); if (!addr->sllc_sap) goto out; } sap = llc_sap_find(addr->sllc_sap); if (!sap) { sap = llc_sap_open(addr->sllc_sap, NULL); rc = -EBUSY; /* some other network layer is using the sap */ if (!sap) goto out; } else { struct llc_addr laddr, daddr; struct sock *ask; memset(&laddr, 0, sizeof(laddr)); memset(&daddr, 0, sizeof(daddr)); /* * FIXME: check if the address is multicast, * only SOCK_DGRAM can do this. */ memcpy(laddr.mac, addr->sllc_mac, IFHWADDRLEN); laddr.lsap = addr->sllc_sap; rc = -EADDRINUSE; /* mac + sap clash. */ ask = llc_lookup_established(sap, &daddr, &laddr); if (ask) { sock_put(ask); goto out_put; } } llc->laddr.lsap = addr->sllc_sap; memcpy(llc->laddr.mac, addr->sllc_mac, IFHWADDRLEN); memcpy(&llc->addr, addr, sizeof(llc->addr)); /* assign new connection to its SAP */ llc_sap_add_socket(sap, sk); sock_reset_flag(sk, SOCK_ZAPPED); rc = 0; out_put: llc_sap_put(sap); out: return rc; } /** * llc_ui_shutdown - shutdown a connect llc2 socket. * @sock: Socket to shutdown. * @how: What part of the socket to shutdown. * * Shutdown a connected llc2 socket. Currently this function only supports * shutting down both sends and receives (2), we could probably make this * function such that a user can shutdown only half the connection but not * right now. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int rc = -ENOTCONN; lock_sock(sk); if (unlikely(sk->sk_state != TCP_ESTABLISHED)) goto out; rc = -EINVAL; if (how != 2) goto out; rc = llc_send_disc(sk); if (!rc) rc = llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo); /* Wake up anyone sleeping in poll */ sk->sk_state_change(sk); out: release_sock(sk); return rc; } /** * llc_ui_connect - Connect to a remote llc2 mac + sap. * @sock: Socket which will be connected to the remote destination. * @uaddr: Remote and possibly the local address of the new connection. * @addrlen: Size of uaddr structure. * @flags: Operational flags specified by the user. * * Connect to a remote llc2 mac + sap. The caller must specify the * destination mac and address to connect to. If the user hasn't previously * called bind(2) with a smac the address of the first interface of the * specified arp type will be used. * This function will autobind if user did not previously call bind. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_connect(struct socket *sock, struct sockaddr *uaddr, int addrlen, int flags) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; int rc = -EINVAL; lock_sock(sk); if (unlikely(addrlen != sizeof(*addr))) goto out; rc = -EAFNOSUPPORT; if (unlikely(addr->sllc_family != AF_LLC)) goto out; if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EALREADY; if (unlikely(sock->state == SS_CONNECTING)) goto out; /* bind connection to sap if user hasn't done it. */ if (sock_flag(sk, SOCK_ZAPPED)) { /* bind to sap with null dev, exclusive */ rc = llc_ui_autobind(sock, addr); if (rc) goto out; } llc->daddr.lsap = addr->sllc_sap; memcpy(llc->daddr.mac, addr->sllc_mac, IFHWADDRLEN); sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; llc->link = llc_ui_next_link_no(llc->sap->laddr.lsap); rc = llc_establish_connection(sk, llc->dev->dev_addr, addr->sllc_mac, addr->sllc_sap); if (rc) { dprintk("%s: llc_ui_send_conn failed :-(\n", __func__); sock->state = SS_UNCONNECTED; sk->sk_state = TCP_CLOSE; goto out; } if (sk->sk_state == TCP_SYN_SENT) { const long timeo = sock_sndtimeo(sk, flags & O_NONBLOCK); if (!timeo || !llc_ui_wait_for_conn(sk, timeo)) goto out; rc = sock_intr_errno(timeo); if (signal_pending(current)) goto out; } if (sk->sk_state == TCP_CLOSE) goto sock_error; sock->state = SS_CONNECTED; rc = 0; out: release_sock(sk); return rc; sock_error: rc = sock_error(sk) ? : -ECONNABORTED; sock->state = SS_UNCONNECTED; goto out; } /** * llc_ui_listen - allow a normal socket to accept incoming connections * @sock: Socket to allow incoming connections on. * @backlog: Number of connections to queue. * * Allow a normal socket to accept incoming connections. * Returns 0 upon success, negative otherwise. */ static int llc_ui_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int rc = -EINVAL; lock_sock(sk); if (unlikely(sock->state != SS_UNCONNECTED)) goto out; rc = -EOPNOTSUPP; if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EAGAIN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; rc = 0; if (!(unsigned int)backlog) /* BSDism */ backlog = 1; sk->sk_max_ack_backlog = backlog; if (sk->sk_state != TCP_LISTEN) { sk->sk_ack_backlog = 0; sk->sk_state = TCP_LISTEN; } sk->sk_socket->flags |= __SO_ACCEPTCON; out: release_sock(sk); return rc; } static int llc_ui_wait_for_disc(struct sock *sk, long timeout) { DEFINE_WAIT(wait); int rc = 0; while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk_wait_event(sk, &timeout, sk->sk_state == TCP_CLOSE)) break; rc = -ERESTARTSYS; if (signal_pending(current)) break; rc = -EAGAIN; if (!timeout) break; rc = 0; } finish_wait(sk_sleep(sk), &wait); return rc; } static long llc_ui_wait_for_conn(struct sock *sk, long timeout) { DEFINE_WAIT(wait); while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk_wait_event(sk, &timeout, sk->sk_state != TCP_SYN_SENT)) break; if (signal_pending(current) || !timeout) break; } finish_wait(sk_sleep(sk), &wait); return timeout; } static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout) { DEFINE_WAIT(wait); struct llc_sock *llc = llc_sk(sk); int rc; while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); rc = 0; if (sk_wait_event(sk, &timeout, (sk->sk_shutdown & RCV_SHUTDOWN) || (!llc_data_accept_state(llc->state) && !llc->remote_busy_flag && !llc->p_flag))) break; rc = -ERESTARTSYS; if (signal_pending(current)) break; rc = -EAGAIN; if (!timeout) break; } finish_wait(sk_sleep(sk), &wait); return rc; } static int llc_wait_data(struct sock *sk, long timeo) { int rc; while (1) { /* * POSIX 1003.1g mandates this order. */ rc = sock_error(sk); if (rc) break; rc = 0; if (sk->sk_shutdown & RCV_SHUTDOWN) break; rc = -EAGAIN; if (!timeo) break; rc = sock_intr_errno(timeo); if (signal_pending(current)) break; rc = 0; if (sk_wait_data(sk, &timeo, NULL)) break; } return rc; } static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } } /** * llc_ui_accept - accept a new incoming connection. * @sock: Socket which connections arrive on. * @newsock: Socket to move incoming connection to. * @flags: User specified operational flags. * * Accept a new incoming connection. * Returns 0 upon success, negative otherwise. */ static int llc_ui_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk, *newsk; struct llc_sock *llc, *newllc; struct sk_buff *skb; int rc = -EOPNOTSUPP; dprintk("%s: accepting on %02X\n", __func__, llc_sk(sk)->laddr.lsap); lock_sock(sk); if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EINVAL; if (unlikely(sock->state != SS_UNCONNECTED || sk->sk_state != TCP_LISTEN)) goto out; /* wait for a connection to arrive. */ if (skb_queue_empty(&sk->sk_receive_queue)) { rc = llc_wait_data(sk, sk->sk_rcvtimeo); if (rc) goto out; } dprintk("%s: got a new connection on %02X\n", __func__, llc_sk(sk)->laddr.lsap); skb = skb_dequeue(&sk->sk_receive_queue); rc = -EINVAL; if (!skb->sk) goto frees; rc = 0; newsk = skb->sk; /* attach connection to a new socket. */ llc_ui_sk_init(newsock, newsk); sock_reset_flag(newsk, SOCK_ZAPPED); newsk->sk_state = TCP_ESTABLISHED; newsock->state = SS_CONNECTED; llc = llc_sk(sk); newllc = llc_sk(newsk); memcpy(&newllc->addr, &llc->addr, sizeof(newllc->addr)); newllc->link = llc_ui_next_link_no(newllc->laddr.lsap); /* put original socket back into a clean listen state. */ sk->sk_state = TCP_LISTEN; sk->sk_ack_backlog--; dprintk("%s: ok success on %02X, client on %02X\n", __func__, llc_sk(sk)->addr.sllc_sap, newllc->daddr.lsap); frees: kfree_skb(skb); out: release_sock(sk); return rc; } /** * llc_ui_recvmsg - copy received data to the socket user. * @sock: Socket to copy data from. * @msg: Various user space related information. * @len: Size of user buffer. * @flags: User specified flags. * * Copy received data to the socket user. * Returns non-negative upon success, negative otherwise. */ static int llc_ui_recvmsg(struct socket *sock, struct msghdr *msg, size_t len, int flags) { DECLARE_SOCKADDR(struct sockaddr_llc *, uaddr, msg->msg_name); const int nonblock = flags & MSG_DONTWAIT; struct sk_buff *skb = NULL; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned long cpu_flags; size_t copied = 0; u32 peek_seq = 0; u32 *seq, skb_len; unsigned long used; int target; /* Read at least this many bytes */ long timeo; lock_sock(sk); copied = -ENOTCONN; if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) goto out; timeo = sock_rcvtimeo(sk, nonblock); seq = &llc->copied_seq; if (flags & MSG_PEEK) { peek_seq = llc->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); copied = 0; do { u32 offset; /* * We need to check signals first, to get correct SIGURG * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { if (copied) break; copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } /* Next get a buffer. */ skb = skb_peek(&sk->sk_receive_queue); if (skb) { offset = *seq; goto found_ok_skb; } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || (flags & MSG_PEEK)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* * This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo, NULL); if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = llc->copied_seq; } continue; found_ok_skb: skb_len = skb->len; /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; if (!(flags & MSG_TRUNC)) { int rc = skb_copy_datagram_msg(skb, offset, msg, used); if (rc) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; /* For non stream protcols we get one packet per recvmsg call */ if (sk->sk_type != SOCK_STREAM) goto copy_uaddr; if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } /* Partial read */ if (used + offset < skb_len) continue; } while (len > 0); out: release_sock(sk); return copied; copy_uaddr: if (uaddr != NULL && skb != NULL) { memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); msg->msg_namelen = sizeof(*uaddr); } if (llc_sk(sk)->cmsg_flags) llc_cmsg_rcv(msg, skb); if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } goto out; } /** * llc_ui_sendmsg - Transmit data provided by the socket user. * @sock: Socket to transmit data from. * @msg: Various user related information. * @len: Length of data to transmit. * * Transmit data provided by the socket user. * Returns non-negative upon success, negative otherwise. */ static int llc_ui_sendmsg(struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); DECLARE_SOCKADDR(struct sockaddr_llc *, addr, msg->msg_name); int flags = msg->msg_flags; int noblock = flags & MSG_DONTWAIT; struct sk_buff *skb; size_t size = 0; int rc = -EINVAL, copied = 0, hdrlen; dprintk("%s: sending from %02X to %02X\n", __func__, llc->laddr.lsap, llc->daddr.lsap); lock_sock(sk); if (addr) { if (msg->msg_namelen < sizeof(*addr)) goto release; } else { if (llc_ui_addr_null(&llc->addr)) goto release; addr = &llc->addr; } /* must bind connection to sap if user hasn't done it. */ if (sock_flag(sk, SOCK_ZAPPED)) { /* bind to sap with null dev, exclusive. */ rc = llc_ui_autobind(sock, addr); if (rc) goto release; } hdrlen = llc->dev->hard_header_len + llc_ui_header_len(sk, addr); size = hdrlen + len; if (size > llc->dev->mtu) size = llc->dev->mtu; copied = size - hdrlen; release_sock(sk); skb = sock_alloc_send_skb(sk, size, noblock, &rc); lock_sock(sk); if (!skb) goto release; skb->dev = llc->dev; skb->protocol = llc_proto_type(addr->sllc_arphrd); skb_reserve(skb, hdrlen); rc = memcpy_from_msg(skb_put(skb, copied), msg, copied); if (rc) goto out; if (sk->sk_type == SOCK_DGRAM || addr->sllc_ua) { llc_build_and_send_ui_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } if (addr->sllc_test) { llc_build_and_send_test_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } if (addr->sllc_xid) { llc_build_and_send_xid_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } rc = -ENOPROTOOPT; if (!(sk->sk_type == SOCK_STREAM && !addr->sllc_ua)) goto out; rc = llc_ui_send_data(sk, skb, noblock); out: if (rc) { kfree_skb(skb); release: dprintk("%s: failed sending from %02X to %02X: %d\n", __func__, llc->laddr.lsap, llc->daddr.lsap, rc); } release_sock(sk); return rc ? : copied; } /** * llc_ui_getname - return the address info of a socket * @sock: Socket to get address of. * @uaddr: Address structure to return information. * @uaddrlen: Length of address structure. * @peer: Does user want local or remote address information. * * Return the address information of a socket. */ static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = -EBADF; memset(&sllc, 0, sizeof(sllc)); lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; } /** * llc_ui_ioctl - io controls for PF_LLC * @sock: Socket to get/set info * @cmd: command * @arg: optional argument for cmd * * get/set info on llc sockets */ static int llc_ui_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -ENOIOCTLCMD; } /** * llc_ui_setsockopt - set various connection specific parameters. * @sock: Socket to set options on. * @level: Socket level user is requesting operations on. * @optname: Operation name. * @optval: User provided operation data. * @optlen: Length of optval. * * Set various connection specific parameters. */ static int llc_ui_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned int opt; int rc = -EINVAL; lock_sock(sk); if (unlikely(level != SOL_LLC || optlen != sizeof(int))) goto out; rc = get_user(opt, (int __user *)optval); if (rc) goto out; rc = -EINVAL; switch (optname) { case LLC_OPT_RETRY: if (opt > LLC_OPT_MAX_RETRY) goto out; llc->n2 = opt; break; case LLC_OPT_SIZE: if (opt > LLC_OPT_MAX_SIZE) goto out; llc->n1 = opt; break; case LLC_OPT_ACK_TMR_EXP: if (opt > LLC_OPT_MAX_ACK_TMR_EXP) goto out; llc->ack_timer.expire = opt * HZ; break; case LLC_OPT_P_TMR_EXP: if (opt > LLC_OPT_MAX_P_TMR_EXP) goto out; llc->pf_cycle_timer.expire = opt * HZ; break; case LLC_OPT_REJ_TMR_EXP: if (opt > LLC_OPT_MAX_REJ_TMR_EXP) goto out; llc->rej_sent_timer.expire = opt * HZ; break; case LLC_OPT_BUSY_TMR_EXP: if (opt > LLC_OPT_MAX_BUSY_TMR_EXP) goto out; llc->busy_state_timer.expire = opt * HZ; break; case LLC_OPT_TX_WIN: if (opt > LLC_OPT_MAX_WIN) goto out; llc->k = opt; break; case LLC_OPT_RX_WIN: if (opt > LLC_OPT_MAX_WIN) goto out; llc->rw = opt; break; case LLC_OPT_PKTINFO: if (opt) llc->cmsg_flags |= LLC_CMSG_PKTINFO; else llc->cmsg_flags &= ~LLC_CMSG_PKTINFO; break; default: rc = -ENOPROTOOPT; goto out; } rc = 0; out: release_sock(sk); return rc; } /** * llc_ui_getsockopt - get connection specific socket info * @sock: Socket to get information from. * @level: Socket level user is requesting operations on. * @optname: Operation name. * @optval: Variable to return operation data in. * @optlen: Length of optval. * * Get connection specific socket information. */ static int llc_ui_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int val = 0, len = 0, rc = -EINVAL; lock_sock(sk); if (unlikely(level != SOL_LLC)) goto out; rc = get_user(len, optlen); if (rc) goto out; rc = -EINVAL; if (len != sizeof(int)) goto out; switch (optname) { case LLC_OPT_RETRY: val = llc->n2; break; case LLC_OPT_SIZE: val = llc->n1; break; case LLC_OPT_ACK_TMR_EXP: val = llc->ack_timer.expire / HZ; break; case LLC_OPT_P_TMR_EXP: val = llc->pf_cycle_timer.expire / HZ; break; case LLC_OPT_REJ_TMR_EXP: val = llc->rej_sent_timer.expire / HZ; break; case LLC_OPT_BUSY_TMR_EXP: val = llc->busy_state_timer.expire / HZ; break; case LLC_OPT_TX_WIN: val = llc->k; break; case LLC_OPT_RX_WIN: val = llc->rw; break; case LLC_OPT_PKTINFO: val = (llc->cmsg_flags & LLC_CMSG_PKTINFO) != 0; break; default: rc = -ENOPROTOOPT; goto out; } rc = 0; if (put_user(len, optlen) || copy_to_user(optval, &val, len)) rc = -EFAULT; out: release_sock(sk); return rc; } static const struct net_proto_family llc_ui_family_ops = { .family = PF_LLC, .create = llc_ui_create, .owner = THIS_MODULE, }; static const struct proto_ops llc_ui_ops = { .family = PF_LLC, .owner = THIS_MODULE, .release = llc_ui_release, .bind = llc_ui_bind, .connect = llc_ui_connect, .socketpair = sock_no_socketpair, .accept = llc_ui_accept, .getname = llc_ui_getname, .poll = datagram_poll, .ioctl = llc_ui_ioctl, .listen = llc_ui_listen, .shutdown = llc_ui_shutdown, .setsockopt = llc_ui_setsockopt, .getsockopt = llc_ui_getsockopt, .sendmsg = llc_ui_sendmsg, .recvmsg = llc_ui_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const char llc_proc_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the proc_fs entries\n"; static const char llc_sysctl_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the sysctl entries\n"; static const char llc_sock_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the network family\n"; static int __init llc2_init(void) { int rc = proto_register(&llc_proto, 0); if (rc != 0) goto out; llc_build_offset_table(); llc_station_init(); llc_ui_sap_last_autoport = LLC_SAP_DYN_START; rc = llc_proc_init(); if (rc != 0) { printk(llc_proc_err_msg); goto out_station; } rc = llc_sysctl_init(); if (rc) { printk(llc_sysctl_err_msg); goto out_proc; } rc = sock_register(&llc_ui_family_ops); if (rc) { printk(llc_sock_err_msg); goto out_sysctl; } llc_add_pack(LLC_DEST_SAP, llc_sap_handler); llc_add_pack(LLC_DEST_CONN, llc_conn_handler); out: return rc; out_sysctl: llc_sysctl_exit(); out_proc: llc_proc_exit(); out_station: llc_station_exit(); proto_unregister(&llc_proto); goto out; } static void __exit llc2_exit(void) { llc_station_exit(); llc_remove_pack(LLC_DEST_SAP); llc_remove_pack(LLC_DEST_CONN); sock_unregister(PF_LLC); llc_proc_exit(); llc_sysctl_exit(); proto_unregister(&llc_proto); } module_init(llc2_init); module_exit(llc2_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Procom 1997, Jay Schullist 2001, Arnaldo C. Melo 2001-2003"); MODULE_DESCRIPTION("IEEE 802.2 PF_LLC support"); MODULE_ALIAS_NETPROTO(PF_LLC);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5049_0
crossvul-cpp_data_bad_3270_0
/* * linux/fs/ext4/inode.c * * Copyright (C) 1992, 1993, 1994, 1995 * Remy Card (card@masi.ibp.fr) * Laboratoire MASI - Institut Blaise Pascal * Universite Pierre et Marie Curie (Paris VI) * * from * * linux/fs/minix/inode.c * * Copyright (C) 1991, 1992 Linus Torvalds * * 64-bit file support on 64-bit platforms by Jakub Jelinek * (jj@sunsite.ms.mff.cuni.cz) * * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000 */ #include <linux/fs.h> #include <linux/time.h> #include <linux/highuid.h> #include <linux/pagemap.h> #include <linux/dax.h> #include <linux/quotaops.h> #include <linux/string.h> #include <linux/buffer_head.h> #include <linux/writeback.h> #include <linux/pagevec.h> #include <linux/mpage.h> #include <linux/namei.h> #include <linux/uio.h> #include <linux/bio.h> #include <linux/workqueue.h> #include <linux/kernel.h> #include <linux/printk.h> #include <linux/slab.h> #include <linux/bitops.h> #include "ext4_jbd2.h" #include "xattr.h" #include "acl.h" #include "truncate.h" #include <trace/events/ext4.h> #define MPAGE_DA_EXTENT_TAIL 0x01 static __u32 ext4_inode_csum(struct inode *inode, struct ext4_inode *raw, struct ext4_inode_info *ei) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); __u16 csum_lo; __u16 csum_hi = 0; __u32 csum; csum_lo = le16_to_cpu(raw->i_checksum_lo); raw->i_checksum_lo = 0; if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) { csum_hi = le16_to_cpu(raw->i_checksum_hi); raw->i_checksum_hi = 0; } csum = ext4_chksum(sbi, ei->i_csum_seed, (__u8 *)raw, EXT4_INODE_SIZE(inode->i_sb)); raw->i_checksum_lo = cpu_to_le16(csum_lo); if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) raw->i_checksum_hi = cpu_to_le16(csum_hi); return csum; } static int ext4_inode_csum_verify(struct inode *inode, struct ext4_inode *raw, struct ext4_inode_info *ei) { __u32 provided, calculated; if (EXT4_SB(inode->i_sb)->s_es->s_creator_os != cpu_to_le32(EXT4_OS_LINUX) || !ext4_has_metadata_csum(inode->i_sb)) return 1; provided = le16_to_cpu(raw->i_checksum_lo); calculated = ext4_inode_csum(inode, raw, ei); if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) provided |= ((__u32)le16_to_cpu(raw->i_checksum_hi)) << 16; else calculated &= 0xFFFF; return provided == calculated; } static void ext4_inode_csum_set(struct inode *inode, struct ext4_inode *raw, struct ext4_inode_info *ei) { __u32 csum; if (EXT4_SB(inode->i_sb)->s_es->s_creator_os != cpu_to_le32(EXT4_OS_LINUX) || !ext4_has_metadata_csum(inode->i_sb)) return; csum = ext4_inode_csum(inode, raw, ei); raw->i_checksum_lo = cpu_to_le16(csum & 0xFFFF); if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && EXT4_FITS_IN_INODE(raw, ei, i_checksum_hi)) raw->i_checksum_hi = cpu_to_le16(csum >> 16); } static inline int ext4_begin_ordered_truncate(struct inode *inode, loff_t new_size) { trace_ext4_begin_ordered_truncate(inode, new_size); /* * If jinode is zero, then we never opened the file for * writing, so there's no need to call * jbd2_journal_begin_ordered_truncate() since there's no * outstanding writes we need to flush. */ if (!EXT4_I(inode)->jinode) return 0; return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode), EXT4_I(inode)->jinode, new_size); } static void ext4_invalidatepage(struct page *page, unsigned int offset, unsigned int length); static int __ext4_journalled_writepage(struct page *page, unsigned int len); static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh); static int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents); /* * Test whether an inode is a fast symlink. */ int ext4_inode_is_fast_symlink(struct inode *inode) { int ea_blocks = EXT4_I(inode)->i_file_acl ? EXT4_CLUSTER_SIZE(inode->i_sb) >> 9 : 0; if (ext4_has_inline_data(inode)) return 0; return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0); } /* * Restart the transaction associated with *handle. This does a commit, * so before we call here everything must be consistently dirtied against * this transaction. */ int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode, int nblocks) { int ret; /* * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this * moment, get_block can be called only for blocks inside i_size since * page cache has been already dropped and writes are blocked by * i_mutex. So we can safely drop the i_data_sem here. */ BUG_ON(EXT4_JOURNAL(inode) == NULL); jbd_debug(2, "restarting handle %p\n", handle); up_write(&EXT4_I(inode)->i_data_sem); ret = ext4_journal_restart(handle, nblocks); down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); return ret; } /* * Called at the last iput() if i_nlink is zero. */ void ext4_evict_inode(struct inode *inode) { handle_t *handle; int err; trace_ext4_evict_inode(inode); if (inode->i_nlink) { /* * When journalling data dirty buffers are tracked only in the * journal. So although mm thinks everything is clean and * ready for reaping the inode might still have some pages to * write in the running transaction or waiting to be * checkpointed. Thus calling jbd2_journal_invalidatepage() * (via truncate_inode_pages()) to discard these buffers can * cause data loss. Also even if we did not discard these * buffers, we would have no way to find them after the inode * is reaped and thus user could see stale data if he tries to * read them before the transaction is checkpointed. So be * careful and force everything to disk here... We use * ei->i_datasync_tid to store the newest transaction * containing inode's data. * * Note that directories do not have this problem because they * don't use page cache. */ if (ext4_should_journal_data(inode) && (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode)) && inode->i_ino != EXT4_JOURNAL_INO) { journal_t *journal = EXT4_SB(inode->i_sb)->s_journal; tid_t commit_tid = EXT4_I(inode)->i_datasync_tid; jbd2_complete_transaction(journal, commit_tid); filemap_write_and_wait(&inode->i_data); } truncate_inode_pages_final(&inode->i_data); goto no_delete; } if (is_bad_inode(inode)) goto no_delete; dquot_initialize(inode); if (ext4_should_order_data(inode)) ext4_begin_ordered_truncate(inode, 0); truncate_inode_pages_final(&inode->i_data); /* * Protect us against freezing - iput() caller didn't have to have any * protection against it */ sb_start_intwrite(inode->i_sb); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, ext4_blocks_for_truncate(inode)+3); if (IS_ERR(handle)) { ext4_std_error(inode->i_sb, PTR_ERR(handle)); /* * If we're going to skip the normal cleanup, we still need to * make sure that the in-core orphan linked list is properly * cleaned up. */ ext4_orphan_del(NULL, inode); sb_end_intwrite(inode->i_sb); goto no_delete; } if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_size = 0; err = ext4_mark_inode_dirty(handle, inode); if (err) { ext4_warning(inode->i_sb, "couldn't mark inode dirty (err %d)", err); goto stop_handle; } if (inode->i_blocks) ext4_truncate(inode); /* * ext4_ext_truncate() doesn't reserve any slop when it * restarts journal transactions; therefore there may not be * enough credits left in the handle to remove the inode from * the orphan list and set the dtime field. */ if (!ext4_handle_has_enough_credits(handle, 3)) { err = ext4_journal_extend(handle, 3); if (err > 0) err = ext4_journal_restart(handle, 3); if (err != 0) { ext4_warning(inode->i_sb, "couldn't extend journal (err %d)", err); stop_handle: ext4_journal_stop(handle); ext4_orphan_del(NULL, inode); sb_end_intwrite(inode->i_sb); goto no_delete; } } /* * Kill off the orphan record which ext4_truncate created. * AKPM: I think this can be inside the above `if'. * Note that ext4_orphan_del() has to be able to cope with the * deletion of a non-existent orphan - this is because we don't * know if ext4_truncate() actually created an orphan record. * (Well, we could do this if we need to, but heck - it works) */ ext4_orphan_del(handle, inode); EXT4_I(inode)->i_dtime = get_seconds(); /* * One subtle ordering requirement: if anything has gone wrong * (transaction abort, IO errors, whatever), then we can still * do these next steps (the fs will already have been marked as * having errors), but we can't free the inode if the mark_dirty * fails. */ if (ext4_mark_inode_dirty(handle, inode)) /* If that failed, just do the required in-core inode clear. */ ext4_clear_inode(inode); else ext4_free_inode(handle, inode); ext4_journal_stop(handle); sb_end_intwrite(inode->i_sb); return; no_delete: ext4_clear_inode(inode); /* We must guarantee clearing of inode... */ } #ifdef CONFIG_QUOTA qsize_t *ext4_get_reserved_space(struct inode *inode) { return &EXT4_I(inode)->i_reserved_quota; } #endif /* * Called with i_data_sem down, which is important since we can call * ext4_discard_preallocations() from here. */ void ext4_da_update_reserve_space(struct inode *inode, int used, int quota_claim) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); spin_lock(&ei->i_block_reservation_lock); trace_ext4_da_update_reserve_space(inode, used, quota_claim); if (unlikely(used > ei->i_reserved_data_blocks)) { ext4_warning(inode->i_sb, "%s: ino %lu, used %d " "with only %d reserved data blocks", __func__, inode->i_ino, used, ei->i_reserved_data_blocks); WARN_ON(1); used = ei->i_reserved_data_blocks; } /* Update per-inode reservations */ ei->i_reserved_data_blocks -= used; percpu_counter_sub(&sbi->s_dirtyclusters_counter, used); spin_unlock(&EXT4_I(inode)->i_block_reservation_lock); /* Update quota subsystem for data blocks */ if (quota_claim) dquot_claim_block(inode, EXT4_C2B(sbi, used)); else { /* * We did fallocate with an offset that is already delayed * allocated. So on delayed allocated writeback we should * not re-claim the quota for fallocated blocks. */ dquot_release_reservation_block(inode, EXT4_C2B(sbi, used)); } /* * If we have done all the pending block allocations and if * there aren't any writers on the inode, we can discard the * inode's preallocations. */ if ((ei->i_reserved_data_blocks == 0) && (atomic_read(&inode->i_writecount) == 0)) ext4_discard_preallocations(inode); } static int __check_block_validity(struct inode *inode, const char *func, unsigned int line, struct ext4_map_blocks *map) { if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk, map->m_len)) { ext4_error_inode(inode, func, line, map->m_pblk, "lblock %lu mapped to illegal pblock " "(length %d)", (unsigned long) map->m_lblk, map->m_len); return -EFSCORRUPTED; } return 0; } int ext4_issue_zeroout(struct inode *inode, ext4_lblk_t lblk, ext4_fsblk_t pblk, ext4_lblk_t len) { int ret; if (ext4_encrypted_inode(inode)) return ext4_encrypted_zeroout(inode, lblk, pblk, len); ret = sb_issue_zeroout(inode->i_sb, pblk, len, GFP_NOFS); if (ret > 0) ret = 0; return ret; } #define check_block_validity(inode, map) \ __check_block_validity((inode), __func__, __LINE__, (map)) #ifdef ES_AGGRESSIVE_TEST static void ext4_map_blocks_es_recheck(handle_t *handle, struct inode *inode, struct ext4_map_blocks *es_map, struct ext4_map_blocks *map, int flags) { int retval; map->m_flags = 0; /* * There is a race window that the result is not the same. * e.g. xfstests #223 when dioread_nolock enables. The reason * is that we lookup a block mapping in extent status tree with * out taking i_data_sem. So at the time the unwritten extent * could be converted. */ down_read(&EXT4_I(inode)->i_data_sem); if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { retval = ext4_ext_map_blocks(handle, inode, map, flags & EXT4_GET_BLOCKS_KEEP_SIZE); } else { retval = ext4_ind_map_blocks(handle, inode, map, flags & EXT4_GET_BLOCKS_KEEP_SIZE); } up_read((&EXT4_I(inode)->i_data_sem)); /* * We don't check m_len because extent will be collpased in status * tree. So the m_len might not equal. */ if (es_map->m_lblk != map->m_lblk || es_map->m_flags != map->m_flags || es_map->m_pblk != map->m_pblk) { printk("ES cache assertion failed for inode: %lu " "es_cached ex [%d/%d/%llu/%x] != " "found ex [%d/%d/%llu/%x] retval %d flags %x\n", inode->i_ino, es_map->m_lblk, es_map->m_len, es_map->m_pblk, es_map->m_flags, map->m_lblk, map->m_len, map->m_pblk, map->m_flags, retval, flags); } } #endif /* ES_AGGRESSIVE_TEST */ /* * The ext4_map_blocks() function tries to look up the requested blocks, * and returns if the blocks are already mapped. * * Otherwise it takes the write lock of the i_data_sem and allocate blocks * and store the allocated blocks in the result buffer head and mark it * mapped. * * If file type is extents based, it will call ext4_ext_map_blocks(), * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping * based files * * On success, it returns the number of blocks being mapped or allocated. if * create==0 and the blocks are pre-allocated and unwritten, the resulting @map * is marked as unwritten. If the create == 1, it will mark @map as mapped. * * It returns 0 if plain look up failed (blocks have not been allocated), in * that case, @map is returned as unmapped but we still do fill map->m_len to * indicate the length of a hole starting at map->m_lblk. * * It returns the error in case of allocation failure. */ int ext4_map_blocks(handle_t *handle, struct inode *inode, struct ext4_map_blocks *map, int flags) { struct extent_status es; int retval; int ret = 0; #ifdef ES_AGGRESSIVE_TEST struct ext4_map_blocks orig_map; memcpy(&orig_map, map, sizeof(*map)); #endif map->m_flags = 0; ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u," "logical block %lu\n", inode->i_ino, flags, map->m_len, (unsigned long) map->m_lblk); /* * ext4_map_blocks returns an int, and m_len is an unsigned int */ if (unlikely(map->m_len > INT_MAX)) map->m_len = INT_MAX; /* We can handle the block number less than EXT_MAX_BLOCKS */ if (unlikely(map->m_lblk >= EXT_MAX_BLOCKS)) return -EFSCORRUPTED; /* Lookup extent status tree firstly */ if (ext4_es_lookup_extent(inode, map->m_lblk, &es)) { if (ext4_es_is_written(&es) || ext4_es_is_unwritten(&es)) { map->m_pblk = ext4_es_pblock(&es) + map->m_lblk - es.es_lblk; map->m_flags |= ext4_es_is_written(&es) ? EXT4_MAP_MAPPED : EXT4_MAP_UNWRITTEN; retval = es.es_len - (map->m_lblk - es.es_lblk); if (retval > map->m_len) retval = map->m_len; map->m_len = retval; } else if (ext4_es_is_delayed(&es) || ext4_es_is_hole(&es)) { map->m_pblk = 0; retval = es.es_len - (map->m_lblk - es.es_lblk); if (retval > map->m_len) retval = map->m_len; map->m_len = retval; retval = 0; } else { BUG_ON(1); } #ifdef ES_AGGRESSIVE_TEST ext4_map_blocks_es_recheck(handle, inode, map, &orig_map, flags); #endif goto found; } /* * Try to see if we can get the block without requesting a new * file system block. */ down_read(&EXT4_I(inode)->i_data_sem); if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { retval = ext4_ext_map_blocks(handle, inode, map, flags & EXT4_GET_BLOCKS_KEEP_SIZE); } else { retval = ext4_ind_map_blocks(handle, inode, map, flags & EXT4_GET_BLOCKS_KEEP_SIZE); } if (retval > 0) { unsigned int status; if (unlikely(retval != map->m_len)) { ext4_warning(inode->i_sb, "ES len assertion failed for inode " "%lu: retval %d != map->m_len %d", inode->i_ino, retval, map->m_len); WARN_ON(1); } status = map->m_flags & EXT4_MAP_UNWRITTEN ? EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) && !(status & EXTENT_STATUS_WRITTEN) && ext4_find_delalloc_range(inode, map->m_lblk, map->m_lblk + map->m_len - 1)) status |= EXTENT_STATUS_DELAYED; ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk, status); if (ret < 0) retval = ret; } up_read((&EXT4_I(inode)->i_data_sem)); found: if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) { ret = check_block_validity(inode, map); if (ret != 0) return ret; } /* If it is only a block(s) look up */ if ((flags & EXT4_GET_BLOCKS_CREATE) == 0) return retval; /* * Returns if the blocks have already allocated * * Note that if blocks have been preallocated * ext4_ext_get_block() returns the create = 0 * with buffer head unmapped. */ if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) /* * If we need to convert extent to unwritten * we continue and do the actual work in * ext4_ext_map_blocks() */ if (!(flags & EXT4_GET_BLOCKS_CONVERT_UNWRITTEN)) return retval; /* * Here we clear m_flags because after allocating an new extent, * it will be set again. */ map->m_flags &= ~EXT4_MAP_FLAGS; /* * New blocks allocate and/or writing to unwritten extent * will possibly result in updating i_data, so we take * the write lock of i_data_sem, and call get_block() * with create == 1 flag. */ down_write(&EXT4_I(inode)->i_data_sem); /* * We need to check for EXT4 here because migrate * could have changed the inode type in between */ if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { retval = ext4_ext_map_blocks(handle, inode, map, flags); } else { retval = ext4_ind_map_blocks(handle, inode, map, flags); if (retval > 0 && map->m_flags & EXT4_MAP_NEW) { /* * We allocated new blocks which will result in * i_data's format changing. Force the migrate * to fail by clearing migrate flags */ ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE); } /* * Update reserved blocks/metadata blocks after successful * block allocation which had been deferred till now. We don't * support fallocate for non extent files. So we can update * reserve space here. */ if ((retval > 0) && (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)) ext4_da_update_reserve_space(inode, retval, 1); } if (retval > 0) { unsigned int status; if (unlikely(retval != map->m_len)) { ext4_warning(inode->i_sb, "ES len assertion failed for inode " "%lu: retval %d != map->m_len %d", inode->i_ino, retval, map->m_len); WARN_ON(1); } /* * We have to zeroout blocks before inserting them into extent * status tree. Otherwise someone could look them up there and * use them before they are really zeroed. */ if (flags & EXT4_GET_BLOCKS_ZERO && map->m_flags & EXT4_MAP_MAPPED && map->m_flags & EXT4_MAP_NEW) { ret = ext4_issue_zeroout(inode, map->m_lblk, map->m_pblk, map->m_len); if (ret) { retval = ret; goto out_sem; } } /* * If the extent has been zeroed out, we don't need to update * extent status tree. */ if ((flags & EXT4_GET_BLOCKS_PRE_IO) && ext4_es_lookup_extent(inode, map->m_lblk, &es)) { if (ext4_es_is_written(&es)) goto out_sem; } status = map->m_flags & EXT4_MAP_UNWRITTEN ? EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; if (!(flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE) && !(status & EXTENT_STATUS_WRITTEN) && ext4_find_delalloc_range(inode, map->m_lblk, map->m_lblk + map->m_len - 1)) status |= EXTENT_STATUS_DELAYED; ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk, status); if (ret < 0) { retval = ret; goto out_sem; } } out_sem: up_write((&EXT4_I(inode)->i_data_sem)); if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) { ret = check_block_validity(inode, map); if (ret != 0) return ret; } return retval; } /* * Update EXT4_MAP_FLAGS in bh->b_state. For buffer heads attached to pages * we have to be careful as someone else may be manipulating b_state as well. */ static void ext4_update_bh_state(struct buffer_head *bh, unsigned long flags) { unsigned long old_state; unsigned long new_state; flags &= EXT4_MAP_FLAGS; /* Dummy buffer_head? Set non-atomically. */ if (!bh->b_page) { bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | flags; return; } /* * Someone else may be modifying b_state. Be careful! This is ugly but * once we get rid of using bh as a container for mapping information * to pass to / from get_block functions, this can go away. */ do { old_state = READ_ONCE(bh->b_state); new_state = (old_state & ~EXT4_MAP_FLAGS) | flags; } while (unlikely( cmpxchg(&bh->b_state, old_state, new_state) != old_state)); } static int _ext4_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int flags) { struct ext4_map_blocks map; int ret = 0; if (ext4_has_inline_data(inode)) return -ERANGE; map.m_lblk = iblock; map.m_len = bh->b_size >> inode->i_blkbits; ret = ext4_map_blocks(ext4_journal_current_handle(), inode, &map, flags); if (ret > 0) { map_bh(bh, inode->i_sb, map.m_pblk); ext4_update_bh_state(bh, map.m_flags); bh->b_size = inode->i_sb->s_blocksize * map.m_len; ret = 0; } return ret; } int ext4_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create) { return _ext4_get_block(inode, iblock, bh, create ? EXT4_GET_BLOCKS_CREATE : 0); } /* * Get block function used when preparing for buffered write if we require * creating an unwritten extent if blocks haven't been allocated. The extent * will be converted to written after the IO is complete. */ int ext4_get_block_unwritten(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { ext4_debug("ext4_get_block_unwritten: inode %lu, create flag %d\n", inode->i_ino, create); return _ext4_get_block(inode, iblock, bh_result, EXT4_GET_BLOCKS_IO_CREATE_EXT); } /* Maximum number of blocks we map for direct IO at once. */ #define DIO_MAX_BLOCKS 4096 /* * Get blocks function for the cases that need to start a transaction - * generally difference cases of direct IO and DAX IO. It also handles retries * in case of ENOSPC. */ static int ext4_get_block_trans(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int flags) { int dio_credits; handle_t *handle; int retries = 0; int ret; /* Trim mapping request to maximum we can map at once for DIO */ if (bh_result->b_size >> inode->i_blkbits > DIO_MAX_BLOCKS) bh_result->b_size = DIO_MAX_BLOCKS << inode->i_blkbits; dio_credits = ext4_chunk_trans_blocks(inode, bh_result->b_size >> inode->i_blkbits); retry: handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, dio_credits); if (IS_ERR(handle)) return PTR_ERR(handle); ret = _ext4_get_block(inode, iblock, bh_result, flags); ext4_journal_stop(handle); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry; return ret; } /* Get block function for DIO reads and writes to inodes without extents */ int ext4_dio_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create) { /* We don't expect handle for direct IO */ WARN_ON_ONCE(ext4_journal_current_handle()); if (!create) return _ext4_get_block(inode, iblock, bh, 0); return ext4_get_block_trans(inode, iblock, bh, EXT4_GET_BLOCKS_CREATE); } /* * Get block function for AIO DIO writes when we create unwritten extent if * blocks are not allocated yet. The extent will be converted to written * after IO is complete. */ static int ext4_dio_get_block_unwritten_async(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { int ret; /* We don't expect handle for direct IO */ WARN_ON_ONCE(ext4_journal_current_handle()); ret = ext4_get_block_trans(inode, iblock, bh_result, EXT4_GET_BLOCKS_IO_CREATE_EXT); /* * When doing DIO using unwritten extents, we need io_end to convert * unwritten extents to written on IO completion. We allocate io_end * once we spot unwritten extent and store it in b_private. Generic * DIO code keeps b_private set and furthermore passes the value to * our completion callback in 'private' argument. */ if (!ret && buffer_unwritten(bh_result)) { if (!bh_result->b_private) { ext4_io_end_t *io_end; io_end = ext4_init_io_end(inode, GFP_KERNEL); if (!io_end) return -ENOMEM; bh_result->b_private = io_end; ext4_set_io_unwritten_flag(inode, io_end); } set_buffer_defer_completion(bh_result); } return ret; } /* * Get block function for non-AIO DIO writes when we create unwritten extent if * blocks are not allocated yet. The extent will be converted to written * after IO is complete from ext4_ext_direct_IO() function. */ static int ext4_dio_get_block_unwritten_sync(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { int ret; /* We don't expect handle for direct IO */ WARN_ON_ONCE(ext4_journal_current_handle()); ret = ext4_get_block_trans(inode, iblock, bh_result, EXT4_GET_BLOCKS_IO_CREATE_EXT); /* * Mark inode as having pending DIO writes to unwritten extents. * ext4_ext_direct_IO() checks this flag and converts extents to * written. */ if (!ret && buffer_unwritten(bh_result)) ext4_set_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); return ret; } static int ext4_dio_get_block_overwrite(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { int ret; ext4_debug("ext4_dio_get_block_overwrite: inode %lu, create flag %d\n", inode->i_ino, create); /* We don't expect handle for direct IO */ WARN_ON_ONCE(ext4_journal_current_handle()); ret = _ext4_get_block(inode, iblock, bh_result, 0); /* * Blocks should have been preallocated! ext4_file_write_iter() checks * that. */ WARN_ON_ONCE(!buffer_mapped(bh_result) || buffer_unwritten(bh_result)); return ret; } /* * `handle' can be NULL if create is zero */ struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode, ext4_lblk_t block, int map_flags) { struct ext4_map_blocks map; struct buffer_head *bh; int create = map_flags & EXT4_GET_BLOCKS_CREATE; int err; J_ASSERT(handle != NULL || create == 0); map.m_lblk = block; map.m_len = 1; err = ext4_map_blocks(handle, inode, &map, map_flags); if (err == 0) return create ? ERR_PTR(-ENOSPC) : NULL; if (err < 0) return ERR_PTR(err); bh = sb_getblk(inode->i_sb, map.m_pblk); if (unlikely(!bh)) return ERR_PTR(-ENOMEM); if (map.m_flags & EXT4_MAP_NEW) { J_ASSERT(create != 0); J_ASSERT(handle != NULL); /* * Now that we do not always journal data, we should * keep in mind whether this should always journal the * new buffer as metadata. For now, regular file * writes use ext4_get_block instead, so it's not a * problem. */ lock_buffer(bh); BUFFER_TRACE(bh, "call get_create_access"); err = ext4_journal_get_create_access(handle, bh); if (unlikely(err)) { unlock_buffer(bh); goto errout; } if (!buffer_uptodate(bh)) { memset(bh->b_data, 0, inode->i_sb->s_blocksize); set_buffer_uptodate(bh); } unlock_buffer(bh); BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata"); err = ext4_handle_dirty_metadata(handle, inode, bh); if (unlikely(err)) goto errout; } else BUFFER_TRACE(bh, "not a new buffer"); return bh; errout: brelse(bh); return ERR_PTR(err); } struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode, ext4_lblk_t block, int map_flags) { struct buffer_head *bh; bh = ext4_getblk(handle, inode, block, map_flags); if (IS_ERR(bh)) return bh; if (!bh || buffer_uptodate(bh)) return bh; ll_rw_block(READ | REQ_META | REQ_PRIO, 1, &bh); wait_on_buffer(bh); if (buffer_uptodate(bh)) return bh; put_bh(bh); return ERR_PTR(-EIO); } int ext4_walk_page_buffers(handle_t *handle, struct buffer_head *head, unsigned from, unsigned to, int *partial, int (*fn)(handle_t *handle, struct buffer_head *bh)) { struct buffer_head *bh; unsigned block_start, block_end; unsigned blocksize = head->b_size; int err, ret = 0; struct buffer_head *next; for (bh = head, block_start = 0; ret == 0 && (bh != head || !block_start); block_start = block_end, bh = next) { next = bh->b_this_page; block_end = block_start + blocksize; if (block_end <= from || block_start >= to) { if (partial && !buffer_uptodate(bh)) *partial = 1; continue; } err = (*fn)(handle, bh); if (!ret) ret = err; } return ret; } /* * To preserve ordering, it is essential that the hole instantiation and * the data write be encapsulated in a single transaction. We cannot * close off a transaction and start a new one between the ext4_get_block() * and the commit_write(). So doing the jbd2_journal_start at the start of * prepare_write() is the right place. * * Also, this function can nest inside ext4_writepage(). In that case, we * *know* that ext4_writepage() has generated enough buffer credits to do the * whole page. So we won't block on the journal in that case, which is good, * because the caller may be PF_MEMALLOC. * * By accident, ext4 can be reentered when a transaction is open via * quota file writes. If we were to commit the transaction while thus * reentered, there can be a deadlock - we would be holding a quota * lock, and the commit would never complete if another thread had a * transaction open and was blocking on the quota lock - a ranking * violation. * * So what we do is to rely on the fact that jbd2_journal_stop/journal_start * will _not_ run commit under these circumstances because handle->h_ref * is elevated. We'll still have enough credits for the tiny quotafile * write. */ int do_journal_get_write_access(handle_t *handle, struct buffer_head *bh) { int dirty = buffer_dirty(bh); int ret; if (!buffer_mapped(bh) || buffer_freed(bh)) return 0; /* * __block_write_begin() could have dirtied some buffers. Clean * the dirty bit as jbd2_journal_get_write_access() could complain * otherwise about fs integrity issues. Setting of the dirty bit * by __block_write_begin() isn't a real problem here as we clear * the bit before releasing a page lock and thus writeback cannot * ever write the buffer. */ if (dirty) clear_buffer_dirty(bh); BUFFER_TRACE(bh, "get write access"); ret = ext4_journal_get_write_access(handle, bh); if (!ret && dirty) ret = ext4_handle_dirty_metadata(handle, NULL, bh); return ret; } #ifdef CONFIG_EXT4_FS_ENCRYPTION static int ext4_block_write_begin(struct page *page, loff_t pos, unsigned len, get_block_t *get_block) { unsigned from = pos & (PAGE_SIZE - 1); unsigned to = from + len; struct inode *inode = page->mapping->host; unsigned block_start, block_end; sector_t block; int err = 0; unsigned blocksize = inode->i_sb->s_blocksize; unsigned bbits; struct buffer_head *bh, *head, *wait[2], **wait_bh = wait; bool decrypt = false; BUG_ON(!PageLocked(page)); BUG_ON(from > PAGE_SIZE); BUG_ON(to > PAGE_SIZE); BUG_ON(from > to); if (!page_has_buffers(page)) create_empty_buffers(page, blocksize, 0); head = page_buffers(page); bbits = ilog2(blocksize); block = (sector_t)page->index << (PAGE_SHIFT - bbits); for (bh = head, block_start = 0; bh != head || !block_start; block++, block_start = block_end, bh = bh->b_this_page) { block_end = block_start + blocksize; if (block_end <= from || block_start >= to) { if (PageUptodate(page)) { if (!buffer_uptodate(bh)) set_buffer_uptodate(bh); } continue; } if (buffer_new(bh)) clear_buffer_new(bh); if (!buffer_mapped(bh)) { WARN_ON(bh->b_size != blocksize); err = get_block(inode, block, bh, 1); if (err) break; if (buffer_new(bh)) { unmap_underlying_metadata(bh->b_bdev, bh->b_blocknr); if (PageUptodate(page)) { clear_buffer_new(bh); set_buffer_uptodate(bh); mark_buffer_dirty(bh); continue; } if (block_end > to || block_start < from) zero_user_segments(page, to, block_end, block_start, from); continue; } } if (PageUptodate(page)) { if (!buffer_uptodate(bh)) set_buffer_uptodate(bh); continue; } if (!buffer_uptodate(bh) && !buffer_delay(bh) && !buffer_unwritten(bh) && (block_start < from || block_end > to)) { ll_rw_block(READ, 1, &bh); *wait_bh++ = bh; decrypt = ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode); } } /* * If we issued read requests, let them complete. */ while (wait_bh > wait) { wait_on_buffer(*--wait_bh); if (!buffer_uptodate(*wait_bh)) err = -EIO; } if (unlikely(err)) page_zero_new_buffers(page, from, to); else if (decrypt) err = ext4_decrypt(page); return err; } #endif static int ext4_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { struct inode *inode = mapping->host; int ret, needed_blocks; handle_t *handle; int retries = 0; struct page *page; pgoff_t index; unsigned from, to; trace_ext4_write_begin(inode, pos, len, flags); /* * Reserve one block more for addition to orphan list in case * we allocate blocks but write fails for some reason */ needed_blocks = ext4_writepage_trans_blocks(inode) + 1; index = pos >> PAGE_SHIFT; from = pos & (PAGE_SIZE - 1); to = from + len; if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) { ret = ext4_try_to_write_inline_data(mapping, inode, pos, len, flags, pagep); if (ret < 0) return ret; if (ret == 1) return 0; } /* * grab_cache_page_write_begin() can take a long time if the * system is thrashing due to memory pressure, or if the page * is being written back. So grab it first before we start * the transaction handle. This also allows us to allocate * the page (if needed) without using GFP_NOFS. */ retry_grab: page = grab_cache_page_write_begin(mapping, index, flags); if (!page) return -ENOMEM; unlock_page(page); retry_journal: handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, needed_blocks); if (IS_ERR(handle)) { put_page(page); return PTR_ERR(handle); } lock_page(page); if (page->mapping != mapping) { /* The page got truncated from under us */ unlock_page(page); put_page(page); ext4_journal_stop(handle); goto retry_grab; } /* In case writeback began while the page was unlocked */ wait_for_stable_page(page); #ifdef CONFIG_EXT4_FS_ENCRYPTION if (ext4_should_dioread_nolock(inode)) ret = ext4_block_write_begin(page, pos, len, ext4_get_block_unwritten); else ret = ext4_block_write_begin(page, pos, len, ext4_get_block); #else if (ext4_should_dioread_nolock(inode)) ret = __block_write_begin(page, pos, len, ext4_get_block_unwritten); else ret = __block_write_begin(page, pos, len, ext4_get_block); #endif if (!ret && ext4_should_journal_data(inode)) { ret = ext4_walk_page_buffers(handle, page_buffers(page), from, to, NULL, do_journal_get_write_access); } if (ret) { unlock_page(page); /* * __block_write_begin may have instantiated a few blocks * outside i_size. Trim these off again. Don't need * i_size_read because we hold i_mutex. * * Add inode to orphan list in case we crash before * truncate finishes */ if (pos + len > inode->i_size && ext4_can_truncate(inode)) ext4_orphan_add(handle, inode); ext4_journal_stop(handle); if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might * still be on the orphan list; we need to * make sure the inode is removed from the * orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_journal; put_page(page); return ret; } *pagep = page; return ret; } /* For write_end() in data=journal mode */ static int write_end_fn(handle_t *handle, struct buffer_head *bh) { int ret; if (!buffer_mapped(bh) || buffer_freed(bh)) return 0; set_buffer_uptodate(bh); ret = ext4_handle_dirty_metadata(handle, NULL, bh); clear_buffer_meta(bh); clear_buffer_prio(bh); return ret; } /* * We need to pick up the new inode size which generic_commit_write gave us * `file' can be NULL - eg, when called from page_symlink(). * * ext4 never places buffers on inode->i_mapping->private_list. metadata * buffers are managed internally. */ static int ext4_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { handle_t *handle = ext4_journal_current_handle(); struct inode *inode = mapping->host; loff_t old_size = inode->i_size; int ret = 0, ret2; int i_size_changed = 0; trace_ext4_write_end(inode, pos, len, copied); if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) { ret = ext4_jbd2_file_inode(handle, inode); if (ret) { unlock_page(page); put_page(page); goto errout; } } if (ext4_has_inline_data(inode)) { ret = ext4_write_inline_data_end(inode, pos, len, copied, page); if (ret < 0) goto errout; copied = ret; } else copied = block_write_end(file, mapping, pos, len, copied, page, fsdata); /* * it's important to update i_size while still holding page lock: * page writeout could otherwise come in and zero beyond i_size. */ i_size_changed = ext4_update_inode_size(inode, pos + copied); unlock_page(page); put_page(page); if (old_size < pos) pagecache_isize_extended(inode, old_size, pos); /* * Don't mark the inode dirty under page lock. First, it unnecessarily * makes the holding time of page lock longer. Second, it forces lock * ordering of page lock and transaction start for journaling * filesystems. */ if (i_size_changed) ext4_mark_inode_dirty(handle, inode); if (pos + len > inode->i_size && ext4_can_truncate(inode)) /* if we have allocated more blocks and copied * less. We will have blocks allocated outside * inode->i_size. So truncate them */ ext4_orphan_add(handle, inode); errout: ret2 = ext4_journal_stop(handle); if (!ret) ret = ret2; if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be * on the orphan list; we need to make sure the inode * is removed from the orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } return ret ? ret : copied; } /* * This is a private version of page_zero_new_buffers() which doesn't * set the buffer to be dirty, since in data=journalled mode we need * to call ext4_handle_dirty_metadata() instead. */ static void zero_new_buffers(struct page *page, unsigned from, unsigned to) { unsigned int block_start = 0, block_end; struct buffer_head *head, *bh; bh = head = page_buffers(page); do { block_end = block_start + bh->b_size; if (buffer_new(bh)) { if (block_end > from && block_start < to) { if (!PageUptodate(page)) { unsigned start, size; start = max(from, block_start); size = min(to, block_end) - start; zero_user(page, start, size); set_buffer_uptodate(bh); } clear_buffer_new(bh); } } block_start = block_end; bh = bh->b_this_page; } while (bh != head); } static int ext4_journalled_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { handle_t *handle = ext4_journal_current_handle(); struct inode *inode = mapping->host; loff_t old_size = inode->i_size; int ret = 0, ret2; int partial = 0; unsigned from, to; int size_changed = 0; trace_ext4_journalled_write_end(inode, pos, len, copied); from = pos & (PAGE_SIZE - 1); to = from + len; BUG_ON(!ext4_handle_valid(handle)); if (ext4_has_inline_data(inode)) copied = ext4_write_inline_data_end(inode, pos, len, copied, page); else { if (copied < len) { if (!PageUptodate(page)) copied = 0; zero_new_buffers(page, from+copied, to); } ret = ext4_walk_page_buffers(handle, page_buffers(page), from, to, &partial, write_end_fn); if (!partial) SetPageUptodate(page); } size_changed = ext4_update_inode_size(inode, pos + copied); ext4_set_inode_state(inode, EXT4_STATE_JDATA); EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid; unlock_page(page); put_page(page); if (old_size < pos) pagecache_isize_extended(inode, old_size, pos); if (size_changed) { ret2 = ext4_mark_inode_dirty(handle, inode); if (!ret) ret = ret2; } if (pos + len > inode->i_size && ext4_can_truncate(inode)) /* if we have allocated more blocks and copied * less. We will have blocks allocated outside * inode->i_size. So truncate them */ ext4_orphan_add(handle, inode); ret2 = ext4_journal_stop(handle); if (!ret) ret = ret2; if (pos + len > inode->i_size) { ext4_truncate_failed_write(inode); /* * If truncate failed early the inode might still be * on the orphan list; we need to make sure the inode * is removed from the orphan list in that case. */ if (inode->i_nlink) ext4_orphan_del(NULL, inode); } return ret ? ret : copied; } /* * Reserve space for a single cluster */ static int ext4_da_reserve_space(struct inode *inode) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); int ret; /* * We will charge metadata quota at writeout time; this saves * us from metadata over-estimation, though we may go over by * a small amount in the end. Here we just reserve for data. */ ret = dquot_reserve_block(inode, EXT4_C2B(sbi, 1)); if (ret) return ret; spin_lock(&ei->i_block_reservation_lock); if (ext4_claim_free_clusters(sbi, 1, 0)) { spin_unlock(&ei->i_block_reservation_lock); dquot_release_reservation_block(inode, EXT4_C2B(sbi, 1)); return -ENOSPC; } ei->i_reserved_data_blocks++; trace_ext4_da_reserve_space(inode); spin_unlock(&ei->i_block_reservation_lock); return 0; /* success */ } static void ext4_da_release_space(struct inode *inode, int to_free) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct ext4_inode_info *ei = EXT4_I(inode); if (!to_free) return; /* Nothing to release, exit */ spin_lock(&EXT4_I(inode)->i_block_reservation_lock); trace_ext4_da_release_space(inode, to_free); if (unlikely(to_free > ei->i_reserved_data_blocks)) { /* * if there aren't enough reserved blocks, then the * counter is messed up somewhere. Since this * function is called from invalidate page, it's * harmless to return without any action. */ ext4_warning(inode->i_sb, "ext4_da_release_space: " "ino %lu, to_free %d with only %d reserved " "data blocks", inode->i_ino, to_free, ei->i_reserved_data_blocks); WARN_ON(1); to_free = ei->i_reserved_data_blocks; } ei->i_reserved_data_blocks -= to_free; /* update fs dirty data blocks counter */ percpu_counter_sub(&sbi->s_dirtyclusters_counter, to_free); spin_unlock(&EXT4_I(inode)->i_block_reservation_lock); dquot_release_reservation_block(inode, EXT4_C2B(sbi, to_free)); } static void ext4_da_page_release_reservation(struct page *page, unsigned int offset, unsigned int length) { int to_release = 0, contiguous_blks = 0; struct buffer_head *head, *bh; unsigned int curr_off = 0; struct inode *inode = page->mapping->host; struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); unsigned int stop = offset + length; int num_clusters; ext4_fsblk_t lblk; BUG_ON(stop > PAGE_SIZE || stop < length); head = page_buffers(page); bh = head; do { unsigned int next_off = curr_off + bh->b_size; if (next_off > stop) break; if ((offset <= curr_off) && (buffer_delay(bh))) { to_release++; contiguous_blks++; clear_buffer_delay(bh); } else if (contiguous_blks) { lblk = page->index << (PAGE_SHIFT - inode->i_blkbits); lblk += (curr_off >> inode->i_blkbits) - contiguous_blks; ext4_es_remove_extent(inode, lblk, contiguous_blks); contiguous_blks = 0; } curr_off = next_off; } while ((bh = bh->b_this_page) != head); if (contiguous_blks) { lblk = page->index << (PAGE_SHIFT - inode->i_blkbits); lblk += (curr_off >> inode->i_blkbits) - contiguous_blks; ext4_es_remove_extent(inode, lblk, contiguous_blks); } /* If we have released all the blocks belonging to a cluster, then we * need to release the reserved space for that cluster. */ num_clusters = EXT4_NUM_B2C(sbi, to_release); while (num_clusters > 0) { lblk = (page->index << (PAGE_SHIFT - inode->i_blkbits)) + ((num_clusters - 1) << sbi->s_cluster_bits); if (sbi->s_cluster_ratio == 1 || !ext4_find_delalloc_cluster(inode, lblk)) ext4_da_release_space(inode, 1); num_clusters--; } } /* * Delayed allocation stuff */ struct mpage_da_data { struct inode *inode; struct writeback_control *wbc; pgoff_t first_page; /* The first page to write */ pgoff_t next_page; /* Current page to examine */ pgoff_t last_page; /* Last page to examine */ /* * Extent to map - this can be after first_page because that can be * fully mapped. We somewhat abuse m_flags to store whether the extent * is delalloc or unwritten. */ struct ext4_map_blocks map; struct ext4_io_submit io_submit; /* IO submission data */ }; static void mpage_release_unused_pages(struct mpage_da_data *mpd, bool invalidate) { int nr_pages, i; pgoff_t index, end; struct pagevec pvec; struct inode *inode = mpd->inode; struct address_space *mapping = inode->i_mapping; /* This is necessary when next_page == 0. */ if (mpd->first_page >= mpd->next_page) return; index = mpd->first_page; end = mpd->next_page - 1; if (invalidate) { ext4_lblk_t start, last; start = index << (PAGE_SHIFT - inode->i_blkbits); last = end << (PAGE_SHIFT - inode->i_blkbits); ext4_es_remove_extent(inode, start, last - start + 1); } pagevec_init(&pvec, 0); while (index <= end) { nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; if (page->index > end) break; BUG_ON(!PageLocked(page)); BUG_ON(PageWriteback(page)); if (invalidate) { block_invalidatepage(page, 0, PAGE_SIZE); ClearPageUptodate(page); } unlock_page(page); } index = pvec.pages[nr_pages - 1]->index + 1; pagevec_release(&pvec); } } static void ext4_print_free_blocks(struct inode *inode) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); struct super_block *sb = inode->i_sb; struct ext4_inode_info *ei = EXT4_I(inode); ext4_msg(sb, KERN_CRIT, "Total free blocks count %lld", EXT4_C2B(EXT4_SB(inode->i_sb), ext4_count_free_clusters(sb))); ext4_msg(sb, KERN_CRIT, "Free/Dirty block details"); ext4_msg(sb, KERN_CRIT, "free_blocks=%lld", (long long) EXT4_C2B(EXT4_SB(sb), percpu_counter_sum(&sbi->s_freeclusters_counter))); ext4_msg(sb, KERN_CRIT, "dirty_blocks=%lld", (long long) EXT4_C2B(EXT4_SB(sb), percpu_counter_sum(&sbi->s_dirtyclusters_counter))); ext4_msg(sb, KERN_CRIT, "Block reservation details"); ext4_msg(sb, KERN_CRIT, "i_reserved_data_blocks=%u", ei->i_reserved_data_blocks); return; } static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh) { return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh); } /* * This function is grabs code from the very beginning of * ext4_map_blocks, but assumes that the caller is from delayed write * time. This function looks up the requested blocks and sets the * buffer delay bit under the protection of i_data_sem. */ static int ext4_da_map_blocks(struct inode *inode, sector_t iblock, struct ext4_map_blocks *map, struct buffer_head *bh) { struct extent_status es; int retval; sector_t invalid_block = ~((sector_t) 0xffff); #ifdef ES_AGGRESSIVE_TEST struct ext4_map_blocks orig_map; memcpy(&orig_map, map, sizeof(*map)); #endif if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es)) invalid_block = ~0; map->m_flags = 0; ext_debug("ext4_da_map_blocks(): inode %lu, max_blocks %u," "logical block %lu\n", inode->i_ino, map->m_len, (unsigned long) map->m_lblk); /* Lookup extent status tree firstly */ if (ext4_es_lookup_extent(inode, iblock, &es)) { if (ext4_es_is_hole(&es)) { retval = 0; down_read(&EXT4_I(inode)->i_data_sem); goto add_delayed; } /* * Delayed extent could be allocated by fallocate. * So we need to check it. */ if (ext4_es_is_delayed(&es) && !ext4_es_is_unwritten(&es)) { map_bh(bh, inode->i_sb, invalid_block); set_buffer_new(bh); set_buffer_delay(bh); return 0; } map->m_pblk = ext4_es_pblock(&es) + iblock - es.es_lblk; retval = es.es_len - (iblock - es.es_lblk); if (retval > map->m_len) retval = map->m_len; map->m_len = retval; if (ext4_es_is_written(&es)) map->m_flags |= EXT4_MAP_MAPPED; else if (ext4_es_is_unwritten(&es)) map->m_flags |= EXT4_MAP_UNWRITTEN; else BUG_ON(1); #ifdef ES_AGGRESSIVE_TEST ext4_map_blocks_es_recheck(NULL, inode, map, &orig_map, 0); #endif return retval; } /* * Try to see if we can get the block without requesting a new * file system block. */ down_read(&EXT4_I(inode)->i_data_sem); if (ext4_has_inline_data(inode)) retval = 0; else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) retval = ext4_ext_map_blocks(NULL, inode, map, 0); else retval = ext4_ind_map_blocks(NULL, inode, map, 0); add_delayed: if (retval == 0) { int ret; /* * XXX: __block_prepare_write() unmaps passed block, * is it OK? */ /* * If the block was allocated from previously allocated cluster, * then we don't need to reserve it again. However we still need * to reserve metadata for every block we're going to write. */ if (EXT4_SB(inode->i_sb)->s_cluster_ratio == 1 || !ext4_find_delalloc_cluster(inode, map->m_lblk)) { ret = ext4_da_reserve_space(inode); if (ret) { /* not enough space to reserve */ retval = ret; goto out_unlock; } } ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len, ~0, EXTENT_STATUS_DELAYED); if (ret) { retval = ret; goto out_unlock; } map_bh(bh, inode->i_sb, invalid_block); set_buffer_new(bh); set_buffer_delay(bh); } else if (retval > 0) { int ret; unsigned int status; if (unlikely(retval != map->m_len)) { ext4_warning(inode->i_sb, "ES len assertion failed for inode " "%lu: retval %d != map->m_len %d", inode->i_ino, retval, map->m_len); WARN_ON(1); } status = map->m_flags & EXT4_MAP_UNWRITTEN ? EXTENT_STATUS_UNWRITTEN : EXTENT_STATUS_WRITTEN; ret = ext4_es_insert_extent(inode, map->m_lblk, map->m_len, map->m_pblk, status); if (ret != 0) retval = ret; } out_unlock: up_read((&EXT4_I(inode)->i_data_sem)); return retval; } /* * This is a special get_block_t callback which is used by * ext4_da_write_begin(). It will either return mapped block or * reserve space for a single block. * * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set. * We also have b_blocknr = -1 and b_bdev initialized properly * * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set. * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev * initialized properly. */ int ext4_da_get_block_prep(struct inode *inode, sector_t iblock, struct buffer_head *bh, int create) { struct ext4_map_blocks map; int ret = 0; BUG_ON(create == 0); BUG_ON(bh->b_size != inode->i_sb->s_blocksize); map.m_lblk = iblock; map.m_len = 1; /* * first, we need to know whether the block is allocated already * preallocated blocks are unmapped but should treated * the same as allocated blocks. */ ret = ext4_da_map_blocks(inode, iblock, &map, bh); if (ret <= 0) return ret; map_bh(bh, inode->i_sb, map.m_pblk); ext4_update_bh_state(bh, map.m_flags); if (buffer_unwritten(bh)) { /* A delayed write to unwritten bh should be marked * new and mapped. Mapped ensures that we don't do * get_block multiple times when we write to the same * offset and new ensures that we do proper zero out * for partial write. */ set_buffer_new(bh); set_buffer_mapped(bh); } return 0; } static int bget_one(handle_t *handle, struct buffer_head *bh) { get_bh(bh); return 0; } static int bput_one(handle_t *handle, struct buffer_head *bh) { put_bh(bh); return 0; } static int __ext4_journalled_writepage(struct page *page, unsigned int len) { struct address_space *mapping = page->mapping; struct inode *inode = mapping->host; struct buffer_head *page_bufs = NULL; handle_t *handle = NULL; int ret = 0, err = 0; int inline_data = ext4_has_inline_data(inode); struct buffer_head *inode_bh = NULL; ClearPageChecked(page); if (inline_data) { BUG_ON(page->index != 0); BUG_ON(len > ext4_get_max_inline_size(inode)); inode_bh = ext4_journalled_write_inline_data(inode, len, page); if (inode_bh == NULL) goto out; } else { page_bufs = page_buffers(page); if (!page_bufs) { BUG(); goto out; } ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one); } /* * We need to release the page lock before we start the * journal, so grab a reference so the page won't disappear * out from under us. */ get_page(page); unlock_page(page); handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, ext4_writepage_trans_blocks(inode)); if (IS_ERR(handle)) { ret = PTR_ERR(handle); put_page(page); goto out_no_pagelock; } BUG_ON(!ext4_handle_valid(handle)); lock_page(page); put_page(page); if (page->mapping != mapping) { /* The page got truncated from under us */ ext4_journal_stop(handle); ret = 0; goto out; } if (inline_data) { BUFFER_TRACE(inode_bh, "get write access"); ret = ext4_journal_get_write_access(handle, inode_bh); err = ext4_handle_dirty_metadata(handle, inode, inode_bh); } else { ret = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL, do_journal_get_write_access); err = ext4_walk_page_buffers(handle, page_bufs, 0, len, NULL, write_end_fn); } if (ret == 0) ret = err; EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid; err = ext4_journal_stop(handle); if (!ret) ret = err; if (!ext4_has_inline_data(inode)) ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL, bput_one); ext4_set_inode_state(inode, EXT4_STATE_JDATA); out: unlock_page(page); out_no_pagelock: brelse(inode_bh); return ret; } /* * Note that we don't need to start a transaction unless we're journaling data * because we should have holes filled from ext4_page_mkwrite(). We even don't * need to file the inode to the transaction's list in ordered mode because if * we are writing back data added by write(), the inode is already there and if * we are writing back data modified via mmap(), no one guarantees in which * transaction the data will hit the disk. In case we are journaling data, we * cannot start transaction directly because transaction start ranks above page * lock so we have to do some magic. * * This function can get called via... * - ext4_writepages after taking page lock (have journal handle) * - journal_submit_inode_data_buffers (no journal handle) * - shrink_page_list via the kswapd/direct reclaim (no journal handle) * - grab_page_cache when doing write_begin (have journal handle) * * We don't do any block allocation in this function. If we have page with * multiple blocks we need to write those buffer_heads that are mapped. This * is important for mmaped based write. So if we do with blocksize 1K * truncate(f, 1024); * a = mmap(f, 0, 4096); * a[0] = 'a'; * truncate(f, 4096); * we have in the page first buffer_head mapped via page_mkwrite call back * but other buffer_heads would be unmapped but dirty (dirty done via the * do_wp_page). So writepage should write the first block. If we modify * the mmap area beyond 1024 we will again get a page_fault and the * page_mkwrite callback will do the block allocation and mark the * buffer_heads mapped. * * We redirty the page if we have any buffer_heads that is either delay or * unwritten in the page. * * We can get recursively called as show below. * * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() -> * ext4_writepage() * * But since we don't do any block allocation we should not deadlock. * Page also have the dirty flag cleared so we don't get recurive page_lock. */ static int ext4_writepage(struct page *page, struct writeback_control *wbc) { int ret = 0; loff_t size; unsigned int len; struct buffer_head *page_bufs = NULL; struct inode *inode = page->mapping->host; struct ext4_io_submit io_submit; bool keep_towrite = false; trace_ext4_writepage(page); size = i_size_read(inode); if (page->index == size >> PAGE_SHIFT) len = size & ~PAGE_MASK; else len = PAGE_SIZE; page_bufs = page_buffers(page); /* * We cannot do block allocation or other extent handling in this * function. If there are buffers needing that, we have to redirty * the page. But we may reach here when we do a journal commit via * journal_submit_inode_data_buffers() and in that case we must write * allocated buffers to achieve data=ordered mode guarantees. * * Also, if there is only one buffer per page (the fs block * size == the page size), if one buffer needs block * allocation or needs to modify the extent tree to clear the * unwritten flag, we know that the page can't be written at * all, so we might as well refuse the write immediately. * Unfortunately if the block size != page size, we can't as * easily detect this case using ext4_walk_page_buffers(), but * for the extremely common case, this is an optimization that * skips a useless round trip through ext4_bio_write_page(). */ if (ext4_walk_page_buffers(NULL, page_bufs, 0, len, NULL, ext4_bh_delay_or_unwritten)) { redirty_page_for_writepage(wbc, page); if ((current->flags & PF_MEMALLOC) || (inode->i_sb->s_blocksize == PAGE_SIZE)) { /* * For memory cleaning there's no point in writing only * some buffers. So just bail out. Warn if we came here * from direct reclaim. */ WARN_ON_ONCE((current->flags & (PF_MEMALLOC|PF_KSWAPD)) == PF_MEMALLOC); unlock_page(page); return 0; } keep_towrite = true; } if (PageChecked(page) && ext4_should_journal_data(inode)) /* * It's mmapped pagecache. Add buffers and journal it. There * doesn't seem much point in redirtying the page here. */ return __ext4_journalled_writepage(page, len); ext4_io_submit_init(&io_submit, wbc); io_submit.io_end = ext4_init_io_end(inode, GFP_NOFS); if (!io_submit.io_end) { redirty_page_for_writepage(wbc, page); unlock_page(page); return -ENOMEM; } ret = ext4_bio_write_page(&io_submit, page, len, wbc, keep_towrite); ext4_io_submit(&io_submit); /* Drop io_end reference we got from init */ ext4_put_io_end_defer(io_submit.io_end); return ret; } static int mpage_submit_page(struct mpage_da_data *mpd, struct page *page) { int len; loff_t size = i_size_read(mpd->inode); int err; BUG_ON(page->index != mpd->first_page); if (page->index == size >> PAGE_SHIFT) len = size & ~PAGE_MASK; else len = PAGE_SIZE; clear_page_dirty_for_io(page); err = ext4_bio_write_page(&mpd->io_submit, page, len, mpd->wbc, false); if (!err) mpd->wbc->nr_to_write--; mpd->first_page++; return err; } #define BH_FLAGS ((1 << BH_Unwritten) | (1 << BH_Delay)) /* * mballoc gives us at most this number of blocks... * XXX: That seems to be only a limitation of ext4_mb_normalize_request(). * The rest of mballoc seems to handle chunks up to full group size. */ #define MAX_WRITEPAGES_EXTENT_LEN 2048 /* * mpage_add_bh_to_extent - try to add bh to extent of blocks to map * * @mpd - extent of blocks * @lblk - logical number of the block in the file * @bh - buffer head we want to add to the extent * * The function is used to collect contig. blocks in the same state. If the * buffer doesn't require mapping for writeback and we haven't started the * extent of buffers to map yet, the function returns 'true' immediately - the * caller can write the buffer right away. Otherwise the function returns true * if the block has been added to the extent, false if the block couldn't be * added. */ static bool mpage_add_bh_to_extent(struct mpage_da_data *mpd, ext4_lblk_t lblk, struct buffer_head *bh) { struct ext4_map_blocks *map = &mpd->map; /* Buffer that doesn't need mapping for writeback? */ if (!buffer_dirty(bh) || !buffer_mapped(bh) || (!buffer_delay(bh) && !buffer_unwritten(bh))) { /* So far no extent to map => we write the buffer right away */ if (map->m_len == 0) return true; return false; } /* First block in the extent? */ if (map->m_len == 0) { map->m_lblk = lblk; map->m_len = 1; map->m_flags = bh->b_state & BH_FLAGS; return true; } /* Don't go larger than mballoc is willing to allocate */ if (map->m_len >= MAX_WRITEPAGES_EXTENT_LEN) return false; /* Can we merge the block to our big extent? */ if (lblk == map->m_lblk + map->m_len && (bh->b_state & BH_FLAGS) == map->m_flags) { map->m_len++; return true; } return false; } /* * mpage_process_page_bufs - submit page buffers for IO or add them to extent * * @mpd - extent of blocks for mapping * @head - the first buffer in the page * @bh - buffer we should start processing from * @lblk - logical number of the block in the file corresponding to @bh * * Walk through page buffers from @bh upto @head (exclusive) and either submit * the page for IO if all buffers in this page were mapped and there's no * accumulated extent of buffers to map or add buffers in the page to the * extent of buffers to map. The function returns 1 if the caller can continue * by processing the next page, 0 if it should stop adding buffers to the * extent to map because we cannot extend it anymore. It can also return value * < 0 in case of error during IO submission. */ static int mpage_process_page_bufs(struct mpage_da_data *mpd, struct buffer_head *head, struct buffer_head *bh, ext4_lblk_t lblk) { struct inode *inode = mpd->inode; int err; ext4_lblk_t blocks = (i_size_read(inode) + (1 << inode->i_blkbits) - 1) >> inode->i_blkbits; do { BUG_ON(buffer_locked(bh)); if (lblk >= blocks || !mpage_add_bh_to_extent(mpd, lblk, bh)) { /* Found extent to map? */ if (mpd->map.m_len) return 0; /* Everything mapped so far and we hit EOF */ break; } } while (lblk++, (bh = bh->b_this_page) != head); /* So far everything mapped? Submit the page for IO. */ if (mpd->map.m_len == 0) { err = mpage_submit_page(mpd, head->b_page); if (err < 0) return err; } return lblk < blocks; } /* * mpage_map_buffers - update buffers corresponding to changed extent and * submit fully mapped pages for IO * * @mpd - description of extent to map, on return next extent to map * * Scan buffers corresponding to changed extent (we expect corresponding pages * to be already locked) and update buffer state according to new extent state. * We map delalloc buffers to their physical location, clear unwritten bits, * and mark buffers as uninit when we perform writes to unwritten extents * and do extent conversion after IO is finished. If the last page is not fully * mapped, we update @map to the next extent in the last page that needs * mapping. Otherwise we submit the page for IO. */ static int mpage_map_and_submit_buffers(struct mpage_da_data *mpd) { struct pagevec pvec; int nr_pages, i; struct inode *inode = mpd->inode; struct buffer_head *head, *bh; int bpp_bits = PAGE_SHIFT - inode->i_blkbits; pgoff_t start, end; ext4_lblk_t lblk; sector_t pblock; int err; start = mpd->map.m_lblk >> bpp_bits; end = (mpd->map.m_lblk + mpd->map.m_len - 1) >> bpp_bits; lblk = start << bpp_bits; pblock = mpd->map.m_pblk; pagevec_init(&pvec, 0); while (start <= end) { nr_pages = pagevec_lookup(&pvec, inode->i_mapping, start, PAGEVEC_SIZE); if (nr_pages == 0) break; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; if (page->index > end) break; /* Up to 'end' pages must be contiguous */ BUG_ON(page->index != start); bh = head = page_buffers(page); do { if (lblk < mpd->map.m_lblk) continue; if (lblk >= mpd->map.m_lblk + mpd->map.m_len) { /* * Buffer after end of mapped extent. * Find next buffer in the page to map. */ mpd->map.m_len = 0; mpd->map.m_flags = 0; /* * FIXME: If dioread_nolock supports * blocksize < pagesize, we need to make * sure we add size mapped so far to * io_end->size as the following call * can submit the page for IO. */ err = mpage_process_page_bufs(mpd, head, bh, lblk); pagevec_release(&pvec); if (err > 0) err = 0; return err; } if (buffer_delay(bh)) { clear_buffer_delay(bh); bh->b_blocknr = pblock++; } clear_buffer_unwritten(bh); } while (lblk++, (bh = bh->b_this_page) != head); /* * FIXME: This is going to break if dioread_nolock * supports blocksize < pagesize as we will try to * convert potentially unmapped parts of inode. */ mpd->io_submit.io_end->size += PAGE_SIZE; /* Page fully mapped - let IO run! */ err = mpage_submit_page(mpd, page); if (err < 0) { pagevec_release(&pvec); return err; } start++; } pagevec_release(&pvec); } /* Extent fully mapped and matches with page boundary. We are done. */ mpd->map.m_len = 0; mpd->map.m_flags = 0; return 0; } static int mpage_map_one_extent(handle_t *handle, struct mpage_da_data *mpd) { struct inode *inode = mpd->inode; struct ext4_map_blocks *map = &mpd->map; int get_blocks_flags; int err, dioread_nolock; trace_ext4_da_write_pages_extent(inode, map); /* * Call ext4_map_blocks() to allocate any delayed allocation blocks, or * to convert an unwritten extent to be initialized (in the case * where we have written into one or more preallocated blocks). It is * possible that we're going to need more metadata blocks than * previously reserved. However we must not fail because we're in * writeback and there is nothing we can do about it so it might result * in data loss. So use reserved blocks to allocate metadata if * possible. * * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE if * the blocks in question are delalloc blocks. This indicates * that the blocks and quotas has already been checked when * the data was copied into the page cache. */ get_blocks_flags = EXT4_GET_BLOCKS_CREATE | EXT4_GET_BLOCKS_METADATA_NOFAIL; dioread_nolock = ext4_should_dioread_nolock(inode); if (dioread_nolock) get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT; if (map->m_flags & (1 << BH_Delay)) get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE; err = ext4_map_blocks(handle, inode, map, get_blocks_flags); if (err < 0) return err; if (dioread_nolock && (map->m_flags & EXT4_MAP_UNWRITTEN)) { if (!mpd->io_submit.io_end->handle && ext4_handle_valid(handle)) { mpd->io_submit.io_end->handle = handle->h_rsv_handle; handle->h_rsv_handle = NULL; } ext4_set_io_unwritten_flag(inode, mpd->io_submit.io_end); } BUG_ON(map->m_len == 0); if (map->m_flags & EXT4_MAP_NEW) { struct block_device *bdev = inode->i_sb->s_bdev; int i; for (i = 0; i < map->m_len; i++) unmap_underlying_metadata(bdev, map->m_pblk + i); } return 0; } /* * mpage_map_and_submit_extent - map extent starting at mpd->lblk of length * mpd->len and submit pages underlying it for IO * * @handle - handle for journal operations * @mpd - extent to map * @give_up_on_write - we set this to true iff there is a fatal error and there * is no hope of writing the data. The caller should discard * dirty pages to avoid infinite loops. * * The function maps extent starting at mpd->lblk of length mpd->len. If it is * delayed, blocks are allocated, if it is unwritten, we may need to convert * them to initialized or split the described range from larger unwritten * extent. Note that we need not map all the described range since allocation * can return less blocks or the range is covered by more unwritten extents. We * cannot map more because we are limited by reserved transaction credits. On * the other hand we always make sure that the last touched page is fully * mapped so that it can be written out (and thus forward progress is * guaranteed). After mapping we submit all mapped pages for IO. */ static int mpage_map_and_submit_extent(handle_t *handle, struct mpage_da_data *mpd, bool *give_up_on_write) { struct inode *inode = mpd->inode; struct ext4_map_blocks *map = &mpd->map; int err; loff_t disksize; int progress = 0; mpd->io_submit.io_end->offset = ((loff_t)map->m_lblk) << inode->i_blkbits; do { err = mpage_map_one_extent(handle, mpd); if (err < 0) { struct super_block *sb = inode->i_sb; if (EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED) goto invalidate_dirty_pages; /* * Let the uper layers retry transient errors. * In the case of ENOSPC, if ext4_count_free_blocks() * is non-zero, a commit should free up blocks. */ if ((err == -ENOMEM) || (err == -ENOSPC && ext4_count_free_clusters(sb))) { if (progress) goto update_disksize; return err; } ext4_msg(sb, KERN_CRIT, "Delayed block allocation failed for " "inode %lu at logical offset %llu with" " max blocks %u with error %d", inode->i_ino, (unsigned long long)map->m_lblk, (unsigned)map->m_len, -err); ext4_msg(sb, KERN_CRIT, "This should not happen!! Data will " "be lost\n"); if (err == -ENOSPC) ext4_print_free_blocks(inode); invalidate_dirty_pages: *give_up_on_write = true; return err; } progress = 1; /* * Update buffer state, submit mapped pages, and get us new * extent to map */ err = mpage_map_and_submit_buffers(mpd); if (err < 0) goto update_disksize; } while (map->m_len); update_disksize: /* * Update on-disk size after IO is submitted. Races with * truncate are avoided by checking i_size under i_data_sem. */ disksize = ((loff_t)mpd->first_page) << PAGE_SHIFT; if (disksize > EXT4_I(inode)->i_disksize) { int err2; loff_t i_size; down_write(&EXT4_I(inode)->i_data_sem); i_size = i_size_read(inode); if (disksize > i_size) disksize = i_size; if (disksize > EXT4_I(inode)->i_disksize) EXT4_I(inode)->i_disksize = disksize; err2 = ext4_mark_inode_dirty(handle, inode); up_write(&EXT4_I(inode)->i_data_sem); if (err2) ext4_error(inode->i_sb, "Failed to mark inode %lu dirty", inode->i_ino); if (!err) err = err2; } return err; } /* * Calculate the total number of credits to reserve for one writepages * iteration. This is called from ext4_writepages(). We map an extent of * up to MAX_WRITEPAGES_EXTENT_LEN blocks and then we go on and finish mapping * the last partial page. So in total we can map MAX_WRITEPAGES_EXTENT_LEN + * bpp - 1 blocks in bpp different extents. */ static int ext4_da_writepages_trans_blocks(struct inode *inode) { int bpp = ext4_journal_blocks_per_page(inode); return ext4_meta_trans_blocks(inode, MAX_WRITEPAGES_EXTENT_LEN + bpp - 1, bpp); } /* * mpage_prepare_extent_to_map - find & lock contiguous range of dirty pages * and underlying extent to map * * @mpd - where to look for pages * * Walk dirty pages in the mapping. If they are fully mapped, submit them for * IO immediately. When we find a page which isn't mapped we start accumulating * extent of buffers underlying these pages that needs mapping (formed by * either delayed or unwritten buffers). We also lock the pages containing * these buffers. The extent found is returned in @mpd structure (starting at * mpd->lblk with length mpd->len blocks). * * Note that this function can attach bios to one io_end structure which are * neither logically nor physically contiguous. Although it may seem as an * unnecessary complication, it is actually inevitable in blocksize < pagesize * case as we need to track IO to all buffers underlying a page in one io_end. */ static int mpage_prepare_extent_to_map(struct mpage_da_data *mpd) { struct address_space *mapping = mpd->inode->i_mapping; struct pagevec pvec; unsigned int nr_pages; long left = mpd->wbc->nr_to_write; pgoff_t index = mpd->first_page; pgoff_t end = mpd->last_page; int tag; int i, err = 0; int blkbits = mpd->inode->i_blkbits; ext4_lblk_t lblk; struct buffer_head *head; if (mpd->wbc->sync_mode == WB_SYNC_ALL || mpd->wbc->tagged_writepages) tag = PAGECACHE_TAG_TOWRITE; else tag = PAGECACHE_TAG_DIRTY; pagevec_init(&pvec, 0); mpd->map.m_len = 0; mpd->next_page = index; while (index <= end) { nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag, min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1); if (nr_pages == 0) goto out; for (i = 0; i < nr_pages; i++) { struct page *page = pvec.pages[i]; /* * At this point, the page may be truncated or * invalidated (changing page->mapping to NULL), or * even swizzled back from swapper_space to tmpfs file * mapping. However, page->index will not change * because we have a reference on the page. */ if (page->index > end) goto out; /* * Accumulated enough dirty pages? This doesn't apply * to WB_SYNC_ALL mode. For integrity sync we have to * keep going because someone may be concurrently * dirtying pages, and we might have synced a lot of * newly appeared dirty pages, but have not synced all * of the old dirty pages. */ if (mpd->wbc->sync_mode == WB_SYNC_NONE && left <= 0) goto out; /* If we can't merge this page, we are done. */ if (mpd->map.m_len > 0 && mpd->next_page != page->index) goto out; lock_page(page); /* * If the page is no longer dirty, or its mapping no * longer corresponds to inode we are writing (which * means it has been truncated or invalidated), or the * page is already under writeback and we are not doing * a data integrity writeback, skip the page */ if (!PageDirty(page) || (PageWriteback(page) && (mpd->wbc->sync_mode == WB_SYNC_NONE)) || unlikely(page->mapping != mapping)) { unlock_page(page); continue; } wait_on_page_writeback(page); BUG_ON(PageWriteback(page)); if (mpd->map.m_len == 0) mpd->first_page = page->index; mpd->next_page = page->index + 1; /* Add all dirty buffers to mpd */ lblk = ((ext4_lblk_t)page->index) << (PAGE_SHIFT - blkbits); head = page_buffers(page); err = mpage_process_page_bufs(mpd, head, head, lblk); if (err <= 0) goto out; err = 0; left--; } pagevec_release(&pvec); cond_resched(); } return 0; out: pagevec_release(&pvec); return err; } static int __writepage(struct page *page, struct writeback_control *wbc, void *data) { struct address_space *mapping = data; int ret = ext4_writepage(page, wbc); mapping_set_error(mapping, ret); return ret; } static int ext4_writepages(struct address_space *mapping, struct writeback_control *wbc) { pgoff_t writeback_index = 0; long nr_to_write = wbc->nr_to_write; int range_whole = 0; int cycled = 1; handle_t *handle = NULL; struct mpage_da_data mpd; struct inode *inode = mapping->host; int needed_blocks, rsv_blocks = 0, ret = 0; struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb); bool done; struct blk_plug plug; bool give_up_on_write = false; trace_ext4_writepages(inode, wbc); if (dax_mapping(mapping)) return dax_writeback_mapping_range(mapping, inode->i_sb->s_bdev, wbc); /* * No pages to write? This is mainly a kludge to avoid starting * a transaction for special inodes like journal inode on last iput() * because that could violate lock ordering on umount */ if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) goto out_writepages; if (ext4_should_journal_data(inode)) { struct blk_plug plug; blk_start_plug(&plug); ret = write_cache_pages(mapping, wbc, __writepage, mapping); blk_finish_plug(&plug); goto out_writepages; } /* * If the filesystem has aborted, it is read-only, so return * right away instead of dumping stack traces later on that * will obscure the real source of the problem. We test * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because * the latter could be true if the filesystem is mounted * read-only, and in that case, ext4_writepages should * *never* be called, so if that ever happens, we would want * the stack trace. */ if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED)) { ret = -EROFS; goto out_writepages; } if (ext4_should_dioread_nolock(inode)) { /* * We may need to convert up to one extent per block in * the page and we may dirty the inode. */ rsv_blocks = 1 + (PAGE_SIZE >> inode->i_blkbits); } /* * If we have inline data and arrive here, it means that * we will soon create the block for the 1st page, so * we'd better clear the inline data here. */ if (ext4_has_inline_data(inode)) { /* Just inode will be modified... */ handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out_writepages; } BUG_ON(ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)); ext4_destroy_inline_data(handle, inode); ext4_journal_stop(handle); } if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX) range_whole = 1; if (wbc->range_cyclic) { writeback_index = mapping->writeback_index; if (writeback_index) cycled = 0; mpd.first_page = writeback_index; mpd.last_page = -1; } else { mpd.first_page = wbc->range_start >> PAGE_SHIFT; mpd.last_page = wbc->range_end >> PAGE_SHIFT; } mpd.inode = inode; mpd.wbc = wbc; ext4_io_submit_init(&mpd.io_submit, wbc); retry: if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages) tag_pages_for_writeback(mapping, mpd.first_page, mpd.last_page); done = false; blk_start_plug(&plug); while (!done && mpd.first_page <= mpd.last_page) { /* For each extent of pages we use new io_end */ mpd.io_submit.io_end = ext4_init_io_end(inode, GFP_KERNEL); if (!mpd.io_submit.io_end) { ret = -ENOMEM; break; } /* * We have two constraints: We find one extent to map and we * must always write out whole page (makes a difference when * blocksize < pagesize) so that we don't block on IO when we * try to write out the rest of the page. Journalled mode is * not supported by delalloc. */ BUG_ON(ext4_should_journal_data(inode)); needed_blocks = ext4_da_writepages_trans_blocks(inode); /* start a new transaction */ handle = ext4_journal_start_with_reserve(inode, EXT4_HT_WRITE_PAGE, needed_blocks, rsv_blocks); if (IS_ERR(handle)) { ret = PTR_ERR(handle); ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: " "%ld pages, ino %lu; err %d", __func__, wbc->nr_to_write, inode->i_ino, ret); /* Release allocated io_end */ ext4_put_io_end(mpd.io_submit.io_end); break; } trace_ext4_da_write_pages(inode, mpd.first_page, mpd.wbc); ret = mpage_prepare_extent_to_map(&mpd); if (!ret) { if (mpd.map.m_len) ret = mpage_map_and_submit_extent(handle, &mpd, &give_up_on_write); else { /* * We scanned the whole range (or exhausted * nr_to_write), submitted what was mapped and * didn't find anything needing mapping. We are * done. */ done = true; } } ext4_journal_stop(handle); /* Submit prepared bio */ ext4_io_submit(&mpd.io_submit); /* Unlock pages we didn't use */ mpage_release_unused_pages(&mpd, give_up_on_write); /* Drop our io_end reference we got from init */ ext4_put_io_end(mpd.io_submit.io_end); if (ret == -ENOSPC && sbi->s_journal) { /* * Commit the transaction which would * free blocks released in the transaction * and try again */ jbd2_journal_force_commit_nested(sbi->s_journal); ret = 0; continue; } /* Fatal error - ENOMEM, EIO... */ if (ret) break; } blk_finish_plug(&plug); if (!ret && !cycled && wbc->nr_to_write > 0) { cycled = 1; mpd.last_page = writeback_index - 1; mpd.first_page = 0; goto retry; } /* Update index */ if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0)) /* * Set the writeback_index so that range_cyclic * mode will write it back later */ mapping->writeback_index = mpd.first_page; out_writepages: trace_ext4_writepages_result(inode, wbc, ret, nr_to_write - wbc->nr_to_write); return ret; } static int ext4_nonda_switch(struct super_block *sb) { s64 free_clusters, dirty_clusters; struct ext4_sb_info *sbi = EXT4_SB(sb); /* * switch to non delalloc mode if we are running low * on free block. The free block accounting via percpu * counters can get slightly wrong with percpu_counter_batch getting * accumulated on each CPU without updating global counters * Delalloc need an accurate free block accounting. So switch * to non delalloc when we are near to error range. */ free_clusters = percpu_counter_read_positive(&sbi->s_freeclusters_counter); dirty_clusters = percpu_counter_read_positive(&sbi->s_dirtyclusters_counter); /* * Start pushing delalloc when 1/2 of free blocks are dirty. */ if (dirty_clusters && (free_clusters < 2 * dirty_clusters)) try_to_writeback_inodes_sb(sb, WB_REASON_FS_FREE_SPACE); if (2 * free_clusters < 3 * dirty_clusters || free_clusters < (dirty_clusters + EXT4_FREECLUSTERS_WATERMARK)) { /* * free block count is less than 150% of dirty blocks * or free blocks is less than watermark */ return 1; } return 0; } /* We always reserve for an inode update; the superblock could be there too */ static int ext4_da_write_credits(struct inode *inode, loff_t pos, unsigned len) { if (likely(ext4_has_feature_large_file(inode->i_sb))) return 1; if (pos + len <= 0x7fffffffULL) return 1; /* We might need to update the superblock to set LARGE_FILE */ return 2; } static int ext4_da_write_begin(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned flags, struct page **pagep, void **fsdata) { int ret, retries = 0; struct page *page; pgoff_t index; struct inode *inode = mapping->host; handle_t *handle; index = pos >> PAGE_SHIFT; if (ext4_nonda_switch(inode->i_sb)) { *fsdata = (void *)FALL_BACK_TO_NONDELALLOC; return ext4_write_begin(file, mapping, pos, len, flags, pagep, fsdata); } *fsdata = (void *)0; trace_ext4_da_write_begin(inode, pos, len, flags); if (ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA)) { ret = ext4_da_write_inline_data_begin(mapping, inode, pos, len, flags, pagep, fsdata); if (ret < 0) return ret; if (ret == 1) return 0; } /* * grab_cache_page_write_begin() can take a long time if the * system is thrashing due to memory pressure, or if the page * is being written back. So grab it first before we start * the transaction handle. This also allows us to allocate * the page (if needed) without using GFP_NOFS. */ retry_grab: page = grab_cache_page_write_begin(mapping, index, flags); if (!page) return -ENOMEM; unlock_page(page); /* * With delayed allocation, we don't log the i_disksize update * if there is delayed block allocation. But we still need * to journalling the i_disksize update if writes to the end * of file which has an already mapped buffer. */ retry_journal: handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, ext4_da_write_credits(inode, pos, len)); if (IS_ERR(handle)) { put_page(page); return PTR_ERR(handle); } lock_page(page); if (page->mapping != mapping) { /* The page got truncated from under us */ unlock_page(page); put_page(page); ext4_journal_stop(handle); goto retry_grab; } /* In case writeback began while the page was unlocked */ wait_for_stable_page(page); #ifdef CONFIG_EXT4_FS_ENCRYPTION ret = ext4_block_write_begin(page, pos, len, ext4_da_get_block_prep); #else ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep); #endif if (ret < 0) { unlock_page(page); ext4_journal_stop(handle); /* * block_write_begin may have instantiated a few blocks * outside i_size. Trim these off again. Don't need * i_size_read because we hold i_mutex. */ if (pos + len > inode->i_size) ext4_truncate_failed_write(inode); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_journal; put_page(page); return ret; } *pagep = page; return ret; } /* * Check if we should update i_disksize * when write to the end of file but not require block allocation */ static int ext4_da_should_update_i_disksize(struct page *page, unsigned long offset) { struct buffer_head *bh; struct inode *inode = page->mapping->host; unsigned int idx; int i; bh = page_buffers(page); idx = offset >> inode->i_blkbits; for (i = 0; i < idx; i++) bh = bh->b_this_page; if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh)) return 0; return 1; } static int ext4_da_write_end(struct file *file, struct address_space *mapping, loff_t pos, unsigned len, unsigned copied, struct page *page, void *fsdata) { struct inode *inode = mapping->host; int ret = 0, ret2; handle_t *handle = ext4_journal_current_handle(); loff_t new_i_size; unsigned long start, end; int write_mode = (int)(unsigned long)fsdata; if (write_mode == FALL_BACK_TO_NONDELALLOC) return ext4_write_end(file, mapping, pos, len, copied, page, fsdata); trace_ext4_da_write_end(inode, pos, len, copied); start = pos & (PAGE_SIZE - 1); end = start + copied - 1; /* * generic_write_end() will run mark_inode_dirty() if i_size * changes. So let's piggyback the i_disksize mark_inode_dirty * into that. */ new_i_size = pos + copied; if (copied && new_i_size > EXT4_I(inode)->i_disksize) { if (ext4_has_inline_data(inode) || ext4_da_should_update_i_disksize(page, end)) { ext4_update_i_disksize(inode, new_i_size); /* We need to mark inode dirty even if * new_i_size is less that inode->i_size * bu greater than i_disksize.(hint delalloc) */ ext4_mark_inode_dirty(handle, inode); } } if (write_mode != CONVERT_INLINE_DATA && ext4_test_inode_state(inode, EXT4_STATE_MAY_INLINE_DATA) && ext4_has_inline_data(inode)) ret2 = ext4_da_write_inline_data_end(inode, pos, len, copied, page); else ret2 = generic_write_end(file, mapping, pos, len, copied, page, fsdata); copied = ret2; if (ret2 < 0) ret = ret2; ret2 = ext4_journal_stop(handle); if (!ret) ret = ret2; return ret ? ret : copied; } static void ext4_da_invalidatepage(struct page *page, unsigned int offset, unsigned int length) { /* * Drop reserved blocks */ BUG_ON(!PageLocked(page)); if (!page_has_buffers(page)) goto out; ext4_da_page_release_reservation(page, offset, length); out: ext4_invalidatepage(page, offset, length); return; } /* * Force all delayed allocation blocks to be allocated for a given inode. */ int ext4_alloc_da_blocks(struct inode *inode) { trace_ext4_alloc_da_blocks(inode); if (!EXT4_I(inode)->i_reserved_data_blocks) return 0; /* * We do something simple for now. The filemap_flush() will * also start triggering a write of the data blocks, which is * not strictly speaking necessary (and for users of * laptop_mode, not even desirable). However, to do otherwise * would require replicating code paths in: * * ext4_writepages() -> * write_cache_pages() ---> (via passed in callback function) * __mpage_da_writepage() --> * mpage_add_bh_to_extent() * mpage_da_map_blocks() * * The problem is that write_cache_pages(), located in * mm/page-writeback.c, marks pages clean in preparation for * doing I/O, which is not desirable if we're not planning on * doing I/O at all. * * We could call write_cache_pages(), and then redirty all of * the pages by calling redirty_page_for_writepage() but that * would be ugly in the extreme. So instead we would need to * replicate parts of the code in the above functions, * simplifying them because we wouldn't actually intend to * write out the pages, but rather only collect contiguous * logical block extents, call the multi-block allocator, and * then update the buffer heads with the block allocations. * * For now, though, we'll cheat by calling filemap_flush(), * which will map the blocks, and start the I/O, but not * actually wait for the I/O to complete. */ return filemap_flush(inode->i_mapping); } /* * bmap() is special. It gets used by applications such as lilo and by * the swapper to find the on-disk block of a specific piece of data. * * Naturally, this is dangerous if the block concerned is still in the * journal. If somebody makes a swapfile on an ext4 data-journaling * filesystem and enables swap, then they may get a nasty shock when the * data getting swapped to that swapfile suddenly gets overwritten by * the original zero's written out previously to the journal and * awaiting writeback in the kernel's buffer cache. * * So, if we see any bmap calls here on a modified, data-journaled file, * take extra steps to flush any blocks which might be in the cache. */ static sector_t ext4_bmap(struct address_space *mapping, sector_t block) { struct inode *inode = mapping->host; journal_t *journal; int err; /* * We can get here for an inline file via the FIBMAP ioctl */ if (ext4_has_inline_data(inode)) return 0; if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) && test_opt(inode->i_sb, DELALLOC)) { /* * With delalloc we want to sync the file * so that we can make sure we allocate * blocks for file */ filemap_write_and_wait(mapping); } if (EXT4_JOURNAL(inode) && ext4_test_inode_state(inode, EXT4_STATE_JDATA)) { /* * This is a REALLY heavyweight approach, but the use of * bmap on dirty files is expected to be extremely rare: * only if we run lilo or swapon on a freshly made file * do we expect this to happen. * * (bmap requires CAP_SYS_RAWIO so this does not * represent an unprivileged user DOS attack --- we'd be * in trouble if mortal users could trigger this path at * will.) * * NB. EXT4_STATE_JDATA is not set on files other than * regular files. If somebody wants to bmap a directory * or symlink and gets confused because the buffer * hasn't yet been flushed to disk, they deserve * everything they get. */ ext4_clear_inode_state(inode, EXT4_STATE_JDATA); journal = EXT4_JOURNAL(inode); jbd2_journal_lock_updates(journal); err = jbd2_journal_flush(journal); jbd2_journal_unlock_updates(journal); if (err) return 0; } return generic_block_bmap(mapping, block, ext4_get_block); } static int ext4_readpage(struct file *file, struct page *page) { int ret = -EAGAIN; struct inode *inode = page->mapping->host; trace_ext4_readpage(page); if (ext4_has_inline_data(inode)) ret = ext4_readpage_inline(inode, page); if (ret == -EAGAIN) return ext4_mpage_readpages(page->mapping, NULL, page, 1); return ret; } static int ext4_readpages(struct file *file, struct address_space *mapping, struct list_head *pages, unsigned nr_pages) { struct inode *inode = mapping->host; /* If the file has inline data, no need to do readpages. */ if (ext4_has_inline_data(inode)) return 0; return ext4_mpage_readpages(mapping, pages, NULL, nr_pages); } static void ext4_invalidatepage(struct page *page, unsigned int offset, unsigned int length) { trace_ext4_invalidatepage(page, offset, length); /* No journalling happens on data buffers when this function is used */ WARN_ON(page_has_buffers(page) && buffer_jbd(page_buffers(page))); block_invalidatepage(page, offset, length); } static int __ext4_journalled_invalidatepage(struct page *page, unsigned int offset, unsigned int length) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); trace_ext4_journalled_invalidatepage(page, offset, length); /* * If it's a full truncate we just forget about the pending dirtying */ if (offset == 0 && length == PAGE_SIZE) ClearPageChecked(page); return jbd2_journal_invalidatepage(journal, page, offset, length); } /* Wrapper for aops... */ static void ext4_journalled_invalidatepage(struct page *page, unsigned int offset, unsigned int length) { WARN_ON(__ext4_journalled_invalidatepage(page, offset, length) < 0); } static int ext4_releasepage(struct page *page, gfp_t wait) { journal_t *journal = EXT4_JOURNAL(page->mapping->host); trace_ext4_releasepage(page); /* Page has dirty journalled data -> cannot release */ if (PageChecked(page)) return 0; if (journal) return jbd2_journal_try_to_free_buffers(journal, page, wait); else return try_to_free_buffers(page); } #ifdef CONFIG_FS_DAX int ext4_dax_mmap_get_block(struct inode *inode, sector_t iblock, struct buffer_head *bh_result, int create) { int ret, err; int credits; struct ext4_map_blocks map; handle_t *handle = NULL; int flags = 0; ext4_debug("ext4_dax_mmap_get_block: inode %lu, create flag %d\n", inode->i_ino, create); map.m_lblk = iblock; map.m_len = bh_result->b_size >> inode->i_blkbits; credits = ext4_chunk_trans_blocks(inode, map.m_len); if (create) { flags |= EXT4_GET_BLOCKS_PRE_IO | EXT4_GET_BLOCKS_CREATE_ZERO; handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); return ret; } } ret = ext4_map_blocks(handle, inode, &map, flags); if (create) { err = ext4_journal_stop(handle); if (ret >= 0 && err < 0) ret = err; } if (ret <= 0) goto out; if (map.m_flags & EXT4_MAP_UNWRITTEN) { int err2; /* * We are protected by i_mmap_sem so we know block cannot go * away from under us even though we dropped i_data_sem. * Convert extent to written and write zeros there. * * Note: We may get here even when create == 0. */ handle = ext4_journal_start(inode, EXT4_HT_MAP_BLOCKS, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); goto out; } err = ext4_map_blocks(handle, inode, &map, EXT4_GET_BLOCKS_CONVERT | EXT4_GET_BLOCKS_CREATE_ZERO); if (err < 0) ret = err; err2 = ext4_journal_stop(handle); if (err2 < 0 && ret > 0) ret = err2; } out: WARN_ON_ONCE(ret == 0 && create); if (ret > 0) { map_bh(bh_result, inode->i_sb, map.m_pblk); /* * At least for now we have to clear BH_New so that DAX code * doesn't attempt to zero blocks again in a racy way. */ map.m_flags &= ~EXT4_MAP_NEW; ext4_update_bh_state(bh_result, map.m_flags); bh_result->b_size = map.m_len << inode->i_blkbits; ret = 0; } return ret; } #endif static int ext4_end_io_dio(struct kiocb *iocb, loff_t offset, ssize_t size, void *private) { ext4_io_end_t *io_end = private; /* if not async direct IO just return */ if (!io_end) return 0; ext_debug("ext4_end_io_dio(): io_end 0x%p " "for inode %lu, iocb 0x%p, offset %llu, size %zd\n", io_end, io_end->inode->i_ino, iocb, offset, size); /* * Error during AIO DIO. We cannot convert unwritten extents as the * data was not written. Just clear the unwritten flag and drop io_end. */ if (size <= 0) { ext4_clear_io_unwritten_flag(io_end); size = 0; } io_end->offset = offset; io_end->size = size; ext4_put_io_end(io_end); return 0; } /* * For ext4 extent files, ext4 will do direct-io write to holes, * preallocated extents, and those write extend the file, no need to * fall back to buffered IO. * * For holes, we fallocate those blocks, mark them as unwritten * If those blocks were preallocated, we mark sure they are split, but * still keep the range to write as unwritten. * * The unwritten extents will be converted to written when DIO is completed. * For async direct IO, since the IO may still pending when return, we * set up an end_io call back function, which will do the conversion * when async direct IO completed. * * If the O_DIRECT write will extend the file then add this inode to the * orphan list. So recovery will truncate it back to the original size * if the machine crashes during the write. * */ static ssize_t ext4_ext_direct_IO(struct kiocb *iocb, struct iov_iter *iter, loff_t offset) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; ssize_t ret; size_t count = iov_iter_count(iter); int overwrite = 0; get_block_t *get_block_func = NULL; int dio_flags = 0; loff_t final_size = offset + count; /* Use the old path for reads and writes beyond i_size. */ if (iov_iter_rw(iter) != WRITE || final_size > inode->i_size) return ext4_ind_direct_IO(iocb, iter, offset); BUG_ON(iocb->private == NULL); /* * Make all waiters for direct IO properly wait also for extent * conversion. This also disallows race between truncate() and * overwrite DIO as i_dio_count needs to be incremented under i_mutex. */ if (iov_iter_rw(iter) == WRITE) inode_dio_begin(inode); /* If we do a overwrite dio, i_mutex locking can be released */ overwrite = *((int *)iocb->private); if (overwrite) inode_unlock(inode); /* * We could direct write to holes and fallocate. * * Allocated blocks to fill the hole are marked as unwritten to prevent * parallel buffered read to expose the stale data before DIO complete * the data IO. * * As to previously fallocated extents, ext4 get_block will just simply * mark the buffer mapped but still keep the extents unwritten. * * For non AIO case, we will convert those unwritten extents to written * after return back from blockdev_direct_IO. That way we save us from * allocating io_end structure and also the overhead of offloading * the extent convertion to a workqueue. * * For async DIO, the conversion needs to be deferred when the * IO is completed. The ext4 end_io callback function will be * called to take care of the conversion work. Here for async * case, we allocate an io_end structure to hook to the iocb. */ iocb->private = NULL; if (overwrite) get_block_func = ext4_dio_get_block_overwrite; else if (is_sync_kiocb(iocb)) { get_block_func = ext4_dio_get_block_unwritten_sync; dio_flags = DIO_LOCKING; } else { get_block_func = ext4_dio_get_block_unwritten_async; dio_flags = DIO_LOCKING; } #ifdef CONFIG_EXT4_FS_ENCRYPTION BUG_ON(ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode)); #endif if (IS_DAX(inode)) ret = dax_do_io(iocb, inode, iter, offset, get_block_func, ext4_end_io_dio, dio_flags); else ret = __blockdev_direct_IO(iocb, inode, inode->i_sb->s_bdev, iter, offset, get_block_func, ext4_end_io_dio, NULL, dio_flags); if (ret > 0 && !overwrite && ext4_test_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN)) { int err; /* * for non AIO case, since the IO is already * completed, we could do the conversion right here */ err = ext4_convert_unwritten_extents(NULL, inode, offset, ret); if (err < 0) ret = err; ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN); } if (iov_iter_rw(iter) == WRITE) inode_dio_end(inode); /* take i_mutex locking again if we do a ovewrite dio */ if (overwrite) inode_lock(inode); return ret; } static ssize_t ext4_direct_IO(struct kiocb *iocb, struct iov_iter *iter, loff_t offset) { struct file *file = iocb->ki_filp; struct inode *inode = file->f_mapping->host; size_t count = iov_iter_count(iter); ssize_t ret; #ifdef CONFIG_EXT4_FS_ENCRYPTION if (ext4_encrypted_inode(inode) && S_ISREG(inode->i_mode)) return 0; #endif /* * If we are doing data journalling we don't support O_DIRECT */ if (ext4_should_journal_data(inode)) return 0; /* Let buffer I/O handle the inline data case. */ if (ext4_has_inline_data(inode)) return 0; trace_ext4_direct_IO_enter(inode, offset, count, iov_iter_rw(iter)); if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) ret = ext4_ext_direct_IO(iocb, iter, offset); else ret = ext4_ind_direct_IO(iocb, iter, offset); trace_ext4_direct_IO_exit(inode, offset, count, iov_iter_rw(iter), ret); return ret; } /* * Pages can be marked dirty completely asynchronously from ext4's journalling * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do * much here because ->set_page_dirty is called under VFS locks. The page is * not necessarily locked. * * We cannot just dirty the page and leave attached buffers clean, because the * buffers' dirty state is "definitive". We cannot just set the buffers dirty * or jbddirty because all the journalling code will explode. * * So what we do is to mark the page "pending dirty" and next time writepage * is called, propagate that into the buffers appropriately. */ static int ext4_journalled_set_page_dirty(struct page *page) { SetPageChecked(page); return __set_page_dirty_nobuffers(page); } static const struct address_space_operations ext4_aops = { .readpage = ext4_readpage, .readpages = ext4_readpages, .writepage = ext4_writepage, .writepages = ext4_writepages, .write_begin = ext4_write_begin, .write_end = ext4_write_end, .bmap = ext4_bmap, .invalidatepage = ext4_invalidatepage, .releasepage = ext4_releasepage, .direct_IO = ext4_direct_IO, .migratepage = buffer_migrate_page, .is_partially_uptodate = block_is_partially_uptodate, .error_remove_page = generic_error_remove_page, }; static const struct address_space_operations ext4_journalled_aops = { .readpage = ext4_readpage, .readpages = ext4_readpages, .writepage = ext4_writepage, .writepages = ext4_writepages, .write_begin = ext4_write_begin, .write_end = ext4_journalled_write_end, .set_page_dirty = ext4_journalled_set_page_dirty, .bmap = ext4_bmap, .invalidatepage = ext4_journalled_invalidatepage, .releasepage = ext4_releasepage, .direct_IO = ext4_direct_IO, .is_partially_uptodate = block_is_partially_uptodate, .error_remove_page = generic_error_remove_page, }; static const struct address_space_operations ext4_da_aops = { .readpage = ext4_readpage, .readpages = ext4_readpages, .writepage = ext4_writepage, .writepages = ext4_writepages, .write_begin = ext4_da_write_begin, .write_end = ext4_da_write_end, .bmap = ext4_bmap, .invalidatepage = ext4_da_invalidatepage, .releasepage = ext4_releasepage, .direct_IO = ext4_direct_IO, .migratepage = buffer_migrate_page, .is_partially_uptodate = block_is_partially_uptodate, .error_remove_page = generic_error_remove_page, }; void ext4_set_aops(struct inode *inode) { switch (ext4_inode_journal_mode(inode)) { case EXT4_INODE_ORDERED_DATA_MODE: ext4_set_inode_state(inode, EXT4_STATE_ORDERED_MODE); break; case EXT4_INODE_WRITEBACK_DATA_MODE: ext4_clear_inode_state(inode, EXT4_STATE_ORDERED_MODE); break; case EXT4_INODE_JOURNAL_DATA_MODE: inode->i_mapping->a_ops = &ext4_journalled_aops; return; default: BUG(); } if (test_opt(inode->i_sb, DELALLOC)) inode->i_mapping->a_ops = &ext4_da_aops; else inode->i_mapping->a_ops = &ext4_aops; } static int __ext4_block_zero_page_range(handle_t *handle, struct address_space *mapping, loff_t from, loff_t length) { ext4_fsblk_t index = from >> PAGE_SHIFT; unsigned offset = from & (PAGE_SIZE-1); unsigned blocksize, pos; ext4_lblk_t iblock; struct inode *inode = mapping->host; struct buffer_head *bh; struct page *page; int err = 0; page = find_or_create_page(mapping, from >> PAGE_SHIFT, mapping_gfp_constraint(mapping, ~__GFP_FS)); if (!page) return -ENOMEM; blocksize = inode->i_sb->s_blocksize; iblock = index << (PAGE_SHIFT - inode->i_sb->s_blocksize_bits); if (!page_has_buffers(page)) create_empty_buffers(page, blocksize, 0); /* Find the buffer that contains "offset" */ bh = page_buffers(page); pos = blocksize; while (offset >= pos) { bh = bh->b_this_page; iblock++; pos += blocksize; } if (buffer_freed(bh)) { BUFFER_TRACE(bh, "freed: skip"); goto unlock; } if (!buffer_mapped(bh)) { BUFFER_TRACE(bh, "unmapped"); ext4_get_block(inode, iblock, bh, 0); /* unmapped? It's a hole - nothing to do */ if (!buffer_mapped(bh)) { BUFFER_TRACE(bh, "still unmapped"); goto unlock; } } /* Ok, it's mapped. Make sure it's up-to-date */ if (PageUptodate(page)) set_buffer_uptodate(bh); if (!buffer_uptodate(bh)) { err = -EIO; ll_rw_block(READ, 1, &bh); wait_on_buffer(bh); /* Uhhuh. Read error. Complain and punt. */ if (!buffer_uptodate(bh)) goto unlock; if (S_ISREG(inode->i_mode) && ext4_encrypted_inode(inode)) { /* We expect the key to be set. */ BUG_ON(!ext4_has_encryption_key(inode)); BUG_ON(blocksize != PAGE_SIZE); WARN_ON_ONCE(ext4_decrypt(page)); } } if (ext4_should_journal_data(inode)) { BUFFER_TRACE(bh, "get write access"); err = ext4_journal_get_write_access(handle, bh); if (err) goto unlock; } zero_user(page, offset, length); BUFFER_TRACE(bh, "zeroed end of block"); if (ext4_should_journal_data(inode)) { err = ext4_handle_dirty_metadata(handle, inode, bh); } else { err = 0; mark_buffer_dirty(bh); if (ext4_test_inode_state(inode, EXT4_STATE_ORDERED_MODE)) err = ext4_jbd2_file_inode(handle, inode); } unlock: unlock_page(page); put_page(page); return err; } /* * ext4_block_zero_page_range() zeros out a mapping of length 'length' * starting from file offset 'from'. The range to be zero'd must * be contained with in one block. If the specified range exceeds * the end of the block it will be shortened to end of the block * that cooresponds to 'from' */ static int ext4_block_zero_page_range(handle_t *handle, struct address_space *mapping, loff_t from, loff_t length) { struct inode *inode = mapping->host; unsigned offset = from & (PAGE_SIZE-1); unsigned blocksize = inode->i_sb->s_blocksize; unsigned max = blocksize - (offset & (blocksize - 1)); /* * correct length if it does not fall between * 'from' and the end of the block */ if (length > max || length < 0) length = max; if (IS_DAX(inode)) return dax_zero_page_range(inode, from, length, ext4_get_block); return __ext4_block_zero_page_range(handle, mapping, from, length); } /* * ext4_block_truncate_page() zeroes out a mapping from file offset `from' * up to the end of the block which corresponds to `from'. * This required during truncate. We need to physically zero the tail end * of that block so it doesn't yield old data if the file is later grown. */ static int ext4_block_truncate_page(handle_t *handle, struct address_space *mapping, loff_t from) { unsigned offset = from & (PAGE_SIZE-1); unsigned length; unsigned blocksize; struct inode *inode = mapping->host; blocksize = inode->i_sb->s_blocksize; length = blocksize - (offset & (blocksize - 1)); return ext4_block_zero_page_range(handle, mapping, from, length); } int ext4_zero_partial_blocks(handle_t *handle, struct inode *inode, loff_t lstart, loff_t length) { struct super_block *sb = inode->i_sb; struct address_space *mapping = inode->i_mapping; unsigned partial_start, partial_end; ext4_fsblk_t start, end; loff_t byte_end = (lstart + length - 1); int err = 0; partial_start = lstart & (sb->s_blocksize - 1); partial_end = byte_end & (sb->s_blocksize - 1); start = lstart >> sb->s_blocksize_bits; end = byte_end >> sb->s_blocksize_bits; /* Handle partial zero within the single block */ if (start == end && (partial_start || (partial_end != sb->s_blocksize - 1))) { err = ext4_block_zero_page_range(handle, mapping, lstart, length); return err; } /* Handle partial zero out on the start of the range */ if (partial_start) { err = ext4_block_zero_page_range(handle, mapping, lstart, sb->s_blocksize); if (err) return err; } /* Handle partial zero out on the end of the range */ if (partial_end != sb->s_blocksize - 1) err = ext4_block_zero_page_range(handle, mapping, byte_end - partial_end, partial_end + 1); return err; } int ext4_can_truncate(struct inode *inode) { if (S_ISREG(inode->i_mode)) return 1; if (S_ISDIR(inode->i_mode)) return 1; if (S_ISLNK(inode->i_mode)) return !ext4_inode_is_fast_symlink(inode); return 0; } /* * We have to make sure i_disksize gets properly updated before we truncate * page cache due to hole punching or zero range. Otherwise i_disksize update * can get lost as it may have been postponed to submission of writeback but * that will never happen after we truncate page cache. */ int ext4_update_disksize_before_punch(struct inode *inode, loff_t offset, loff_t len) { handle_t *handle; loff_t size = i_size_read(inode); WARN_ON(!inode_is_locked(inode)); if (offset > size || offset + len < size) return 0; if (EXT4_I(inode)->i_disksize >= size) return 0; handle = ext4_journal_start(inode, EXT4_HT_MISC, 1); if (IS_ERR(handle)) return PTR_ERR(handle); ext4_update_i_disksize(inode, size); ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); return 0; } /* * ext4_punch_hole: punches a hole in a file by releaseing the blocks * associated with the given offset and length * * @inode: File inode * @offset: The offset where the hole will begin * @len: The length of the hole * * Returns: 0 on success or negative on failure */ int ext4_punch_hole(struct inode *inode, loff_t offset, loff_t length) { struct super_block *sb = inode->i_sb; ext4_lblk_t first_block, stop_block; struct address_space *mapping = inode->i_mapping; loff_t first_block_offset, last_block_offset; handle_t *handle; unsigned int credits; int ret = 0; if (!S_ISREG(inode->i_mode)) return -EOPNOTSUPP; trace_ext4_punch_hole(inode, offset, length, 0); /* * Write out all dirty pages to avoid race conditions * Then release them. */ if (mapping->nrpages && mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) { ret = filemap_write_and_wait_range(mapping, offset, offset + length - 1); if (ret) return ret; } inode_lock(inode); /* No need to punch hole beyond i_size */ if (offset >= inode->i_size) goto out_mutex; /* * If the hole extends beyond i_size, set the hole * to end after the page that contains i_size */ if (offset + length > inode->i_size) { length = inode->i_size + PAGE_SIZE - (inode->i_size & (PAGE_SIZE - 1)) - offset; } if (offset & (sb->s_blocksize - 1) || (offset + length) & (sb->s_blocksize - 1)) { /* * Attach jinode to inode for jbd2 if we do any zeroing of * partial block */ ret = ext4_inode_attach_jinode(inode); if (ret < 0) goto out_mutex; } /* Wait all existing dio workers, newcomers will block on i_mutex */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); /* * Prevent page faults from reinstantiating pages we have released from * page cache. */ down_write(&EXT4_I(inode)->i_mmap_sem); first_block_offset = round_up(offset, sb->s_blocksize); last_block_offset = round_down((offset + length), sb->s_blocksize) - 1; /* Now release the pages and zero block aligned part of pages*/ if (last_block_offset > first_block_offset) { ret = ext4_update_disksize_before_punch(inode, offset, length); if (ret) goto out_dio; truncate_pagecache_range(inode, first_block_offset, last_block_offset); } if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) credits = ext4_writepage_trans_blocks(inode); else credits = ext4_blocks_for_truncate(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ret = PTR_ERR(handle); ext4_std_error(sb, ret); goto out_dio; } ret = ext4_zero_partial_blocks(handle, inode, offset, length); if (ret) goto out_stop; first_block = (offset + sb->s_blocksize - 1) >> EXT4_BLOCK_SIZE_BITS(sb); stop_block = (offset + length) >> EXT4_BLOCK_SIZE_BITS(sb); /* If there are no blocks to remove, return now */ if (first_block >= stop_block) goto out_stop; down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); ret = ext4_es_remove_extent(inode, first_block, stop_block - first_block); if (ret) { up_write(&EXT4_I(inode)->i_data_sem); goto out_stop; } if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) ret = ext4_ext_remove_space(inode, first_block, stop_block - 1); else ret = ext4_ind_remove_space(handle, inode, first_block, stop_block); up_write(&EXT4_I(inode)->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); out_stop: ext4_journal_stop(handle); out_dio: up_write(&EXT4_I(inode)->i_mmap_sem); ext4_inode_resume_unlocked_dio(inode); out_mutex: inode_unlock(inode); return ret; } int ext4_inode_attach_jinode(struct inode *inode) { struct ext4_inode_info *ei = EXT4_I(inode); struct jbd2_inode *jinode; if (ei->jinode || !EXT4_SB(inode->i_sb)->s_journal) return 0; jinode = jbd2_alloc_inode(GFP_KERNEL); spin_lock(&inode->i_lock); if (!ei->jinode) { if (!jinode) { spin_unlock(&inode->i_lock); return -ENOMEM; } ei->jinode = jinode; jbd2_journal_init_jbd_inode(ei->jinode, inode); jinode = NULL; } spin_unlock(&inode->i_lock); if (unlikely(jinode != NULL)) jbd2_free_inode(jinode); return 0; } /* * ext4_truncate() * * We block out ext4_get_block() block instantiations across the entire * transaction, and VFS/VM ensures that ext4_truncate() cannot run * simultaneously on behalf of the same inode. * * As we work through the truncate and commit bits of it to the journal there * is one core, guiding principle: the file's tree must always be consistent on * disk. We must be able to restart the truncate after a crash. * * The file's tree may be transiently inconsistent in memory (although it * probably isn't), but whenever we close off and commit a journal transaction, * the contents of (the filesystem + the journal) must be consistent and * restartable. It's pretty simple, really: bottom up, right to left (although * left-to-right works OK too). * * Note that at recovery time, journal replay occurs *before* the restart of * truncate against the orphan inode list. * * The committed inode has the new, desired i_size (which is the same as * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see * that this inode's truncate did not complete and it will again call * ext4_truncate() to have another go. So there will be instantiated blocks * to the right of the truncation point in a crashed ext4 filesystem. But * that's fine - as long as they are linked from the inode, the post-crash * ext4_truncate() run will find them and release them. */ void ext4_truncate(struct inode *inode) { struct ext4_inode_info *ei = EXT4_I(inode); unsigned int credits; handle_t *handle; struct address_space *mapping = inode->i_mapping; /* * There is a possibility that we're either freeing the inode * or it's a completely new inode. In those cases we might not * have i_mutex locked because it's not necessary. */ if (!(inode->i_state & (I_NEW|I_FREEING))) WARN_ON(!inode_is_locked(inode)); trace_ext4_truncate_enter(inode); if (!ext4_can_truncate(inode)) return; ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS); if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC)) ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE); if (ext4_has_inline_data(inode)) { int has_inline = 1; ext4_inline_data_truncate(inode, &has_inline); if (has_inline) return; } /* If we zero-out tail of the page, we have to create jinode for jbd2 */ if (inode->i_size & (inode->i_sb->s_blocksize - 1)) { if (ext4_inode_attach_jinode(inode) < 0) return; } if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) credits = ext4_writepage_trans_blocks(inode); else credits = ext4_blocks_for_truncate(inode); handle = ext4_journal_start(inode, EXT4_HT_TRUNCATE, credits); if (IS_ERR(handle)) { ext4_std_error(inode->i_sb, PTR_ERR(handle)); return; } if (inode->i_size & (inode->i_sb->s_blocksize - 1)) ext4_block_truncate_page(handle, mapping, inode->i_size); /* * We add the inode to the orphan list, so that if this * truncate spans multiple transactions, and we crash, we will * resume the truncate when the filesystem recovers. It also * marks the inode dirty, to catch the new size. * * Implication: the file must always be in a sane, consistent * truncatable state while each transaction commits. */ if (ext4_orphan_add(handle, inode)) goto out_stop; down_write(&EXT4_I(inode)->i_data_sem); ext4_discard_preallocations(inode); if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) ext4_ext_truncate(handle, inode); else ext4_ind_truncate(handle, inode); up_write(&ei->i_data_sem); if (IS_SYNC(inode)) ext4_handle_sync(handle); out_stop: /* * If this was a simple ftruncate() and the file will remain alive, * then we need to clear up the orphan record which we created above. * However, if this was a real unlink then we were called by * ext4_evict_inode(), and we allow that function to clean up the * orphan info for us. */ if (inode->i_nlink) ext4_orphan_del(handle, inode); inode->i_mtime = inode->i_ctime = ext4_current_time(inode); ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); trace_ext4_truncate_exit(inode); } /* * ext4_get_inode_loc returns with an extra refcount against the inode's * underlying buffer_head on success. If 'in_mem' is true, we have all * data in memory that is needed to recreate the on-disk version of this * inode. */ static int __ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc, int in_mem) { struct ext4_group_desc *gdp; struct buffer_head *bh; struct super_block *sb = inode->i_sb; ext4_fsblk_t block; int inodes_per_block, inode_offset; iloc->bh = NULL; if (!ext4_valid_inum(sb, inode->i_ino)) return -EFSCORRUPTED; iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb); gdp = ext4_get_group_desc(sb, iloc->block_group, NULL); if (!gdp) return -EIO; /* * Figure out the offset within the block group inode table */ inodes_per_block = EXT4_SB(sb)->s_inodes_per_block; inode_offset = ((inode->i_ino - 1) % EXT4_INODES_PER_GROUP(sb)); block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block); iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb); bh = sb_getblk(sb, block); if (unlikely(!bh)) return -ENOMEM; if (!buffer_uptodate(bh)) { lock_buffer(bh); /* * If the buffer has the write error flag, we have failed * to write out another inode in the same block. In this * case, we don't have to read the block because we may * read the old inode data successfully. */ if (buffer_write_io_error(bh) && !buffer_uptodate(bh)) set_buffer_uptodate(bh); if (buffer_uptodate(bh)) { /* someone brought it uptodate while we waited */ unlock_buffer(bh); goto has_buffer; } /* * If we have all information of the inode in memory and this * is the only valid inode in the block, we need not read the * block. */ if (in_mem) { struct buffer_head *bitmap_bh; int i, start; start = inode_offset & ~(inodes_per_block - 1); /* Is the inode bitmap in cache? */ bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp)); if (unlikely(!bitmap_bh)) goto make_io; /* * If the inode bitmap isn't in cache then the * optimisation may end up performing two reads instead * of one, so skip it. */ if (!buffer_uptodate(bitmap_bh)) { brelse(bitmap_bh); goto make_io; } for (i = start; i < start + inodes_per_block; i++) { if (i == inode_offset) continue; if (ext4_test_bit(i, bitmap_bh->b_data)) break; } brelse(bitmap_bh); if (i == start + inodes_per_block) { /* all other inodes are free, so skip I/O */ memset(bh->b_data, 0, bh->b_size); set_buffer_uptodate(bh); unlock_buffer(bh); goto has_buffer; } } make_io: /* * If we need to do any I/O, try to pre-readahead extra * blocks from the inode table. */ if (EXT4_SB(sb)->s_inode_readahead_blks) { ext4_fsblk_t b, end, table; unsigned num; __u32 ra_blks = EXT4_SB(sb)->s_inode_readahead_blks; table = ext4_inode_table(sb, gdp); /* s_inode_readahead_blks is always a power of 2 */ b = block & ~((ext4_fsblk_t) ra_blks - 1); if (table > b) b = table; end = b + ra_blks; num = EXT4_INODES_PER_GROUP(sb); if (ext4_has_group_desc_csum(sb)) num -= ext4_itable_unused_count(sb, gdp); table += num / inodes_per_block; if (end > table) end = table; while (b <= end) sb_breadahead(sb, b++); } /* * There are other valid inodes in the buffer, this inode * has in-inode xattrs, or we don't have this inode in memory. * Read the block from disk. */ trace_ext4_load_inode(inode); get_bh(bh); bh->b_end_io = end_buffer_read_sync; submit_bh(READ | REQ_META | REQ_PRIO, bh); wait_on_buffer(bh); if (!buffer_uptodate(bh)) { EXT4_ERROR_INODE_BLOCK(inode, block, "unable to read itable block"); brelse(bh); return -EIO; } } has_buffer: iloc->bh = bh; return 0; } int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc) { /* We have all inode data except xattrs in memory here. */ return __ext4_get_inode_loc(inode, iloc, !ext4_test_inode_state(inode, EXT4_STATE_XATTR)); } void ext4_set_inode_flags(struct inode *inode) { unsigned int flags = EXT4_I(inode)->i_flags; unsigned int new_fl = 0; if (flags & EXT4_SYNC_FL) new_fl |= S_SYNC; if (flags & EXT4_APPEND_FL) new_fl |= S_APPEND; if (flags & EXT4_IMMUTABLE_FL) new_fl |= S_IMMUTABLE; if (flags & EXT4_NOATIME_FL) new_fl |= S_NOATIME; if (flags & EXT4_DIRSYNC_FL) new_fl |= S_DIRSYNC; if (test_opt(inode->i_sb, DAX) && S_ISREG(inode->i_mode)) new_fl |= S_DAX; inode_set_flags(inode, new_fl, S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC|S_DAX); } /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */ void ext4_get_inode_flags(struct ext4_inode_info *ei) { unsigned int vfs_fl; unsigned long old_fl, new_fl; do { vfs_fl = ei->vfs_inode.i_flags; old_fl = ei->i_flags; new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL| EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL| EXT4_DIRSYNC_FL); if (vfs_fl & S_SYNC) new_fl |= EXT4_SYNC_FL; if (vfs_fl & S_APPEND) new_fl |= EXT4_APPEND_FL; if (vfs_fl & S_IMMUTABLE) new_fl |= EXT4_IMMUTABLE_FL; if (vfs_fl & S_NOATIME) new_fl |= EXT4_NOATIME_FL; if (vfs_fl & S_DIRSYNC) new_fl |= EXT4_DIRSYNC_FL; } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl); } static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode, struct ext4_inode_info *ei) { blkcnt_t i_blocks ; struct inode *inode = &(ei->vfs_inode); struct super_block *sb = inode->i_sb; if (ext4_has_feature_huge_file(sb)) { /* we are using combined 48 bit field */ i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 | le32_to_cpu(raw_inode->i_blocks_lo); if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) { /* i_blocks represent file system block size */ return i_blocks << (inode->i_blkbits - 9); } else { return i_blocks; } } else { return le32_to_cpu(raw_inode->i_blocks_lo); } } static inline void ext4_iget_extra_inode(struct inode *inode, struct ext4_inode *raw_inode, struct ext4_inode_info *ei) { __le32 *magic = (void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize; if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC)) { ext4_set_inode_state(inode, EXT4_STATE_XATTR); ext4_find_inline_data_nolock(inode); } else EXT4_I(inode)->i_inline_off = 0; } int ext4_get_projid(struct inode *inode, kprojid_t *projid) { if (!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_PROJECT)) return -EOPNOTSUPP; *projid = EXT4_I(inode)->i_projid; return 0; } struct inode *ext4_iget(struct super_block *sb, unsigned long ino) { struct ext4_iloc iloc; struct ext4_inode *raw_inode; struct ext4_inode_info *ei; struct inode *inode; journal_t *journal = EXT4_SB(sb)->s_journal; long ret; int block; uid_t i_uid; gid_t i_gid; projid_t i_projid; inode = iget_locked(sb, ino); if (!inode) return ERR_PTR(-ENOMEM); if (!(inode->i_state & I_NEW)) return inode; ei = EXT4_I(inode); iloc.bh = NULL; ret = __ext4_get_inode_loc(inode, &iloc, 0); if (ret < 0) goto bad_inode; raw_inode = ext4_raw_inode(&iloc); if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize); if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize > EXT4_INODE_SIZE(inode->i_sb)) { EXT4_ERROR_INODE(inode, "bad extra_isize (%u != %u)", EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize, EXT4_INODE_SIZE(inode->i_sb)); ret = -EFSCORRUPTED; goto bad_inode; } } else ei->i_extra_isize = 0; /* Precompute checksum seed for inode metadata */ if (ext4_has_metadata_csum(sb)) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); __u32 csum; __le32 inum = cpu_to_le32(inode->i_ino); __le32 gen = raw_inode->i_generation; csum = ext4_chksum(sbi, sbi->s_csum_seed, (__u8 *)&inum, sizeof(inum)); ei->i_csum_seed = ext4_chksum(sbi, csum, (__u8 *)&gen, sizeof(gen)); } if (!ext4_inode_csum_verify(inode, raw_inode, ei)) { EXT4_ERROR_INODE(inode, "checksum invalid"); ret = -EFSBADCRC; goto bad_inode; } inode->i_mode = le16_to_cpu(raw_inode->i_mode); i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low); i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low); if (EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_PROJECT) && EXT4_INODE_SIZE(sb) > EXT4_GOOD_OLD_INODE_SIZE && EXT4_FITS_IN_INODE(raw_inode, ei, i_projid)) i_projid = (projid_t)le32_to_cpu(raw_inode->i_projid); else i_projid = EXT4_DEF_PROJID; if (!(test_opt(inode->i_sb, NO_UID32))) { i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16; i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16; } i_uid_write(inode, i_uid); i_gid_write(inode, i_gid); ei->i_projid = make_kprojid(&init_user_ns, i_projid); set_nlink(inode, le16_to_cpu(raw_inode->i_links_count)); ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */ ei->i_inline_off = 0; ei->i_dir_start_lookup = 0; ei->i_dtime = le32_to_cpu(raw_inode->i_dtime); /* We now have enough fields to check if the inode was active or not. * This is needed because nfsd might try to access dead inodes * the test is that same one that e2fsck uses * NeilBrown 1999oct15 */ if (inode->i_nlink == 0) { if ((inode->i_mode == 0 || !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) && ino != EXT4_BOOT_LOADER_INO) { /* this inode is deleted */ ret = -ESTALE; goto bad_inode; } /* The only unlinked inodes we let through here have * valid i_mode and are being read by the orphan * recovery code: that's fine, we're about to complete * the process of deleting those. * OR it is the EXT4_BOOT_LOADER_INO which is * not initialized on a new filesystem. */ } ei->i_flags = le32_to_cpu(raw_inode->i_flags); inode->i_blocks = ext4_inode_blocks(raw_inode, ei); ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo); if (ext4_has_feature_64bit(sb)) ei->i_file_acl |= ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32; inode->i_size = ext4_isize(raw_inode); ei->i_disksize = inode->i_size; #ifdef CONFIG_QUOTA ei->i_reserved_quota = 0; #endif inode->i_generation = le32_to_cpu(raw_inode->i_generation); ei->i_block_group = iloc.block_group; ei->i_last_alloc_group = ~0; /* * NOTE! The in-memory inode i_data array is in little-endian order * even on big-endian machines: we do NOT byteswap the block numbers! */ for (block = 0; block < EXT4_N_BLOCKS; block++) ei->i_data[block] = raw_inode->i_block[block]; INIT_LIST_HEAD(&ei->i_orphan); /* * Set transaction id's of transactions that have to be committed * to finish f[data]sync. We set them to currently running transaction * as we cannot be sure that the inode or some of its metadata isn't * part of the transaction - the inode could have been reclaimed and * now it is reread from disk. */ if (journal) { transaction_t *transaction; tid_t tid; read_lock(&journal->j_state_lock); if (journal->j_running_transaction) transaction = journal->j_running_transaction; else transaction = journal->j_committing_transaction; if (transaction) tid = transaction->t_tid; else tid = journal->j_commit_sequence; read_unlock(&journal->j_state_lock); ei->i_sync_tid = tid; ei->i_datasync_tid = tid; } if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { if (ei->i_extra_isize == 0) { /* The extra space is currently unused. Use it. */ ei->i_extra_isize = sizeof(struct ext4_inode) - EXT4_GOOD_OLD_INODE_SIZE; } else { ext4_iget_extra_inode(inode, raw_inode, ei); } } EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode); EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode); EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode); EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode); if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) { inode->i_version = le32_to_cpu(raw_inode->i_disk_version); if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) { if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi)) inode->i_version |= (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32; } } ret = 0; if (ei->i_file_acl && !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) { EXT4_ERROR_INODE(inode, "bad extended attribute block %llu", ei->i_file_acl); ret = -EFSCORRUPTED; goto bad_inode; } else if (!ext4_has_inline_data(inode)) { if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) { if ((S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || (S_ISLNK(inode->i_mode) && !ext4_inode_is_fast_symlink(inode)))) /* Validate extent which is part of inode */ ret = ext4_ext_check_inode(inode); } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) || (S_ISLNK(inode->i_mode) && !ext4_inode_is_fast_symlink(inode))) { /* Validate block references which are part of inode */ ret = ext4_ind_check_inode(inode); } } if (ret) goto bad_inode; if (S_ISREG(inode->i_mode)) { inode->i_op = &ext4_file_inode_operations; inode->i_fop = &ext4_file_operations; ext4_set_aops(inode); } else if (S_ISDIR(inode->i_mode)) { inode->i_op = &ext4_dir_inode_operations; inode->i_fop = &ext4_dir_operations; } else if (S_ISLNK(inode->i_mode)) { if (ext4_encrypted_inode(inode)) { inode->i_op = &ext4_encrypted_symlink_inode_operations; ext4_set_aops(inode); } else if (ext4_inode_is_fast_symlink(inode)) { inode->i_link = (char *)ei->i_data; inode->i_op = &ext4_fast_symlink_inode_operations; nd_terminate_link(ei->i_data, inode->i_size, sizeof(ei->i_data) - 1); } else { inode->i_op = &ext4_symlink_inode_operations; ext4_set_aops(inode); } inode_nohighmem(inode); } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) || S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) { inode->i_op = &ext4_special_inode_operations; if (raw_inode->i_block[0]) init_special_inode(inode, inode->i_mode, old_decode_dev(le32_to_cpu(raw_inode->i_block[0]))); else init_special_inode(inode, inode->i_mode, new_decode_dev(le32_to_cpu(raw_inode->i_block[1]))); } else if (ino == EXT4_BOOT_LOADER_INO) { make_bad_inode(inode); } else { ret = -EFSCORRUPTED; EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode); goto bad_inode; } brelse(iloc.bh); ext4_set_inode_flags(inode); unlock_new_inode(inode); return inode; bad_inode: brelse(iloc.bh); iget_failed(inode); return ERR_PTR(ret); } struct inode *ext4_iget_normal(struct super_block *sb, unsigned long ino) { if (ino < EXT4_FIRST_INO(sb) && ino != EXT4_ROOT_INO) return ERR_PTR(-EFSCORRUPTED); return ext4_iget(sb, ino); } static int ext4_inode_blocks_set(handle_t *handle, struct ext4_inode *raw_inode, struct ext4_inode_info *ei) { struct inode *inode = &(ei->vfs_inode); u64 i_blocks = inode->i_blocks; struct super_block *sb = inode->i_sb; if (i_blocks <= ~0U) { /* * i_blocks can be represented in a 32 bit variable * as multiple of 512 bytes */ raw_inode->i_blocks_lo = cpu_to_le32(i_blocks); raw_inode->i_blocks_high = 0; ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE); return 0; } if (!ext4_has_feature_huge_file(sb)) return -EFBIG; if (i_blocks <= 0xffffffffffffULL) { /* * i_blocks can be represented in a 48 bit variable * as multiple of 512 bytes */ raw_inode->i_blocks_lo = cpu_to_le32(i_blocks); raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32); ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE); } else { ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE); /* i_block is stored in file system block size */ i_blocks = i_blocks >> (inode->i_blkbits - 9); raw_inode->i_blocks_lo = cpu_to_le32(i_blocks); raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32); } return 0; } struct other_inode { unsigned long orig_ino; struct ext4_inode *raw_inode; }; static int other_inode_match(struct inode * inode, unsigned long ino, void *data) { struct other_inode *oi = (struct other_inode *) data; if ((inode->i_ino != ino) || (inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW | I_DIRTY_SYNC | I_DIRTY_DATASYNC)) || ((inode->i_state & I_DIRTY_TIME) == 0)) return 0; spin_lock(&inode->i_lock); if (((inode->i_state & (I_FREEING | I_WILL_FREE | I_NEW | I_DIRTY_SYNC | I_DIRTY_DATASYNC)) == 0) && (inode->i_state & I_DIRTY_TIME)) { struct ext4_inode_info *ei = EXT4_I(inode); inode->i_state &= ~(I_DIRTY_TIME | I_DIRTY_TIME_EXPIRED); spin_unlock(&inode->i_lock); spin_lock(&ei->i_raw_lock); EXT4_INODE_SET_XTIME(i_ctime, inode, oi->raw_inode); EXT4_INODE_SET_XTIME(i_mtime, inode, oi->raw_inode); EXT4_INODE_SET_XTIME(i_atime, inode, oi->raw_inode); ext4_inode_csum_set(inode, oi->raw_inode, ei); spin_unlock(&ei->i_raw_lock); trace_ext4_other_inode_update_time(inode, oi->orig_ino); return -1; } spin_unlock(&inode->i_lock); return -1; } /* * Opportunistically update the other time fields for other inodes in * the same inode table block. */ static void ext4_update_other_inodes_time(struct super_block *sb, unsigned long orig_ino, char *buf) { struct other_inode oi; unsigned long ino; int i, inodes_per_block = EXT4_SB(sb)->s_inodes_per_block; int inode_size = EXT4_INODE_SIZE(sb); oi.orig_ino = orig_ino; /* * Calculate the first inode in the inode table block. Inode * numbers are one-based. That is, the first inode in a block * (assuming 4k blocks and 256 byte inodes) is (n*16 + 1). */ ino = ((orig_ino - 1) & ~(inodes_per_block - 1)) + 1; for (i = 0; i < inodes_per_block; i++, ino++, buf += inode_size) { if (ino == orig_ino) continue; oi.raw_inode = (struct ext4_inode *) buf; (void) find_inode_nowait(sb, ino, other_inode_match, &oi); } } /* * Post the struct inode info into an on-disk inode location in the * buffer-cache. This gobbles the caller's reference to the * buffer_head in the inode location struct. * * The caller must have write access to iloc->bh. */ static int ext4_do_update_inode(handle_t *handle, struct inode *inode, struct ext4_iloc *iloc) { struct ext4_inode *raw_inode = ext4_raw_inode(iloc); struct ext4_inode_info *ei = EXT4_I(inode); struct buffer_head *bh = iloc->bh; struct super_block *sb = inode->i_sb; int err = 0, rc, block; int need_datasync = 0, set_large_file = 0; uid_t i_uid; gid_t i_gid; projid_t i_projid; spin_lock(&ei->i_raw_lock); /* For fields not tracked in the in-memory inode, * initialise them to zero for new inodes. */ if (ext4_test_inode_state(inode, EXT4_STATE_NEW)) memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size); ext4_get_inode_flags(ei); raw_inode->i_mode = cpu_to_le16(inode->i_mode); i_uid = i_uid_read(inode); i_gid = i_gid_read(inode); i_projid = from_kprojid(&init_user_ns, ei->i_projid); if (!(test_opt(inode->i_sb, NO_UID32))) { raw_inode->i_uid_low = cpu_to_le16(low_16_bits(i_uid)); raw_inode->i_gid_low = cpu_to_le16(low_16_bits(i_gid)); /* * Fix up interoperability with old kernels. Otherwise, old inodes get * re-used with the upper 16 bits of the uid/gid intact */ if (!ei->i_dtime) { raw_inode->i_uid_high = cpu_to_le16(high_16_bits(i_uid)); raw_inode->i_gid_high = cpu_to_le16(high_16_bits(i_gid)); } else { raw_inode->i_uid_high = 0; raw_inode->i_gid_high = 0; } } else { raw_inode->i_uid_low = cpu_to_le16(fs_high2lowuid(i_uid)); raw_inode->i_gid_low = cpu_to_le16(fs_high2lowgid(i_gid)); raw_inode->i_uid_high = 0; raw_inode->i_gid_high = 0; } raw_inode->i_links_count = cpu_to_le16(inode->i_nlink); EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode); EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode); EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode); EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode); err = ext4_inode_blocks_set(handle, raw_inode, ei); if (err) { spin_unlock(&ei->i_raw_lock); goto out_brelse; } raw_inode->i_dtime = cpu_to_le32(ei->i_dtime); raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF); if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) raw_inode->i_file_acl_high = cpu_to_le16(ei->i_file_acl >> 32); raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl); if (ei->i_disksize != ext4_isize(raw_inode)) { ext4_isize_set(raw_inode, ei->i_disksize); need_datasync = 1; } if (ei->i_disksize > 0x7fffffffULL) { if (!ext4_has_feature_large_file(sb) || EXT4_SB(sb)->s_es->s_rev_level == cpu_to_le32(EXT4_GOOD_OLD_REV)) set_large_file = 1; } raw_inode->i_generation = cpu_to_le32(inode->i_generation); if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) { if (old_valid_dev(inode->i_rdev)) { raw_inode->i_block[0] = cpu_to_le32(old_encode_dev(inode->i_rdev)); raw_inode->i_block[1] = 0; } else { raw_inode->i_block[0] = 0; raw_inode->i_block[1] = cpu_to_le32(new_encode_dev(inode->i_rdev)); raw_inode->i_block[2] = 0; } } else if (!ext4_has_inline_data(inode)) { for (block = 0; block < EXT4_N_BLOCKS; block++) raw_inode->i_block[block] = ei->i_data[block]; } if (likely(!test_opt2(inode->i_sb, HURD_COMPAT))) { raw_inode->i_disk_version = cpu_to_le32(inode->i_version); if (ei->i_extra_isize) { if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi)) raw_inode->i_version_hi = cpu_to_le32(inode->i_version >> 32); raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize); } } BUG_ON(!EXT4_HAS_RO_COMPAT_FEATURE(inode->i_sb, EXT4_FEATURE_RO_COMPAT_PROJECT) && i_projid != EXT4_DEF_PROJID); if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE && EXT4_FITS_IN_INODE(raw_inode, ei, i_projid)) raw_inode->i_projid = cpu_to_le32(i_projid); ext4_inode_csum_set(inode, raw_inode, ei); spin_unlock(&ei->i_raw_lock); if (inode->i_sb->s_flags & MS_LAZYTIME) ext4_update_other_inodes_time(inode->i_sb, inode->i_ino, bh->b_data); BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata"); rc = ext4_handle_dirty_metadata(handle, NULL, bh); if (!err) err = rc; ext4_clear_inode_state(inode, EXT4_STATE_NEW); if (set_large_file) { BUFFER_TRACE(EXT4_SB(sb)->s_sbh, "get write access"); err = ext4_journal_get_write_access(handle, EXT4_SB(sb)->s_sbh); if (err) goto out_brelse; ext4_update_dynamic_rev(sb); ext4_set_feature_large_file(sb); ext4_handle_sync(handle); err = ext4_handle_dirty_super(handle, sb); } ext4_update_inode_fsync_trans(handle, inode, need_datasync); out_brelse: brelse(bh); ext4_std_error(inode->i_sb, err); return err; } /* * ext4_write_inode() * * We are called from a few places: * * - Within generic_file_aio_write() -> generic_write_sync() for O_SYNC files. * Here, there will be no transaction running. We wait for any running * transaction to commit. * * - Within flush work (sys_sync(), kupdate and such). * We wait on commit, if told to. * * - Within iput_final() -> write_inode_now() * We wait on commit, if told to. * * In all cases it is actually safe for us to return without doing anything, * because the inode has been copied into a raw inode buffer in * ext4_mark_inode_dirty(). This is a correctness thing for WB_SYNC_ALL * writeback. * * Note that we are absolutely dependent upon all inode dirtiers doing the * right thing: they *must* call mark_inode_dirty() after dirtying info in * which we are interested. * * It would be a bug for them to not do this. The code: * * mark_inode_dirty(inode) * stuff(); * inode->i_size = expr; * * is in error because write_inode() could occur while `stuff()' is running, * and the new i_size will be lost. Plus the inode will no longer be on the * superblock's dirty inode list. */ int ext4_write_inode(struct inode *inode, struct writeback_control *wbc) { int err; if (WARN_ON_ONCE(current->flags & PF_MEMALLOC)) return 0; if (EXT4_SB(inode->i_sb)->s_journal) { if (ext4_journal_current_handle()) { jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n"); dump_stack(); return -EIO; } /* * No need to force transaction in WB_SYNC_NONE mode. Also * ext4_sync_fs() will force the commit after everything is * written. */ if (wbc->sync_mode != WB_SYNC_ALL || wbc->for_sync) return 0; err = ext4_force_commit(inode->i_sb); } else { struct ext4_iloc iloc; err = __ext4_get_inode_loc(inode, &iloc, 0); if (err) return err; /* * sync(2) will flush the whole buffer cache. No need to do * it here separately for each inode. */ if (wbc->sync_mode == WB_SYNC_ALL && !wbc->for_sync) sync_dirty_buffer(iloc.bh); if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) { EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr, "IO error syncing inode"); err = -EIO; } brelse(iloc.bh); } return err; } /* * In data=journal mode ext4_journalled_invalidatepage() may fail to invalidate * buffers that are attached to a page stradding i_size and are undergoing * commit. In that case we have to wait for commit to finish and try again. */ static void ext4_wait_for_tail_page_commit(struct inode *inode) { struct page *page; unsigned offset; journal_t *journal = EXT4_SB(inode->i_sb)->s_journal; tid_t commit_tid = 0; int ret; offset = inode->i_size & (PAGE_SIZE - 1); /* * All buffers in the last page remain valid? Then there's nothing to * do. We do the check mainly to optimize the common PAGE_SIZE == * blocksize case */ if (offset > PAGE_SIZE - (1 << inode->i_blkbits)) return; while (1) { page = find_lock_page(inode->i_mapping, inode->i_size >> PAGE_SHIFT); if (!page) return; ret = __ext4_journalled_invalidatepage(page, offset, PAGE_SIZE - offset); unlock_page(page); put_page(page); if (ret != -EBUSY) return; commit_tid = 0; read_lock(&journal->j_state_lock); if (journal->j_committing_transaction) commit_tid = journal->j_committing_transaction->t_tid; read_unlock(&journal->j_state_lock); if (commit_tid) jbd2_log_wait_commit(journal, commit_tid); } } /* * ext4_setattr() * * Called from notify_change. * * We want to trap VFS attempts to truncate the file as soon as * possible. In particular, we want to make sure that when the VFS * shrinks i_size, we put the inode on the orphan list and modify * i_disksize immediately, so that during the subsequent flushing of * dirty pages and freeing of disk blocks, we can guarantee that any * commit will leave the blocks being flushed in an unused state on * disk. (On recovery, the inode will get truncated and the blocks will * be freed, so we have a strong guarantee that no future commit will * leave these blocks visible to the user.) * * Another thing we have to assure is that if we are in ordered mode * and inode is still attached to the committing transaction, we must * we start writeout of all the dirty pages which are being truncated. * This way we are sure that all the data written in the previous * transaction are already on disk (truncate waits for pages under * writeback). * * Called with inode->i_mutex down. */ int ext4_setattr(struct dentry *dentry, struct iattr *attr) { struct inode *inode = d_inode(dentry); int error, rc = 0; int orphan = 0; const unsigned int ia_valid = attr->ia_valid; error = inode_change_ok(inode, attr); if (error) return error; if (is_quota_modification(inode, attr)) { error = dquot_initialize(inode); if (error) return error; } if ((ia_valid & ATTR_UID && !uid_eq(attr->ia_uid, inode->i_uid)) || (ia_valid & ATTR_GID && !gid_eq(attr->ia_gid, inode->i_gid))) { handle_t *handle; /* (user+group)*(old+new) structure, inode write (sb, * inode block, ? - but truncate inode update has it) */ handle = ext4_journal_start(inode, EXT4_HT_QUOTA, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb) + EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb)) + 3); if (IS_ERR(handle)) { error = PTR_ERR(handle); goto err_out; } error = dquot_transfer(inode, attr); if (error) { ext4_journal_stop(handle); return error; } /* Update corresponding info in inode so that everything is in * one transaction */ if (attr->ia_valid & ATTR_UID) inode->i_uid = attr->ia_uid; if (attr->ia_valid & ATTR_GID) inode->i_gid = attr->ia_gid; error = ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); } if (attr->ia_valid & ATTR_SIZE) { handle_t *handle; loff_t oldsize = inode->i_size; int shrink = (attr->ia_size <= inode->i_size); if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) { struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); if (attr->ia_size > sbi->s_bitmap_maxbytes) return -EFBIG; } if (!S_ISREG(inode->i_mode)) return -EINVAL; if (IS_I_VERSION(inode) && attr->ia_size != inode->i_size) inode_inc_iversion(inode); if (ext4_should_order_data(inode) && (attr->ia_size < inode->i_size)) { error = ext4_begin_ordered_truncate(inode, attr->ia_size); if (error) goto err_out; } if (attr->ia_size != inode->i_size) { handle = ext4_journal_start(inode, EXT4_HT_INODE, 3); if (IS_ERR(handle)) { error = PTR_ERR(handle); goto err_out; } if (ext4_handle_valid(handle) && shrink) { error = ext4_orphan_add(handle, inode); orphan = 1; } /* * Update c/mtime on truncate up, ext4_truncate() will * update c/mtime in shrink case below */ if (!shrink) { inode->i_mtime = ext4_current_time(inode); inode->i_ctime = inode->i_mtime; } down_write(&EXT4_I(inode)->i_data_sem); EXT4_I(inode)->i_disksize = attr->ia_size; rc = ext4_mark_inode_dirty(handle, inode); if (!error) error = rc; /* * We have to update i_size under i_data_sem together * with i_disksize to avoid races with writeback code * running ext4_wb_update_i_disksize(). */ if (!error) i_size_write(inode, attr->ia_size); up_write(&EXT4_I(inode)->i_data_sem); ext4_journal_stop(handle); if (error) { if (orphan) ext4_orphan_del(NULL, inode); goto err_out; } } if (!shrink) pagecache_isize_extended(inode, oldsize, inode->i_size); /* * Blocks are going to be removed from the inode. Wait * for dio in flight. Temporarily disable * dioread_nolock to prevent livelock. */ if (orphan) { if (!ext4_should_journal_data(inode)) { ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); ext4_inode_resume_unlocked_dio(inode); } else ext4_wait_for_tail_page_commit(inode); } down_write(&EXT4_I(inode)->i_mmap_sem); /* * Truncate pagecache after we've waited for commit * in data=journal mode to make pages freeable. */ truncate_pagecache(inode, inode->i_size); if (shrink) ext4_truncate(inode); up_write(&EXT4_I(inode)->i_mmap_sem); } if (!rc) { setattr_copy(inode, attr); mark_inode_dirty(inode); } /* * If the call to ext4_truncate failed to get a transaction handle at * all, we need to clean up the in-core orphan list manually. */ if (orphan && inode->i_nlink) ext4_orphan_del(NULL, inode); if (!rc && (ia_valid & ATTR_MODE)) rc = posix_acl_chmod(inode, inode->i_mode); err_out: ext4_std_error(inode->i_sb, error); if (!error) error = rc; return error; } int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry, struct kstat *stat) { struct inode *inode; unsigned long long delalloc_blocks; inode = d_inode(dentry); generic_fillattr(inode, stat); /* * If there is inline data in the inode, the inode will normally not * have data blocks allocated (it may have an external xattr block). * Report at least one sector for such files, so tools like tar, rsync, * others doen't incorrectly think the file is completely sparse. */ if (unlikely(ext4_has_inline_data(inode))) stat->blocks += (stat->size + 511) >> 9; /* * We can't update i_blocks if the block allocation is delayed * otherwise in the case of system crash before the real block * allocation is done, we will have i_blocks inconsistent with * on-disk file blocks. * We always keep i_blocks updated together with real * allocation. But to not confuse with user, stat * will return the blocks that include the delayed allocation * blocks for this file. */ delalloc_blocks = EXT4_C2B(EXT4_SB(inode->i_sb), EXT4_I(inode)->i_reserved_data_blocks); stat->blocks += delalloc_blocks << (inode->i_sb->s_blocksize_bits - 9); return 0; } static int ext4_index_trans_blocks(struct inode *inode, int lblocks, int pextents) { if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) return ext4_ind_trans_blocks(inode, lblocks); return ext4_ext_index_trans_blocks(inode, pextents); } /* * Account for index blocks, block groups bitmaps and block group * descriptor blocks if modify datablocks and index blocks * worse case, the indexs blocks spread over different block groups * * If datablocks are discontiguous, they are possible to spread over * different block groups too. If they are contiguous, with flexbg, * they could still across block group boundary. * * Also account for superblock, inode, quota and xattr blocks */ static int ext4_meta_trans_blocks(struct inode *inode, int lblocks, int pextents) { ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb); int gdpblocks; int idxblocks; int ret = 0; /* * How many index blocks need to touch to map @lblocks logical blocks * to @pextents physical extents? */ idxblocks = ext4_index_trans_blocks(inode, lblocks, pextents); ret = idxblocks; /* * Now let's see how many group bitmaps and group descriptors need * to account */ groups = idxblocks + pextents; gdpblocks = groups; if (groups > ngroups) groups = ngroups; if (groups > EXT4_SB(inode->i_sb)->s_gdb_count) gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count; /* bitmaps and block group descriptor blocks */ ret += groups + gdpblocks; /* Blocks for super block, inode, quota and xattr blocks */ ret += EXT4_META_TRANS_BLOCKS(inode->i_sb); return ret; } /* * Calculate the total number of credits to reserve to fit * the modification of a single pages into a single transaction, * which may include multiple chunks of block allocations. * * This could be called via ext4_write_begin() * * We need to consider the worse case, when * one new block per extent. */ int ext4_writepage_trans_blocks(struct inode *inode) { int bpp = ext4_journal_blocks_per_page(inode); int ret; ret = ext4_meta_trans_blocks(inode, bpp, bpp); /* Account for data blocks for journalled mode */ if (ext4_should_journal_data(inode)) ret += bpp; return ret; } /* * Calculate the journal credits for a chunk of data modification. * * This is called from DIO, fallocate or whoever calling * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks. * * journal buffers for data blocks are not included here, as DIO * and fallocate do no need to journal data buffers. */ int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks) { return ext4_meta_trans_blocks(inode, nrblocks, 1); } /* * The caller must have previously called ext4_reserve_inode_write(). * Give this, we know that the caller already has write access to iloc->bh. */ int ext4_mark_iloc_dirty(handle_t *handle, struct inode *inode, struct ext4_iloc *iloc) { int err = 0; if (IS_I_VERSION(inode)) inode_inc_iversion(inode); /* the do_update_inode consumes one bh->b_count */ get_bh(iloc->bh); /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */ err = ext4_do_update_inode(handle, inode, iloc); put_bh(iloc->bh); return err; } /* * On success, We end up with an outstanding reference count against * iloc->bh. This _must_ be cleaned up later. */ int ext4_reserve_inode_write(handle_t *handle, struct inode *inode, struct ext4_iloc *iloc) { int err; err = ext4_get_inode_loc(inode, iloc); if (!err) { BUFFER_TRACE(iloc->bh, "get_write_access"); err = ext4_journal_get_write_access(handle, iloc->bh); if (err) { brelse(iloc->bh); iloc->bh = NULL; } } ext4_std_error(inode->i_sb, err); return err; } /* * Expand an inode by new_extra_isize bytes. * Returns 0 on success or negative error number on failure. */ static int ext4_expand_extra_isize(struct inode *inode, unsigned int new_extra_isize, struct ext4_iloc iloc, handle_t *handle) { struct ext4_inode *raw_inode; struct ext4_xattr_ibody_header *header; if (EXT4_I(inode)->i_extra_isize >= new_extra_isize) return 0; raw_inode = ext4_raw_inode(&iloc); header = IHDR(inode, raw_inode); /* No extended attributes present */ if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) || header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) { memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0, new_extra_isize); EXT4_I(inode)->i_extra_isize = new_extra_isize; return 0; } /* try to expand with EAs present */ return ext4_expand_extra_isize_ea(inode, new_extra_isize, raw_inode, handle); } /* * What we do here is to mark the in-core inode as clean with respect to inode * dirtiness (it may still be data-dirty). * This means that the in-core inode may be reaped by prune_icache * without having to perform any I/O. This is a very good thing, * because *any* task may call prune_icache - even ones which * have a transaction open against a different journal. * * Is this cheating? Not really. Sure, we haven't written the * inode out, but prune_icache isn't a user-visible syncing function. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync) * we start and wait on commits. */ int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode) { struct ext4_iloc iloc; struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb); static unsigned int mnt_count; int err, ret; might_sleep(); trace_ext4_mark_inode_dirty(inode, _RET_IP_); err = ext4_reserve_inode_write(handle, inode, &iloc); if (err) return err; if (ext4_handle_valid(handle) && EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize && !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) { /* * We need extra buffer credits since we may write into EA block * with this same handle. If journal_extend fails, then it will * only result in a minor loss of functionality for that inode. * If this is felt to be critical, then e2fsck should be run to * force a large enough s_min_extra_isize. */ if ((jbd2_journal_extend(handle, EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) { ret = ext4_expand_extra_isize(inode, sbi->s_want_extra_isize, iloc, handle); if (ret) { ext4_set_inode_state(inode, EXT4_STATE_NO_EXPAND); if (mnt_count != le16_to_cpu(sbi->s_es->s_mnt_count)) { ext4_warning(inode->i_sb, "Unable to expand inode %lu. Delete" " some EAs or run e2fsck.", inode->i_ino); mnt_count = le16_to_cpu(sbi->s_es->s_mnt_count); } } } } return ext4_mark_iloc_dirty(handle, inode, &iloc); } /* * ext4_dirty_inode() is called from __mark_inode_dirty() * * We're really interested in the case where a file is being extended. * i_size has been changed by generic_commit_write() and we thus need * to include the updated inode in the current transaction. * * Also, dquot_alloc_block() will always dirty the inode when blocks * are allocated to the file. * * If the inode is marked synchronous, we don't honour that here - doing * so would cause a commit on atime updates, which we don't bother doing. * We handle synchronous inodes at the highest possible level. * * If only the I_DIRTY_TIME flag is set, we can skip everything. If * I_DIRTY_TIME and I_DIRTY_SYNC is set, the only inode fields we need * to copy into the on-disk inode structure are the timestamp files. */ void ext4_dirty_inode(struct inode *inode, int flags) { handle_t *handle; if (flags == I_DIRTY_TIME) return; handle = ext4_journal_start(inode, EXT4_HT_INODE, 2); if (IS_ERR(handle)) goto out; ext4_mark_inode_dirty(handle, inode); ext4_journal_stop(handle); out: return; } #if 0 /* * Bind an inode's backing buffer_head into this transaction, to prevent * it from being flushed to disk early. Unlike * ext4_reserve_inode_write, this leaves behind no bh reference and * returns no iloc structure, so the caller needs to repeat the iloc * lookup to mark the inode dirty later. */ static int ext4_pin_inode(handle_t *handle, struct inode *inode) { struct ext4_iloc iloc; int err = 0; if (handle) { err = ext4_get_inode_loc(inode, &iloc); if (!err) { BUFFER_TRACE(iloc.bh, "get_write_access"); err = jbd2_journal_get_write_access(handle, iloc.bh); if (!err) err = ext4_handle_dirty_metadata(handle, NULL, iloc.bh); brelse(iloc.bh); } } ext4_std_error(inode->i_sb, err); return err; } #endif int ext4_change_inode_journal_flag(struct inode *inode, int val) { journal_t *journal; handle_t *handle; int err; /* * We have to be very careful here: changing a data block's * journaling status dynamically is dangerous. If we write a * data block to the journal, change the status and then delete * that block, we risk forgetting to revoke the old log record * from the journal and so a subsequent replay can corrupt data. * So, first we make sure that the journal is empty and that * nobody is changing anything. */ journal = EXT4_JOURNAL(inode); if (!journal) return 0; if (is_journal_aborted(journal)) return -EROFS; /* We have to allocate physical blocks for delalloc blocks * before flushing journal. otherwise delalloc blocks can not * be allocated any more. even more truncate on delalloc blocks * could trigger BUG by flushing delalloc blocks in journal. * There is no delalloc block in non-journal data mode. */ if (val && test_opt(inode->i_sb, DELALLOC)) { err = ext4_alloc_da_blocks(inode); if (err < 0) return err; } /* Wait for all existing dio workers */ ext4_inode_block_unlocked_dio(inode); inode_dio_wait(inode); jbd2_journal_lock_updates(journal); /* * OK, there are no updates running now, and all cached data is * synced to disk. We are now in a completely consistent state * which doesn't have anything in the journal, and we know that * no filesystem updates are running, so it is safe to modify * the inode's in-core data-journaling state flag now. */ if (val) ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); else { err = jbd2_journal_flush(journal); if (err < 0) { jbd2_journal_unlock_updates(journal); ext4_inode_resume_unlocked_dio(inode); return err; } ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA); } ext4_set_aops(inode); jbd2_journal_unlock_updates(journal); ext4_inode_resume_unlocked_dio(inode); /* Finally we can mark the inode as dirty. */ handle = ext4_journal_start(inode, EXT4_HT_INODE, 1); if (IS_ERR(handle)) return PTR_ERR(handle); err = ext4_mark_inode_dirty(handle, inode); ext4_handle_sync(handle); ext4_journal_stop(handle); ext4_std_error(inode->i_sb, err); return err; } static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh) { return !buffer_mapped(bh); } int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf) { struct page *page = vmf->page; loff_t size; unsigned long len; int ret; struct file *file = vma->vm_file; struct inode *inode = file_inode(file); struct address_space *mapping = inode->i_mapping; handle_t *handle; get_block_t *get_block; int retries = 0; sb_start_pagefault(inode->i_sb); file_update_time(vma->vm_file); down_read(&EXT4_I(inode)->i_mmap_sem); /* Delalloc case is easy... */ if (test_opt(inode->i_sb, DELALLOC) && !ext4_should_journal_data(inode) && !ext4_nonda_switch(inode->i_sb)) { do { ret = block_page_mkwrite(vma, vmf, ext4_da_get_block_prep); } while (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)); goto out_ret; } lock_page(page); size = i_size_read(inode); /* Page got truncated from under us? */ if (page->mapping != mapping || page_offset(page) > size) { unlock_page(page); ret = VM_FAULT_NOPAGE; goto out; } if (page->index == size >> PAGE_SHIFT) len = size & ~PAGE_MASK; else len = PAGE_SIZE; /* * Return if we have all the buffers mapped. This avoids the need to do * journal_start/journal_stop which can block and take a long time */ if (page_has_buffers(page)) { if (!ext4_walk_page_buffers(NULL, page_buffers(page), 0, len, NULL, ext4_bh_unmapped)) { /* Wait so that we don't change page under IO */ wait_for_stable_page(page); ret = VM_FAULT_LOCKED; goto out; } } unlock_page(page); /* OK, we need to fill the hole... */ if (ext4_should_dioread_nolock(inode)) get_block = ext4_get_block_unwritten; else get_block = ext4_get_block; retry_alloc: handle = ext4_journal_start(inode, EXT4_HT_WRITE_PAGE, ext4_writepage_trans_blocks(inode)); if (IS_ERR(handle)) { ret = VM_FAULT_SIGBUS; goto out; } ret = block_page_mkwrite(vma, vmf, get_block); if (!ret && ext4_should_journal_data(inode)) { if (ext4_walk_page_buffers(handle, page_buffers(page), 0, PAGE_SIZE, NULL, do_journal_get_write_access)) { unlock_page(page); ret = VM_FAULT_SIGBUS; ext4_journal_stop(handle); goto out; } ext4_set_inode_state(inode, EXT4_STATE_JDATA); } ext4_journal_stop(handle); if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries)) goto retry_alloc; out_ret: ret = block_page_mkwrite_return(ret); out: up_read(&EXT4_I(inode)->i_mmap_sem); sb_end_pagefault(inode->i_sb); return ret; } int ext4_filemap_fault(struct vm_area_struct *vma, struct vm_fault *vmf) { struct inode *inode = file_inode(vma->vm_file); int err; down_read(&EXT4_I(inode)->i_mmap_sem); err = filemap_fault(vma, vmf); up_read(&EXT4_I(inode)->i_mmap_sem); return err; } /* * Find the first extent at or after @lblk in an inode that is not a hole. * Search for @map_len blocks at most. The extent is returned in @result. * * The function returns 1 if we found an extent. The function returns 0 in * case there is no extent at or after @lblk and in that case also sets * @result->es_len to 0. In case of error, the error code is returned. */ int ext4_get_next_extent(struct inode *inode, ext4_lblk_t lblk, unsigned int map_len, struct extent_status *result) { struct ext4_map_blocks map; struct extent_status es = {}; int ret; map.m_lblk = lblk; map.m_len = map_len; /* * For non-extent based files this loop may iterate several times since * we do not determine full hole size. */ while (map.m_len > 0) { ret = ext4_map_blocks(NULL, inode, &map, 0); if (ret < 0) return ret; /* There's extent covering m_lblk? Just return it. */ if (ret > 0) { int status; ext4_es_store_pblock(result, map.m_pblk); result->es_lblk = map.m_lblk; result->es_len = map.m_len; if (map.m_flags & EXT4_MAP_UNWRITTEN) status = EXTENT_STATUS_UNWRITTEN; else status = EXTENT_STATUS_WRITTEN; ext4_es_store_status(result, status); return 1; } ext4_es_find_delayed_extent_range(inode, map.m_lblk, map.m_lblk + map.m_len - 1, &es); /* Is delalloc data before next block in extent tree? */ if (es.es_len && es.es_lblk < map.m_lblk + map.m_len) { ext4_lblk_t offset = 0; if (es.es_lblk < lblk) offset = lblk - es.es_lblk; result->es_lblk = es.es_lblk + offset; ext4_es_store_pblock(result, ext4_es_pblock(&es) + offset); result->es_len = es.es_len - offset; ext4_es_store_status(result, ext4_es_status(&es)); return 1; } /* There's a hole at m_lblk, advance us after it */ map.m_lblk += map.m_len; map_len -= map.m_len; map.m_len = map_len; cond_resched(); } result->es_len = 0; return 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3270_0
crossvul-cpp_data_bad_506_0
/* * ipddp.c: IP to Appletalk-IP Encapsulation driver for Linux * Appletalk-IP to IP Decapsulation driver for Linux * * Authors: * - DDP-IP Encap by: Bradford W. Johnson <johns393@maroon.tc.umn.edu> * - DDP-IP Decap by: Jay Schulist <jschlst@samba.org> * * Derived from: * - Almost all code already existed in net/appletalk/ddp.c I just * moved/reorginized it into a driver file. Original IP-over-DDP code * was done by Bradford W. Johnson <johns393@maroon.tc.umn.edu> * - skeleton.c: A network driver outline for linux. * Written 1993-94 by Donald Becker. * - dummy.c: A dummy net driver. By Nick Holloway. * - MacGate: A user space Daemon for Appletalk-IP Decap for * Linux by Jay Schulist <jschlst@samba.org> * * Copyright 1993 United States Government as represented by the * Director, National Security Agency. * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ip.h> #include <linux/atalk.h> #include <linux/if_arp.h> #include <linux/slab.h> #include <net/route.h> #include <linux/uaccess.h> #include "ipddp.h" /* Our stuff */ static const char version[] = KERN_INFO "ipddp.c:v0.01 8/28/97 Bradford W. Johnson <johns393@maroon.tc.umn.edu>\n"; static struct ipddp_route *ipddp_route_list; static DEFINE_SPINLOCK(ipddp_route_lock); #ifdef CONFIG_IPDDP_ENCAP static int ipddp_mode = IPDDP_ENCAP; #else static int ipddp_mode = IPDDP_DECAP; #endif /* Index to functions, as function prototypes. */ static netdev_tx_t ipddp_xmit(struct sk_buff *skb, struct net_device *dev); static int ipddp_create(struct ipddp_route *new_rt); static int ipddp_delete(struct ipddp_route *rt); static struct ipddp_route* __ipddp_find_route(struct ipddp_route *rt); static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd); static const struct net_device_ops ipddp_netdev_ops = { .ndo_start_xmit = ipddp_xmit, .ndo_do_ioctl = ipddp_ioctl, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static struct net_device * __init ipddp_init(void) { static unsigned version_printed; struct net_device *dev; int err; dev = alloc_etherdev(0); if (!dev) return ERR_PTR(-ENOMEM); netif_keep_dst(dev); strcpy(dev->name, "ipddp%d"); if (version_printed++ == 0) printk(version); /* Initialize the device structure. */ dev->netdev_ops = &ipddp_netdev_ops; dev->type = ARPHRD_IPDDP; /* IP over DDP tunnel */ dev->mtu = 585; dev->flags |= IFF_NOARP; /* * The worst case header we will need is currently a * ethernet header (14 bytes) and a ddp header (sizeof ddpehdr+1) * We send over SNAP so that takes another 8 bytes. */ dev->hard_header_len = 14+8+sizeof(struct ddpehdr)+1; err = register_netdev(dev); if (err) { free_netdev(dev); return ERR_PTR(err); } /* Let the user now what mode we are in */ if(ipddp_mode == IPDDP_ENCAP) printk("%s: Appletalk-IP Encap. mode by Bradford W. Johnson <johns393@maroon.tc.umn.edu>\n", dev->name); if(ipddp_mode == IPDDP_DECAP) printk("%s: Appletalk-IP Decap. mode by Jay Schulist <jschlst@samba.org>\n", dev->name); return dev; } /* * Transmit LLAP/ELAP frame using aarp_send_ddp. */ static netdev_tx_t ipddp_xmit(struct sk_buff *skb, struct net_device *dev) { __be32 paddr = skb_rtable(skb)->rt_gateway; struct ddpehdr *ddp; struct ipddp_route *rt; struct atalk_addr *our_addr; spin_lock(&ipddp_route_lock); /* * Find appropriate route to use, based only on IP number. */ for(rt = ipddp_route_list; rt != NULL; rt = rt->next) { if(rt->ip == paddr) break; } if(rt == NULL) { spin_unlock(&ipddp_route_lock); return NETDEV_TX_OK; } our_addr = atalk_find_dev_addr(rt->dev); if(ipddp_mode == IPDDP_DECAP) /* * Pull off the excess room that should not be there. * This is due to a hard-header problem. This is the * quick fix for now though, till it breaks. */ skb_pull(skb, 35-(sizeof(struct ddpehdr)+1)); /* Create the Extended DDP header */ ddp = (struct ddpehdr *)skb->data; ddp->deh_len_hops = htons(skb->len + (1<<10)); ddp->deh_sum = 0; /* * For Localtalk we need aarp_send_ddp to strip the * long DDP header and place a shot DDP header on it. */ if(rt->dev->type == ARPHRD_LOCALTLK) { ddp->deh_dnet = 0; /* FIXME more hops?? */ ddp->deh_snet = 0; } else { ddp->deh_dnet = rt->at.s_net; /* FIXME more hops?? */ ddp->deh_snet = our_addr->s_net; } ddp->deh_dnode = rt->at.s_node; ddp->deh_snode = our_addr->s_node; ddp->deh_dport = 72; ddp->deh_sport = 72; *((__u8 *)(ddp+1)) = 22; /* ddp type = IP */ skb->protocol = htons(ETH_P_ATALK); /* Protocol has changed */ dev->stats.tx_packets++; dev->stats.tx_bytes += skb->len; aarp_send_ddp(rt->dev, skb, &rt->at, NULL); spin_unlock(&ipddp_route_lock); return NETDEV_TX_OK; } /* * Create a routing entry. We first verify that the * record does not already exist. If it does we return -EEXIST */ static int ipddp_create(struct ipddp_route *new_rt) { struct ipddp_route *rt = kzalloc(sizeof(*rt), GFP_KERNEL); if (rt == NULL) return -ENOMEM; rt->ip = new_rt->ip; rt->at = new_rt->at; rt->next = NULL; if ((rt->dev = atrtr_get_dev(&rt->at)) == NULL) { kfree(rt); return -ENETUNREACH; } spin_lock_bh(&ipddp_route_lock); if (__ipddp_find_route(rt)) { spin_unlock_bh(&ipddp_route_lock); kfree(rt); return -EEXIST; } rt->next = ipddp_route_list; ipddp_route_list = rt; spin_unlock_bh(&ipddp_route_lock); return 0; } /* * Delete a route, we only delete a FULL match. * If route does not exist we return -ENOENT. */ static int ipddp_delete(struct ipddp_route *rt) { struct ipddp_route **r = &ipddp_route_list; struct ipddp_route *tmp; spin_lock_bh(&ipddp_route_lock); while((tmp = *r) != NULL) { if(tmp->ip == rt->ip && tmp->at.s_net == rt->at.s_net && tmp->at.s_node == rt->at.s_node) { *r = tmp->next; spin_unlock_bh(&ipddp_route_lock); kfree(tmp); return 0; } r = &tmp->next; } spin_unlock_bh(&ipddp_route_lock); return -ENOENT; } /* * Find a routing entry, we only return a FULL match */ static struct ipddp_route* __ipddp_find_route(struct ipddp_route *rt) { struct ipddp_route *f; for(f = ipddp_route_list; f != NULL; f = f->next) { if(f->ip == rt->ip && f->at.s_net == rt->at.s_net && f->at.s_node == rt->at.s_node) return f; } return NULL; } static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct ipddp_route __user *rt = ifr->ifr_data; struct ipddp_route rcp, rcp2, *rp; if(!capable(CAP_NET_ADMIN)) return -EPERM; if(copy_from_user(&rcp, rt, sizeof(rcp))) return -EFAULT; switch(cmd) { case SIOCADDIPDDPRT: return ipddp_create(&rcp); case SIOCFINDIPDDPRT: spin_lock_bh(&ipddp_route_lock); rp = __ipddp_find_route(&rcp); if (rp) memcpy(&rcp2, rp, sizeof(rcp2)); spin_unlock_bh(&ipddp_route_lock); if (rp) { if (copy_to_user(rt, &rcp2, sizeof(struct ipddp_route))) return -EFAULT; return 0; } else return -ENOENT; case SIOCDELIPDDPRT: return ipddp_delete(&rcp); default: return -EINVAL; } } static struct net_device *dev_ipddp; MODULE_LICENSE("GPL"); module_param(ipddp_mode, int, 0); static int __init ipddp_init_module(void) { dev_ipddp = ipddp_init(); return PTR_ERR_OR_ZERO(dev_ipddp); } static void __exit ipddp_cleanup_module(void) { struct ipddp_route *p; unregister_netdev(dev_ipddp); free_netdev(dev_ipddp); while (ipddp_route_list) { p = ipddp_route_list->next; kfree(ipddp_route_list); ipddp_route_list = p; } } module_init(ipddp_init_module); module_exit(ipddp_cleanup_module);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_506_0
crossvul-cpp_data_bad_460_0
/* * Crypto user configuration API. * * Copyright (C) 2011 secunet Security Networks AG * Copyright (C) 2011 Steffen Klassert <steffen.klassert@secunet.com> * * This program is free software; you can redistribute it and/or modify it * under the terms and conditions of the GNU General Public License, * version 2, as published by the Free Software Foundation. * * This program is distributed in the hope it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along with * this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. */ #include <linux/module.h> #include <linux/crypto.h> #include <linux/cryptouser.h> #include <linux/sched.h> #include <net/netlink.h> #include <linux/security.h> #include <net/net_namespace.h> #include <crypto/internal/skcipher.h> #include <crypto/internal/rng.h> #include <crypto/akcipher.h> #include <crypto/kpp.h> #include <crypto/internal/cryptouser.h> #include "internal.h" #define null_terminated(x) (strnlen(x, sizeof(x)) < sizeof(x)) static DEFINE_MUTEX(crypto_cfg_mutex); /* The crypto netlink socket */ struct sock *crypto_nlsk; struct crypto_dump_info { struct sk_buff *in_skb; struct sk_buff *out_skb; u32 nlmsg_seq; u16 nlmsg_flags; }; struct crypto_alg *crypto_alg_match(struct crypto_user_alg *p, int exact) { struct crypto_alg *q, *alg = NULL; down_read(&crypto_alg_sem); list_for_each_entry(q, &crypto_alg_list, cra_list) { int match = 0; if ((q->cra_flags ^ p->cru_type) & p->cru_mask) continue; if (strlen(p->cru_driver_name)) match = !strcmp(q->cra_driver_name, p->cru_driver_name); else if (!exact) match = !strcmp(q->cra_name, p->cru_name); if (!match) continue; if (unlikely(!crypto_mod_get(q))) continue; alg = q; break; } up_read(&crypto_alg_sem); return alg; } static int crypto_report_cipher(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_cipher rcipher; strlcpy(rcipher.type, "cipher", sizeof(rcipher.type)); rcipher.blocksize = alg->cra_blocksize; rcipher.min_keysize = alg->cra_cipher.cia_min_keysize; rcipher.max_keysize = alg->cra_cipher.cia_max_keysize; if (nla_put(skb, CRYPTOCFGA_REPORT_CIPHER, sizeof(struct crypto_report_cipher), &rcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_comp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_comp rcomp; strlcpy(rcomp.type, "compression", sizeof(rcomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_COMPRESS, sizeof(struct crypto_report_comp), &rcomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_acomp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_acomp racomp; strlcpy(racomp.type, "acomp", sizeof(racomp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_ACOMP, sizeof(struct crypto_report_acomp), &racomp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_akcipher(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_akcipher rakcipher; strlcpy(rakcipher.type, "akcipher", sizeof(rakcipher.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_AKCIPHER, sizeof(struct crypto_report_akcipher), &rakcipher)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_kpp(struct sk_buff *skb, struct crypto_alg *alg) { struct crypto_report_kpp rkpp; strlcpy(rkpp.type, "kpp", sizeof(rkpp.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_KPP, sizeof(struct crypto_report_kpp), &rkpp)) goto nla_put_failure; return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_one(struct crypto_alg *alg, struct crypto_user_alg *ualg, struct sk_buff *skb) { strlcpy(ualg->cru_name, alg->cra_name, sizeof(ualg->cru_name)); strlcpy(ualg->cru_driver_name, alg->cra_driver_name, sizeof(ualg->cru_driver_name)); strlcpy(ualg->cru_module_name, module_name(alg->cra_module), sizeof(ualg->cru_module_name)); ualg->cru_type = 0; ualg->cru_mask = 0; ualg->cru_flags = alg->cra_flags; ualg->cru_refcnt = refcount_read(&alg->cra_refcnt); if (nla_put_u32(skb, CRYPTOCFGA_PRIORITY_VAL, alg->cra_priority)) goto nla_put_failure; if (alg->cra_flags & CRYPTO_ALG_LARVAL) { struct crypto_report_larval rl; strlcpy(rl.type, "larval", sizeof(rl.type)); if (nla_put(skb, CRYPTOCFGA_REPORT_LARVAL, sizeof(struct crypto_report_larval), &rl)) goto nla_put_failure; goto out; } if (alg->cra_type && alg->cra_type->report) { if (alg->cra_type->report(skb, alg)) goto nla_put_failure; goto out; } switch (alg->cra_flags & (CRYPTO_ALG_TYPE_MASK | CRYPTO_ALG_LARVAL)) { case CRYPTO_ALG_TYPE_CIPHER: if (crypto_report_cipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_COMPRESS: if (crypto_report_comp(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_ACOMPRESS: if (crypto_report_acomp(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_AKCIPHER: if (crypto_report_akcipher(skb, alg)) goto nla_put_failure; break; case CRYPTO_ALG_TYPE_KPP: if (crypto_report_kpp(skb, alg)) goto nla_put_failure; break; } out: return 0; nla_put_failure: return -EMSGSIZE; } static int crypto_report_alg(struct crypto_alg *alg, struct crypto_dump_info *info) { struct sk_buff *in_skb = info->in_skb; struct sk_buff *skb = info->out_skb; struct nlmsghdr *nlh; struct crypto_user_alg *ualg; int err = 0; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).portid, info->nlmsg_seq, CRYPTO_MSG_GETALG, sizeof(*ualg), info->nlmsg_flags); if (!nlh) { err = -EMSGSIZE; goto out; } ualg = nlmsg_data(nlh); err = crypto_report_one(alg, ualg, skb); if (err) { nlmsg_cancel(skb, nlh); goto out; } nlmsg_end(skb, nlh); out: return err; } static int crypto_report(struct sk_buff *in_skb, struct nlmsghdr *in_nlh, struct nlattr **attrs) { struct crypto_user_alg *p = nlmsg_data(in_nlh); struct crypto_alg *alg; struct sk_buff *skb; struct crypto_dump_info info; int err; if (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name)) return -EINVAL; alg = crypto_alg_match(p, 0); if (!alg) return -ENOENT; err = -ENOMEM; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) goto drop_alg; info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = in_nlh->nlmsg_seq; info.nlmsg_flags = 0; err = crypto_report_alg(alg, &info); drop_alg: crypto_mod_put(alg); if (err) return err; return nlmsg_unicast(crypto_nlsk, skb, NETLINK_CB(in_skb).portid); } static int crypto_dump_report(struct sk_buff *skb, struct netlink_callback *cb) { struct crypto_alg *alg; struct crypto_dump_info info; int err; if (cb->args[0]) goto out; cb->args[0] = 1; info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; list_for_each_entry(alg, &crypto_alg_list, cra_list) { err = crypto_report_alg(alg, &info); if (err) goto out_err; } out: return skb->len; out_err: return err; } static int crypto_dump_report_done(struct netlink_callback *cb) { return 0; } static int crypto_update_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); struct nlattr *priority = attrs[CRYPTOCFGA_PRIORITY_VAL]; LIST_HEAD(list); if (!netlink_capable(skb, CAP_NET_ADMIN)) return -EPERM; if (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name)) return -EINVAL; if (priority && !strlen(p->cru_driver_name)) return -EINVAL; alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; down_write(&crypto_alg_sem); crypto_remove_spawns(alg, &list, NULL); if (priority) alg->cra_priority = nla_get_u32(priority); up_write(&crypto_alg_sem); crypto_mod_put(alg); crypto_remove_final(&list); return 0; } static int crypto_del_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); int err; if (!netlink_capable(skb, CAP_NET_ADMIN)) return -EPERM; if (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name)) return -EINVAL; alg = crypto_alg_match(p, 1); if (!alg) return -ENOENT; /* We can not unregister core algorithms such as aes-generic. * We would loose the reference in the crypto_alg_list to this algorithm * if we try to unregister. Unregistering such an algorithm without * removing the module is not possible, so we restrict to crypto * instances that are build from templates. */ err = -EINVAL; if (!(alg->cra_flags & CRYPTO_ALG_INSTANCE)) goto drop_alg; err = -EBUSY; if (refcount_read(&alg->cra_refcnt) > 2) goto drop_alg; err = crypto_unregister_instance((struct crypto_instance *)alg); drop_alg: crypto_mod_put(alg); return err; } static int crypto_add_alg(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { int exact = 0; const char *name; struct crypto_alg *alg; struct crypto_user_alg *p = nlmsg_data(nlh); struct nlattr *priority = attrs[CRYPTOCFGA_PRIORITY_VAL]; if (!netlink_capable(skb, CAP_NET_ADMIN)) return -EPERM; if (!null_terminated(p->cru_name) || !null_terminated(p->cru_driver_name)) return -EINVAL; if (strlen(p->cru_driver_name)) exact = 1; if (priority && !exact) return -EINVAL; alg = crypto_alg_match(p, exact); if (alg) { crypto_mod_put(alg); return -EEXIST; } if (strlen(p->cru_driver_name)) name = p->cru_driver_name; else name = p->cru_name; alg = crypto_alg_mod_lookup(name, p->cru_type, p->cru_mask); if (IS_ERR(alg)) return PTR_ERR(alg); down_write(&crypto_alg_sem); if (priority) alg->cra_priority = nla_get_u32(priority); up_write(&crypto_alg_sem); crypto_mod_put(alg); return 0; } static int crypto_del_rng(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { if (!netlink_capable(skb, CAP_NET_ADMIN)) return -EPERM; return crypto_del_default_rng(); } #define MSGSIZE(type) sizeof(struct type) static const int crypto_msg_min[CRYPTO_NR_MSGTYPES] = { [CRYPTO_MSG_NEWALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_DELALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_UPDATEALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), [CRYPTO_MSG_DELRNG - CRYPTO_MSG_BASE] = 0, [CRYPTO_MSG_GETSTAT - CRYPTO_MSG_BASE] = MSGSIZE(crypto_user_alg), }; static const struct nla_policy crypto_policy[CRYPTOCFGA_MAX+1] = { [CRYPTOCFGA_PRIORITY_VAL] = { .type = NLA_U32}, }; #undef MSGSIZE static const struct crypto_link { int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **); int (*dump)(struct sk_buff *, struct netlink_callback *); int (*done)(struct netlink_callback *); } crypto_dispatch[CRYPTO_NR_MSGTYPES] = { [CRYPTO_MSG_NEWALG - CRYPTO_MSG_BASE] = { .doit = crypto_add_alg}, [CRYPTO_MSG_DELALG - CRYPTO_MSG_BASE] = { .doit = crypto_del_alg}, [CRYPTO_MSG_UPDATEALG - CRYPTO_MSG_BASE] = { .doit = crypto_update_alg}, [CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE] = { .doit = crypto_report, .dump = crypto_dump_report, .done = crypto_dump_report_done}, [CRYPTO_MSG_DELRNG - CRYPTO_MSG_BASE] = { .doit = crypto_del_rng }, [CRYPTO_MSG_GETSTAT - CRYPTO_MSG_BASE] = { .doit = crypto_reportstat, .dump = crypto_dump_reportstat, .done = crypto_dump_reportstat_done}, }; static int crypto_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct nlattr *attrs[CRYPTOCFGA_MAX+1]; const struct crypto_link *link; int type, err; type = nlh->nlmsg_type; if (type > CRYPTO_MSG_MAX) return -EINVAL; type -= CRYPTO_MSG_BASE; link = &crypto_dispatch[type]; if ((type == (CRYPTO_MSG_GETALG - CRYPTO_MSG_BASE) && (nlh->nlmsg_flags & NLM_F_DUMP))) { struct crypto_alg *alg; u16 dump_alloc = 0; if (link->dump == NULL) return -EINVAL; down_read(&crypto_alg_sem); list_for_each_entry(alg, &crypto_alg_list, cra_list) dump_alloc += CRYPTO_REPORT_MAXSIZE; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, .min_dump_alloc = dump_alloc, }; err = netlink_dump_start(crypto_nlsk, skb, nlh, &c); } up_read(&crypto_alg_sem); return err; } err = nlmsg_parse(nlh, crypto_msg_min[type], attrs, CRYPTOCFGA_MAX, crypto_policy, extack); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } static void crypto_netlink_rcv(struct sk_buff *skb) { mutex_lock(&crypto_cfg_mutex); netlink_rcv_skb(skb, &crypto_user_rcv_msg); mutex_unlock(&crypto_cfg_mutex); } static int __init crypto_user_init(void) { struct netlink_kernel_cfg cfg = { .input = crypto_netlink_rcv, }; crypto_nlsk = netlink_kernel_create(&init_net, NETLINK_CRYPTO, &cfg); if (!crypto_nlsk) return -ENOMEM; return 0; } static void __exit crypto_user_exit(void) { netlink_kernel_release(crypto_nlsk); } module_init(crypto_user_init); module_exit(crypto_user_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Steffen Klassert <steffen.klassert@secunet.com>"); MODULE_DESCRIPTION("Crypto userspace configuration API"); MODULE_ALIAS("net-pf-16-proto-21");
./CrossVul/dataset_final_sorted/CWE-200/c/bad_460_0
crossvul-cpp_data_good_5689_0
/* * L2TPv3 IP encapsulation support for IPv6 * * Copyright (c) 2012 Katalix Systems Ltd * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #include <linux/icmp.h> #include <linux/module.h> #include <linux/skbuff.h> #include <linux/random.h> #include <linux/socket.h> #include <linux/l2tp.h> #include <linux/in.h> #include <linux/in6.h> #include <net/sock.h> #include <net/ip.h> #include <net/icmp.h> #include <net/udp.h> #include <net/inet_common.h> #include <net/inet_hashtables.h> #include <net/tcp_states.h> #include <net/protocol.h> #include <net/xfrm.h> #include <net/transp_v6.h> #include <net/addrconf.h> #include <net/ip6_route.h> #include "l2tp_core.h" struct l2tp_ip6_sock { /* inet_sock has to be the first member of l2tp_ip6_sock */ struct inet_sock inet; u32 conn_id; u32 peer_conn_id; /* ipv6_pinfo has to be the last member of l2tp_ip6_sock, see inet6_sk_generic */ struct ipv6_pinfo inet6; }; static DEFINE_RWLOCK(l2tp_ip6_lock); static struct hlist_head l2tp_ip6_table; static struct hlist_head l2tp_ip6_bind_table; static inline struct l2tp_ip6_sock *l2tp_ip6_sk(const struct sock *sk) { return (struct l2tp_ip6_sock *)sk; } static struct sock *__l2tp_ip6_bind_lookup(struct net *net, struct in6_addr *laddr, int dif, u32 tunnel_id) { struct sock *sk; sk_for_each_bound(sk, &l2tp_ip6_bind_table) { struct in6_addr *addr = inet6_rcv_saddr(sk); struct l2tp_ip6_sock *l2tp = l2tp_ip6_sk(sk); if (l2tp == NULL) continue; if ((l2tp->conn_id == tunnel_id) && net_eq(sock_net(sk), net) && !(addr && ipv6_addr_equal(addr, laddr)) && !(sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)) goto found; } sk = NULL; found: return sk; } static inline struct sock *l2tp_ip6_bind_lookup(struct net *net, struct in6_addr *laddr, int dif, u32 tunnel_id) { struct sock *sk = __l2tp_ip6_bind_lookup(net, laddr, dif, tunnel_id); if (sk) sock_hold(sk); return sk; } /* When processing receive frames, there are two cases to * consider. Data frames consist of a non-zero session-id and an * optional cookie. Control frames consist of a regular L2TP header * preceded by 32-bits of zeros. * * L2TPv3 Session Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Session ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Cookie (optional, maximum 64 bits)... * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * L2TPv3 Control Message Header Over IP * * 0 1 2 3 * 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | (32 bits of zeros) | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * |T|L|x|x|S|x|x|x|x|x|x|x| Ver | Length | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Control Connection ID | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * | Ns | Nr | * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ * * All control frames are passed to userspace. */ static int l2tp_ip6_recv(struct sk_buff *skb) { struct sock *sk; u32 session_id; u32 tunnel_id; unsigned char *ptr, *optr; struct l2tp_session *session; struct l2tp_tunnel *tunnel = NULL; int length; /* Point to L2TP header */ optr = ptr = skb->data; if (!pskb_may_pull(skb, 4)) goto discard; session_id = ntohl(*((__be32 *) ptr)); ptr += 4; /* RFC3931: L2TP/IP packets have the first 4 bytes containing * the session_id. If it is 0, the packet is a L2TP control * frame and the session_id value can be discarded. */ if (session_id == 0) { __skb_pull(skb, 4); goto pass_up; } /* Ok, this is a data packet. Lookup the session. */ session = l2tp_session_find(&init_net, NULL, session_id); if (session == NULL) goto discard; tunnel = session->tunnel; if (tunnel == NULL) goto discard; /* Trace packet contents, if enabled */ if (tunnel->debug & L2TP_MSG_DATA) { length = min(32u, skb->len); if (!pskb_may_pull(skb, length)) goto discard; pr_debug("%s: ip recv\n", tunnel->name); print_hex_dump_bytes("", DUMP_PREFIX_OFFSET, ptr, length); } l2tp_recv_common(session, skb, ptr, optr, 0, skb->len, tunnel->recv_payload_hook); return 0; pass_up: /* Get the tunnel_id from the L2TP header */ if (!pskb_may_pull(skb, 12)) goto discard; if ((skb->data[0] & 0xc0) != 0xc0) goto discard; tunnel_id = ntohl(*(__be32 *) &skb->data[4]); tunnel = l2tp_tunnel_find(&init_net, tunnel_id); if (tunnel != NULL) sk = tunnel->sock; else { struct ipv6hdr *iph = ipv6_hdr(skb); read_lock_bh(&l2tp_ip6_lock); sk = __l2tp_ip6_bind_lookup(&init_net, &iph->daddr, 0, tunnel_id); read_unlock_bh(&l2tp_ip6_lock); } if (sk == NULL) goto discard; sock_hold(sk); if (!xfrm6_policy_check(sk, XFRM_POLICY_IN, skb)) goto discard_put; nf_reset(skb); return sk_receive_skb(sk, skb, 1); discard_put: sock_put(sk); discard: kfree_skb(skb); return 0; } static int l2tp_ip6_open(struct sock *sk) { /* Prevent autobind. We don't have ports. */ inet_sk(sk)->inet_num = IPPROTO_L2TP; write_lock_bh(&l2tp_ip6_lock); sk_add_node(sk, &l2tp_ip6_table); write_unlock_bh(&l2tp_ip6_lock); return 0; } static void l2tp_ip6_close(struct sock *sk, long timeout) { write_lock_bh(&l2tp_ip6_lock); hlist_del_init(&sk->sk_bind_node); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip6_lock); sk_common_release(sk); } static void l2tp_ip6_destroy_sock(struct sock *sk) { struct l2tp_tunnel *tunnel = l2tp_sock_to_tunnel(sk); lock_sock(sk); ip6_flush_pending_frames(sk); release_sock(sk); if (tunnel) { l2tp_tunnel_closeall(tunnel); sock_put(sk); } inet6_destroy_sock(sk); } static int l2tp_ip6_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *addr = (struct sockaddr_l2tpip6 *) uaddr; __be32 v4addr = 0; int addr_type; int err; if (!sock_flag(sk, SOCK_ZAPPED)) return -EINVAL; if (addr->l2tp_family != AF_INET6) return -EINVAL; if (addr_len < sizeof(*addr)) return -EINVAL; addr_type = ipv6_addr_type(&addr->l2tp_addr); /* l2tp_ip6 sockets are IPv6 only */ if (addr_type == IPV6_ADDR_MAPPED) return -EADDRNOTAVAIL; /* L2TP is point-point, not multicast */ if (addr_type & IPV6_ADDR_MULTICAST) return -EADDRNOTAVAIL; err = -EADDRINUSE; read_lock_bh(&l2tp_ip6_lock); if (__l2tp_ip6_bind_lookup(&init_net, &addr->l2tp_addr, sk->sk_bound_dev_if, addr->l2tp_conn_id)) goto out_in_use; read_unlock_bh(&l2tp_ip6_lock); lock_sock(sk); err = -EINVAL; if (sk->sk_state != TCP_CLOSE) goto out_unlock; /* Check if the address belongs to the host. */ rcu_read_lock(); if (addr_type != IPV6_ADDR_ANY) { struct net_device *dev = NULL; if (addr_type & IPV6_ADDR_LINKLOCAL) { if (addr_len >= sizeof(struct sockaddr_in6) && addr->l2tp_scope_id) { /* Override any existing binding, if another * one is supplied by user. */ sk->sk_bound_dev_if = addr->l2tp_scope_id; } /* Binding to link-local address requires an interface */ if (!sk->sk_bound_dev_if) goto out_unlock_rcu; err = -ENODEV; dev = dev_get_by_index_rcu(sock_net(sk), sk->sk_bound_dev_if); if (!dev) goto out_unlock_rcu; } /* ipv4 addr of the socket is invalid. Only the * unspecified and mapped address have a v4 equivalent. */ v4addr = LOOPBACK4_IPV6; err = -EADDRNOTAVAIL; if (!ipv6_chk_addr(sock_net(sk), &addr->l2tp_addr, dev, 0)) goto out_unlock_rcu; } rcu_read_unlock(); inet->inet_rcv_saddr = inet->inet_saddr = v4addr; np->rcv_saddr = addr->l2tp_addr; np->saddr = addr->l2tp_addr; l2tp_ip6_sk(sk)->conn_id = addr->l2tp_conn_id; write_lock_bh(&l2tp_ip6_lock); sk_add_bind_node(sk, &l2tp_ip6_bind_table); sk_del_node_init(sk); write_unlock_bh(&l2tp_ip6_lock); sock_reset_flag(sk, SOCK_ZAPPED); release_sock(sk); return 0; out_unlock_rcu: rcu_read_unlock(); out_unlock: release_sock(sk); return err; out_in_use: read_unlock_bh(&l2tp_ip6_lock); return err; } static int l2tp_ip6_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *) uaddr; struct sockaddr_in6 *usin = (struct sockaddr_in6 *) uaddr; struct in6_addr *daddr; int addr_type; int rc; if (sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */ return -EINVAL; if (addr_len < sizeof(*lsa)) return -EINVAL; addr_type = ipv6_addr_type(&usin->sin6_addr); if (addr_type & IPV6_ADDR_MULTICAST) return -EINVAL; if (addr_type & IPV6_ADDR_MAPPED) { daddr = &usin->sin6_addr; if (ipv4_is_multicast(daddr->s6_addr32[3])) return -EINVAL; } rc = ip6_datagram_connect(sk, uaddr, addr_len); lock_sock(sk); l2tp_ip6_sk(sk)->peer_conn_id = lsa->l2tp_conn_id; write_lock_bh(&l2tp_ip6_lock); hlist_del_init(&sk->sk_bind_node); sk_add_bind_node(sk, &l2tp_ip6_bind_table); write_unlock_bh(&l2tp_ip6_lock); release_sock(sk); return rc; } static int l2tp_ip6_disconnect(struct sock *sk, int flags) { if (sock_flag(sk, SOCK_ZAPPED)) return 0; return udp_disconnect(sk, flags); } static int l2tp_ip6_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)uaddr; struct sock *sk = sock->sk; struct ipv6_pinfo *np = inet6_sk(sk); struct l2tp_ip6_sock *lsk = l2tp_ip6_sk(sk); lsa->l2tp_family = AF_INET6; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_unused = 0; if (peer) { if (!lsk->peer_conn_id) return -ENOTCONN; lsa->l2tp_conn_id = lsk->peer_conn_id; lsa->l2tp_addr = np->daddr; if (np->sndflow) lsa->l2tp_flowinfo = np->flow_label; } else { if (ipv6_addr_any(&np->rcv_saddr)) lsa->l2tp_addr = np->saddr; else lsa->l2tp_addr = np->rcv_saddr; lsa->l2tp_conn_id = lsk->conn_id; } if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = sk->sk_bound_dev_if; *uaddr_len = sizeof(*lsa); return 0; } static int l2tp_ip6_backlog_recv(struct sock *sk, struct sk_buff *skb) { int rc; /* Charge it to the socket, dropping if the queue is full. */ rc = sock_queue_rcv_skb(sk, skb); if (rc < 0) goto drop; return 0; drop: IP_INC_STATS(&init_net, IPSTATS_MIB_INDISCARDS); kfree_skb(skb); return -1; } static int l2tp_ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb; __be32 *transhdr = NULL; int err = 0; skb = skb_peek(&sk->sk_write_queue); if (skb == NULL) goto out; transhdr = (__be32 *)skb_transport_header(skb); *transhdr = 0; err = ip6_push_pending_frames(sk); out: return err; } /* Userspace will call sendmsg() on the tunnel socket to send L2TP * control frames. */ static int l2tp_ip6_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len) { struct ipv6_txoptions opt_space; struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *) msg->msg_name; struct in6_addr *daddr, *final_p, final; struct ipv6_pinfo *np = inet6_sk(sk); struct ipv6_txoptions *opt = NULL; struct ip6_flowlabel *flowlabel = NULL; struct dst_entry *dst = NULL; struct flowi6 fl6; int addr_len = msg->msg_namelen; int hlimit = -1; int tclass = -1; int dontfrag = -1; int transhdrlen = 4; /* zero session-id */ int ulen = len + transhdrlen; int err; /* Rough check on arithmetic overflow, better check is made in ip6_append_data(). */ if (len > INT_MAX) return -EMSGSIZE; /* Mirror BSD error message compatibility */ if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* * Get and verify the address. */ memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_mark = sk->sk_mark; if (lsa) { if (addr_len < SIN6_LEN_RFC2133) return -EINVAL; if (lsa->l2tp_family && lsa->l2tp_family != AF_INET6) return -EAFNOSUPPORT; daddr = &lsa->l2tp_addr; if (np->sndflow) { fl6.flowlabel = lsa->l2tp_flowinfo & IPV6_FLOWINFO_MASK; if (fl6.flowlabel&IPV6_FLOWLABEL_MASK) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; daddr = &flowlabel->dst; } } /* * Otherwise it will be difficult to maintain * sk->sk_dst_cache. */ if (sk->sk_state == TCP_ESTABLISHED && ipv6_addr_equal(daddr, &np->daddr)) daddr = &np->daddr; if (addr_len >= sizeof(struct sockaddr_in6) && lsa->l2tp_scope_id && ipv6_addr_type(daddr) & IPV6_ADDR_LINKLOCAL) fl6.flowi6_oif = lsa->l2tp_scope_id; } else { if (sk->sk_state != TCP_ESTABLISHED) return -EDESTADDRREQ; daddr = &np->daddr; fl6.flowlabel = np->flow_label; } if (fl6.flowi6_oif == 0) fl6.flowi6_oif = sk->sk_bound_dev_if; if (msg->msg_controllen) { opt = &opt_space; memset(opt, 0, sizeof(struct ipv6_txoptions)); opt->tot_len = sizeof(struct ipv6_txoptions); err = ip6_datagram_send_ctl(sock_net(sk), sk, msg, &fl6, opt, &hlimit, &tclass, &dontfrag); if (err < 0) { fl6_sock_release(flowlabel); return err; } if ((fl6.flowlabel & IPV6_FLOWLABEL_MASK) && !flowlabel) { flowlabel = fl6_sock_lookup(sk, fl6.flowlabel); if (flowlabel == NULL) return -EINVAL; } if (!(opt->opt_nflen|opt->opt_flen)) opt = NULL; } if (opt == NULL) opt = np->opt; if (flowlabel) opt = fl6_merge_options(&opt_space, flowlabel, opt); opt = ipv6_fixup_options(&opt_space, opt); fl6.flowi6_proto = sk->sk_protocol; if (!ipv6_addr_any(daddr)) fl6.daddr = *daddr; else fl6.daddr.s6_addr[15] = 0x1; /* :: means loopback (BSD'ism) */ if (ipv6_addr_any(&fl6.saddr) && !ipv6_addr_any(&np->saddr)) fl6.saddr = np->saddr; final_p = fl6_update_dst(&fl6, opt, &final); if (!fl6.flowi6_oif && ipv6_addr_is_multicast(&fl6.daddr)) fl6.flowi6_oif = np->mcast_oif; else if (!fl6.flowi6_oif) fl6.flowi6_oif = np->ucast_oif; security_sk_classify_flow(sk, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p, true); if (IS_ERR(dst)) { err = PTR_ERR(dst); goto out; } if (hlimit < 0) { if (ipv6_addr_is_multicast(&fl6.daddr)) hlimit = np->mcast_hops; else hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); } if (tclass < 0) tclass = np->tclass; if (dontfrag < 0) dontfrag = np->dontfrag; if (msg->msg_flags & MSG_CONFIRM) goto do_confirm; back_from_confirm: lock_sock(sk); err = ip6_append_data(sk, ip_generic_getfrag, msg->msg_iov, ulen, transhdrlen, hlimit, tclass, opt, &fl6, (struct rt6_info *)dst, msg->msg_flags, dontfrag); if (err) ip6_flush_pending_frames(sk); else if (!(msg->msg_flags & MSG_MORE)) err = l2tp_ip6_push_pending_frames(sk); release_sock(sk); done: dst_release(dst); out: fl6_sock_release(flowlabel); return err < 0 ? err : len; do_confirm: dst_confirm(dst); if (!(msg->msg_flags & MSG_PROBE) || len) goto back_from_confirm; err = 0; goto done; } static int l2tp_ip6_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg, size_t len, int noblock, int flags, int *addr_len) { struct ipv6_pinfo *np = inet6_sk(sk); struct sockaddr_l2tpip6 *lsa = (struct sockaddr_l2tpip6 *)msg->msg_name; size_t copied = 0; int err = -EOPNOTSUPP; struct sk_buff *skb; if (flags & MSG_OOB) goto out; if (addr_len) *addr_len = sizeof(*lsa); if (flags & MSG_ERRQUEUE) return ipv6_recv_error(sk, msg, len); skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) goto out; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (err) goto done; sock_recv_timestamp(msg, sk, skb); /* Copy the address. */ if (lsa) { lsa->l2tp_family = AF_INET6; lsa->l2tp_unused = 0; lsa->l2tp_addr = ipv6_hdr(skb)->saddr; lsa->l2tp_flowinfo = 0; lsa->l2tp_scope_id = 0; lsa->l2tp_conn_id = 0; if (ipv6_addr_type(&lsa->l2tp_addr) & IPV6_ADDR_LINKLOCAL) lsa->l2tp_scope_id = IP6CB(skb)->iif; } if (np->rxopt.all) ip6_datagram_recv_ctl(sk, msg, skb); if (flags & MSG_TRUNC) copied = skb->len; done: skb_free_datagram(sk, skb); out: return err ? err : copied; } static struct proto l2tp_ip6_prot = { .name = "L2TP/IPv6", .owner = THIS_MODULE, .init = l2tp_ip6_open, .close = l2tp_ip6_close, .bind = l2tp_ip6_bind, .connect = l2tp_ip6_connect, .disconnect = l2tp_ip6_disconnect, .ioctl = udp_ioctl, .destroy = l2tp_ip6_destroy_sock, .setsockopt = ipv6_setsockopt, .getsockopt = ipv6_getsockopt, .sendmsg = l2tp_ip6_sendmsg, .recvmsg = l2tp_ip6_recvmsg, .backlog_rcv = l2tp_ip6_backlog_recv, .hash = inet_hash, .unhash = inet_unhash, .obj_size = sizeof(struct l2tp_ip6_sock), #ifdef CONFIG_COMPAT .compat_setsockopt = compat_ipv6_setsockopt, .compat_getsockopt = compat_ipv6_getsockopt, #endif }; static const struct proto_ops l2tp_ip6_ops = { .family = PF_INET6, .owner = THIS_MODULE, .release = inet6_release, .bind = inet6_bind, .connect = inet_dgram_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = l2tp_ip6_getname, .poll = datagram_poll, .ioctl = inet6_ioctl, .listen = sock_no_listen, .shutdown = inet_shutdown, .setsockopt = sock_common_setsockopt, .getsockopt = sock_common_getsockopt, .sendmsg = inet_sendmsg, .recvmsg = sock_common_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, #ifdef CONFIG_COMPAT .compat_setsockopt = compat_sock_common_setsockopt, .compat_getsockopt = compat_sock_common_getsockopt, #endif }; static struct inet_protosw l2tp_ip6_protosw = { .type = SOCK_DGRAM, .protocol = IPPROTO_L2TP, .prot = &l2tp_ip6_prot, .ops = &l2tp_ip6_ops, .no_check = 0, }; static struct inet6_protocol l2tp_ip6_protocol __read_mostly = { .handler = l2tp_ip6_recv, }; static int __init l2tp_ip6_init(void) { int err; pr_info("L2TP IP encapsulation support for IPv6 (L2TPv3)\n"); err = proto_register(&l2tp_ip6_prot, 1); if (err != 0) goto out; err = inet6_add_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP); if (err) goto out1; inet6_register_protosw(&l2tp_ip6_protosw); return 0; out1: proto_unregister(&l2tp_ip6_prot); out: return err; } static void __exit l2tp_ip6_exit(void) { inet6_unregister_protosw(&l2tp_ip6_protosw); inet6_del_protocol(&l2tp_ip6_protocol, IPPROTO_L2TP); proto_unregister(&l2tp_ip6_prot); } module_init(l2tp_ip6_init); module_exit(l2tp_ip6_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Chris Elston <celston@katalix.com>"); MODULE_DESCRIPTION("L2TP IP encapsulation for IPv6"); MODULE_VERSION("1.0"); /* Use the value of SOCK_DGRAM (2) directory, because __stringify doesn't like * enums */ MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_INET6, 2, IPPROTO_L2TP);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5689_0
crossvul-cpp_data_good_2958_3
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ #include "vim.h" #ifdef AMIGA # include <time.h> /* for time() */ #endif /* * Vim originated from Stevie version 3.6 (Fish disk 217) by GRWalter (Fred) * It has been changed beyond recognition since then. * * Differences between version 7.4 and 8.x can be found with ":help version8". * Differences between version 6.4 and 7.x can be found with ":help version7". * Differences between version 5.8 and 6.x can be found with ":help version6". * Differences between version 4.x and 5.x can be found with ":help version5". * Differences between version 3.0 and 4.x can be found with ":help version4". * All the remarks about older versions have been removed, they are not very * interesting. */ #include "version.h" char *Version = VIM_VERSION_SHORT; static char *mediumVersion = VIM_VERSION_MEDIUM; #if defined(HAVE_DATE_TIME) || defined(PROTO) # if (defined(VMS) && defined(VAXC)) || defined(PROTO) char longVersion[sizeof(VIM_VERSION_LONG_DATE) + sizeof(__DATE__) + sizeof(__TIME__) + 3]; void make_version(void) { /* * Construct the long version string. Necessary because * VAX C can't catenate strings in the preprocessor. */ strcpy(longVersion, VIM_VERSION_LONG_DATE); strcat(longVersion, __DATE__); strcat(longVersion, " "); strcat(longVersion, __TIME__); strcat(longVersion, ")"); } # else char *longVersion = VIM_VERSION_LONG_DATE __DATE__ " " __TIME__ ")"; # endif #else char *longVersion = VIM_VERSION_LONG; #endif static void list_features(void); static void version_msg(char *s); static char *(features[]) = { #ifdef HAVE_ACL "+acl", #else "-acl", #endif #ifdef AMIGA /* only for Amiga systems */ # ifdef FEAT_ARP "+ARP", # else "-ARP", # endif #endif #ifdef FEAT_ARABIC "+arabic", #else "-arabic", #endif #ifdef FEAT_AUTOCMD "+autocmd", #else "-autocmd", #endif #ifdef FEAT_BEVAL "+balloon_eval", #else "-balloon_eval", #endif #ifdef FEAT_BROWSE "+browse", #else "-browse", #endif #ifdef NO_BUILTIN_TCAPS "-builtin_terms", #endif #ifdef SOME_BUILTIN_TCAPS "+builtin_terms", #endif #ifdef ALL_BUILTIN_TCAPS "++builtin_terms", #endif #ifdef FEAT_BYTEOFF "+byte_offset", #else "-byte_offset", #endif #ifdef FEAT_JOB_CHANNEL "+channel", #else "-channel", #endif #ifdef FEAT_CINDENT "+cindent", #else "-cindent", #endif #ifdef FEAT_CLIENTSERVER "+clientserver", #else "-clientserver", #endif #ifdef FEAT_CLIPBOARD "+clipboard", #else "-clipboard", #endif #ifdef FEAT_CMDL_COMPL "+cmdline_compl", #else "-cmdline_compl", #endif #ifdef FEAT_CMDHIST "+cmdline_hist", #else "-cmdline_hist", #endif #ifdef FEAT_CMDL_INFO "+cmdline_info", #else "-cmdline_info", #endif #ifdef FEAT_COMMENTS "+comments", #else "-comments", #endif #ifdef FEAT_CONCEAL "+conceal", #else "-conceal", #endif #ifdef FEAT_CRYPT "+cryptv", #else "-cryptv", #endif #ifdef FEAT_CSCOPE "+cscope", #else "-cscope", #endif #ifdef FEAT_CURSORBIND "+cursorbind", #else "-cursorbind", #endif #ifdef CURSOR_SHAPE "+cursorshape", #else "-cursorshape", #endif #if defined(FEAT_CON_DIALOG) && defined(FEAT_GUI_DIALOG) "+dialog_con_gui", #else # if defined(FEAT_CON_DIALOG) "+dialog_con", # else # if defined(FEAT_GUI_DIALOG) "+dialog_gui", # else "-dialog", # endif # endif #endif #ifdef FEAT_DIFF "+diff", #else "-diff", #endif #ifdef FEAT_DIGRAPHS "+digraphs", #else "-digraphs", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_DIRECTX "+directx", # else "-directx", # endif #endif #ifdef FEAT_DND "+dnd", #else "-dnd", #endif #ifdef EBCDIC "+ebcdic", #else "-ebcdic", #endif #ifdef FEAT_EMACS_TAGS "+emacs_tags", #else "-emacs_tags", #endif #ifdef FEAT_EVAL "+eval", #else "-eval", #endif "+ex_extra", #ifdef FEAT_SEARCH_EXTRA "+extra_search", #else "-extra_search", #endif #ifdef FEAT_FKMAP "+farsi", #else "-farsi", #endif #ifdef FEAT_SEARCHPATH "+file_in_path", #else "-file_in_path", #endif #ifdef FEAT_FIND_ID "+find_in_path", #else "-find_in_path", #endif #ifdef FEAT_FLOAT "+float", #else "-float", #endif #ifdef FEAT_FOLDING "+folding", #else "-folding", #endif #ifdef FEAT_FOOTER "+footer", #else "-footer", #endif /* only interesting on Unix systems */ #if !defined(USE_SYSTEM) && defined(UNIX) "+fork()", #endif #ifdef FEAT_GETTEXT # ifdef DYNAMIC_GETTEXT "+gettext/dyn", # else "+gettext", # endif #else "-gettext", #endif #ifdef FEAT_HANGULIN "+hangul_input", #else "-hangul_input", #endif #if (defined(HAVE_ICONV_H) && defined(USE_ICONV)) || defined(DYNAMIC_ICONV) # ifdef DYNAMIC_ICONV "+iconv/dyn", # else "+iconv", # endif #else "-iconv", #endif #ifdef FEAT_INS_EXPAND "+insert_expand", #else "-insert_expand", #endif #ifdef FEAT_JOB_CHANNEL "+job", #else "-job", #endif #ifdef FEAT_JUMPLIST "+jumplist", #else "-jumplist", #endif #ifdef FEAT_KEYMAP "+keymap", #else "-keymap", #endif #ifdef FEAT_EVAL "+lambda", #else "-lambda", #endif #ifdef FEAT_LANGMAP "+langmap", #else "-langmap", #endif #ifdef FEAT_LIBCALL "+libcall", #else "-libcall", #endif #ifdef FEAT_LINEBREAK "+linebreak", #else "-linebreak", #endif #ifdef FEAT_LISP "+lispindent", #else "-lispindent", #endif #ifdef FEAT_LISTCMDS "+listcmds", #else "-listcmds", #endif #ifdef FEAT_LOCALMAP "+localmap", #else "-localmap", #endif #ifdef FEAT_LUA # ifdef DYNAMIC_LUA "+lua/dyn", # else "+lua", # endif #else "-lua", #endif #ifdef FEAT_MENU "+menu", #else "-menu", #endif #ifdef FEAT_SESSION "+mksession", #else "-mksession", #endif #ifdef FEAT_MODIFY_FNAME "+modify_fname", #else "-modify_fname", #endif #ifdef FEAT_MOUSE "+mouse", # ifdef FEAT_MOUSESHAPE "+mouseshape", # else "-mouseshape", # endif # else "-mouse", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_DEC "+mouse_dec", # else "-mouse_dec", # endif # ifdef FEAT_MOUSE_GPM "+mouse_gpm", # else "-mouse_gpm", # endif # ifdef FEAT_MOUSE_JSB "+mouse_jsbterm", # else "-mouse_jsbterm", # endif # ifdef FEAT_MOUSE_NET "+mouse_netterm", # else "-mouse_netterm", # endif #endif #ifdef __QNX__ # ifdef FEAT_MOUSE_PTERM "+mouse_pterm", # else "-mouse_pterm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_MOUSE_SGR "+mouse_sgr", # else "-mouse_sgr", # endif # ifdef FEAT_SYSMOUSE "+mouse_sysmouse", # else "-mouse_sysmouse", # endif # ifdef FEAT_MOUSE_URXVT "+mouse_urxvt", # else "-mouse_urxvt", # endif # ifdef FEAT_MOUSE_XTERM "+mouse_xterm", # else "-mouse_xterm", # endif #endif #ifdef FEAT_MBYTE_IME # ifdef DYNAMIC_IME "+multi_byte_ime/dyn", # else "+multi_byte_ime", # endif #else # ifdef FEAT_MBYTE "+multi_byte", # else "-multi_byte", # endif #endif #ifdef FEAT_MULTI_LANG "+multi_lang", #else "-multi_lang", #endif #ifdef FEAT_MZSCHEME # ifdef DYNAMIC_MZSCHEME "+mzscheme/dyn", # else "+mzscheme", # endif #else "-mzscheme", #endif #ifdef FEAT_NETBEANS_INTG "+netbeans_intg", #else "-netbeans_intg", #endif #ifdef FEAT_NUM64 "+num64", #else "-num64", #endif #ifdef FEAT_GUI_W32 # ifdef FEAT_OLE "+ole", # else "-ole", # endif #endif "+packages", #ifdef FEAT_PATH_EXTRA "+path_extra", #else "-path_extra", #endif #ifdef FEAT_PERL # ifdef DYNAMIC_PERL "+perl/dyn", # else "+perl", # endif #else "-perl", #endif #ifdef FEAT_PERSISTENT_UNDO "+persistent_undo", #else "-persistent_undo", #endif #ifdef FEAT_PRINTER # ifdef FEAT_POSTSCRIPT "+postscript", # else "-postscript", # endif "+printer", #else "-printer", #endif #ifdef FEAT_PROFILE "+profile", #else "-profile", #endif #ifdef FEAT_PYTHON # ifdef DYNAMIC_PYTHON "+python/dyn", # else "+python", # endif #else "-python", #endif #ifdef FEAT_PYTHON3 # ifdef DYNAMIC_PYTHON3 "+python3/dyn", # else "+python3", # endif #else "-python3", #endif #ifdef FEAT_QUICKFIX "+quickfix", #else "-quickfix", #endif #ifdef FEAT_RELTIME "+reltime", #else "-reltime", #endif #ifdef FEAT_RIGHTLEFT "+rightleft", #else "-rightleft", #endif #ifdef FEAT_RUBY # ifdef DYNAMIC_RUBY "+ruby/dyn", # else "+ruby", # endif #else "-ruby", #endif #ifdef FEAT_SCROLLBIND "+scrollbind", #else "-scrollbind", #endif #ifdef FEAT_SIGNS "+signs", #else "-signs", #endif #ifdef FEAT_SMARTINDENT "+smartindent", #else "-smartindent", #endif #ifdef STARTUPTIME "+startuptime", #else "-startuptime", #endif #ifdef FEAT_STL_OPT "+statusline", #else "-statusline", #endif #ifdef FEAT_SUN_WORKSHOP "+sun_workshop", #else "-sun_workshop", #endif #ifdef FEAT_SYN_HL "+syntax", #else "-syntax", #endif /* only interesting on Unix systems */ #if defined(USE_SYSTEM) && defined(UNIX) "+system()", #endif #ifdef FEAT_TAG_BINS "+tag_binary", #else "-tag_binary", #endif #ifdef FEAT_TAG_OLDSTATIC "+tag_old_static", #else "-tag_old_static", #endif #ifdef FEAT_TAG_ANYWHITE "+tag_any_white", #else "-tag_any_white", #endif #ifdef FEAT_TCL # ifdef DYNAMIC_TCL "+tcl/dyn", # else "+tcl", # endif #else "-tcl", #endif #ifdef FEAT_TERMGUICOLORS "+termguicolors", #else "-termguicolors", #endif #ifdef FEAT_TERMINAL "+terminal", #else "-terminal", #endif #if defined(UNIX) /* only Unix can have terminfo instead of termcap */ # ifdef TERMINFO "+terminfo", # else "-terminfo", # endif #else /* unix always includes termcap support */ # ifdef HAVE_TGETENT "+tgetent", # else "-tgetent", # endif #endif #ifdef FEAT_TERMRESPONSE "+termresponse", #else "-termresponse", #endif #ifdef FEAT_TEXTOBJ "+textobjects", #else "-textobjects", #endif #ifdef FEAT_TIMERS "+timers", #else "-timers", #endif #ifdef FEAT_TITLE "+title", #else "-title", #endif #ifdef FEAT_TOOLBAR "+toolbar", #else "-toolbar", #endif #ifdef FEAT_USR_CMDS "+user_commands", #else "-user_commands", #endif "+vertsplit", #ifdef FEAT_VIRTUALEDIT "+virtualedit", #else "-virtualedit", #endif "+visual", #ifdef FEAT_VISUALEXTRA "+visualextra", #else "-visualextra", #endif #ifdef FEAT_VIMINFO "+viminfo", #else "-viminfo", #endif #ifdef FEAT_VREPLACE "+vreplace", #else "-vreplace", #endif #ifdef FEAT_WILDIGN "+wildignore", #else "-wildignore", #endif #ifdef FEAT_WILDMENU "+wildmenu", #else "-wildmenu", #endif "+windows", #ifdef FEAT_WRITEBACKUP "+writebackup", #else "-writebackup", #endif #if defined(UNIX) || defined(VMS) # ifdef FEAT_X11 "+X11", # else "-X11", # endif #endif #ifdef FEAT_XFONTSET "+xfontset", #else "-xfontset", #endif #ifdef FEAT_XIM "+xim", #else "-xim", #endif #ifdef WIN3264 # ifdef FEAT_XPM_W32 "+xpm_w32", # else "-xpm_w32", # endif #else # ifdef HAVE_XPM "+xpm", # else "-xpm", # endif #endif #if defined(UNIX) || defined(VMS) # ifdef USE_XSMP_INTERACT "+xsmp_interact", # else # ifdef USE_XSMP "+xsmp", # else "-xsmp", # endif # endif # ifdef FEAT_XCLIPBOARD "+xterm_clipboard", # else "-xterm_clipboard", # endif #endif #ifdef FEAT_XTERM_SAVE "+xterm_save", #else "-xterm_save", #endif NULL }; static int included_patches[] = { /* Add new patch number below this line */ /**/ 1263, /**/ 1262, /**/ 1261, /**/ 1260, /**/ 1259, /**/ 1258, /**/ 1257, /**/ 1256, /**/ 1255, /**/ 1254, /**/ 1253, /**/ 1252, /**/ 1251, /**/ 1250, /**/ 1249, /**/ 1248, /**/ 1247, /**/ 1246, /**/ 1245, /**/ 1244, /**/ 1243, /**/ 1242, /**/ 1241, /**/ 1240, /**/ 1239, /**/ 1238, /**/ 1237, /**/ 1236, /**/ 1235, /**/ 1234, /**/ 1233, /**/ 1232, /**/ 1231, /**/ 1230, /**/ 1229, /**/ 1228, /**/ 1227, /**/ 1226, /**/ 1225, /**/ 1224, /**/ 1223, /**/ 1222, /**/ 1221, /**/ 1220, /**/ 1219, /**/ 1218, /**/ 1217, /**/ 1216, /**/ 1215, /**/ 1214, /**/ 1213, /**/ 1212, /**/ 1211, /**/ 1210, /**/ 1209, /**/ 1208, /**/ 1207, /**/ 1206, /**/ 1205, /**/ 1204, /**/ 1203, /**/ 1202, /**/ 1201, /**/ 1200, /**/ 1199, /**/ 1198, /**/ 1197, /**/ 1196, /**/ 1195, /**/ 1194, /**/ 1193, /**/ 1192, /**/ 1191, /**/ 1190, /**/ 1189, /**/ 1188, /**/ 1187, /**/ 1186, /**/ 1185, /**/ 1184, /**/ 1183, /**/ 1182, /**/ 1181, /**/ 1180, /**/ 1179, /**/ 1178, /**/ 1177, /**/ 1176, /**/ 1175, /**/ 1174, /**/ 1173, /**/ 1172, /**/ 1171, /**/ 1170, /**/ 1169, /**/ 1168, /**/ 1167, /**/ 1166, /**/ 1165, /**/ 1164, /**/ 1163, /**/ 1162, /**/ 1161, /**/ 1160, /**/ 1159, /**/ 1158, /**/ 1157, /**/ 1156, /**/ 1155, /**/ 1154, /**/ 1153, /**/ 1152, /**/ 1151, /**/ 1150, /**/ 1149, /**/ 1148, /**/ 1147, /**/ 1146, /**/ 1145, /**/ 1144, /**/ 1143, /**/ 1142, /**/ 1141, /**/ 1140, /**/ 1139, /**/ 1138, /**/ 1137, /**/ 1136, /**/ 1135, /**/ 1134, /**/ 1133, /**/ 1132, /**/ 1131, /**/ 1130, /**/ 1129, /**/ 1128, /**/ 1127, /**/ 1126, /**/ 1125, /**/ 1124, /**/ 1123, /**/ 1122, /**/ 1121, /**/ 1120, /**/ 1119, /**/ 1118, /**/ 1117, /**/ 1116, /**/ 1115, /**/ 1114, /**/ 1113, /**/ 1112, /**/ 1111, /**/ 1110, /**/ 1109, /**/ 1108, /**/ 1107, /**/ 1106, /**/ 1105, /**/ 1104, /**/ 1103, /**/ 1102, /**/ 1101, /**/ 1100, /**/ 1099, /**/ 1098, /**/ 1097, /**/ 1096, /**/ 1095, /**/ 1094, /**/ 1093, /**/ 1092, /**/ 1091, /**/ 1090, /**/ 1089, /**/ 1088, /**/ 1087, /**/ 1086, /**/ 1085, /**/ 1084, /**/ 1083, /**/ 1082, /**/ 1081, /**/ 1080, /**/ 1079, /**/ 1078, /**/ 1077, /**/ 1076, /**/ 1075, /**/ 1074, /**/ 1073, /**/ 1072, /**/ 1071, /**/ 1070, /**/ 1069, /**/ 1068, /**/ 1067, /**/ 1066, /**/ 1065, /**/ 1064, /**/ 1063, /**/ 1062, /**/ 1061, /**/ 1060, /**/ 1059, /**/ 1058, /**/ 1057, /**/ 1056, /**/ 1055, /**/ 1054, /**/ 1053, /**/ 1052, /**/ 1051, /**/ 1050, /**/ 1049, /**/ 1048, /**/ 1047, /**/ 1046, /**/ 1045, /**/ 1044, /**/ 1043, /**/ 1042, /**/ 1041, /**/ 1040, /**/ 1039, /**/ 1038, /**/ 1037, /**/ 1036, /**/ 1035, /**/ 1034, /**/ 1033, /**/ 1032, /**/ 1031, /**/ 1030, /**/ 1029, /**/ 1028, /**/ 1027, /**/ 1026, /**/ 1025, /**/ 1024, /**/ 1023, /**/ 1022, /**/ 1021, /**/ 1020, /**/ 1019, /**/ 1018, /**/ 1017, /**/ 1016, /**/ 1015, /**/ 1014, /**/ 1013, /**/ 1012, /**/ 1011, /**/ 1010, /**/ 1009, /**/ 1008, /**/ 1007, /**/ 1006, /**/ 1005, /**/ 1004, /**/ 1003, /**/ 1002, /**/ 1001, /**/ 1000, /**/ 999, /**/ 998, /**/ 997, /**/ 996, /**/ 995, /**/ 994, /**/ 993, /**/ 992, /**/ 991, /**/ 990, /**/ 989, /**/ 988, /**/ 987, /**/ 986, /**/ 985, /**/ 984, /**/ 983, /**/ 982, /**/ 981, /**/ 980, /**/ 979, /**/ 978, /**/ 977, /**/ 976, /**/ 975, /**/ 974, /**/ 973, /**/ 972, /**/ 971, /**/ 970, /**/ 969, /**/ 968, /**/ 967, /**/ 966, /**/ 965, /**/ 964, /**/ 963, /**/ 962, /**/ 961, /**/ 960, /**/ 959, /**/ 958, /**/ 957, /**/ 956, /**/ 955, /**/ 954, /**/ 953, /**/ 952, /**/ 951, /**/ 950, /**/ 949, /**/ 948, /**/ 947, /**/ 946, /**/ 945, /**/ 944, /**/ 943, /**/ 942, /**/ 941, /**/ 940, /**/ 939, /**/ 938, /**/ 937, /**/ 936, /**/ 935, /**/ 934, /**/ 933, /**/ 932, /**/ 931, /**/ 930, /**/ 929, /**/ 928, /**/ 927, /**/ 926, /**/ 925, /**/ 924, /**/ 923, /**/ 922, /**/ 921, /**/ 920, /**/ 919, /**/ 918, /**/ 917, /**/ 916, /**/ 915, /**/ 914, /**/ 913, /**/ 912, /**/ 911, /**/ 910, /**/ 909, /**/ 908, /**/ 907, /**/ 906, /**/ 905, /**/ 904, /**/ 903, /**/ 902, /**/ 901, /**/ 900, /**/ 899, /**/ 898, /**/ 897, /**/ 896, /**/ 895, /**/ 894, /**/ 893, /**/ 892, /**/ 891, /**/ 890, /**/ 889, /**/ 888, /**/ 887, /**/ 886, /**/ 885, /**/ 884, /**/ 883, /**/ 882, /**/ 881, /**/ 880, /**/ 879, /**/ 878, /**/ 877, /**/ 876, /**/ 875, /**/ 874, /**/ 873, /**/ 872, /**/ 871, /**/ 870, /**/ 869, /**/ 868, /**/ 867, /**/ 866, /**/ 865, /**/ 864, /**/ 863, /**/ 862, /**/ 861, /**/ 860, /**/ 859, /**/ 858, /**/ 857, /**/ 856, /**/ 855, /**/ 854, /**/ 853, /**/ 852, /**/ 851, /**/ 850, /**/ 849, /**/ 848, /**/ 847, /**/ 846, /**/ 845, /**/ 844, /**/ 843, /**/ 842, /**/ 841, /**/ 840, /**/ 839, /**/ 838, /**/ 837, /**/ 836, /**/ 835, /**/ 834, /**/ 833, /**/ 832, /**/ 831, /**/ 830, /**/ 829, /**/ 828, /**/ 827, /**/ 826, /**/ 825, /**/ 824, /**/ 823, /**/ 822, /**/ 821, /**/ 820, /**/ 819, /**/ 818, /**/ 817, /**/ 816, /**/ 815, /**/ 814, /**/ 813, /**/ 812, /**/ 811, /**/ 810, /**/ 809, /**/ 808, /**/ 807, /**/ 806, /**/ 805, /**/ 804, /**/ 803, /**/ 802, /**/ 801, /**/ 800, /**/ 799, /**/ 798, /**/ 797, /**/ 796, /**/ 795, /**/ 794, /**/ 793, /**/ 792, /**/ 791, /**/ 790, /**/ 789, /**/ 788, /**/ 787, /**/ 786, /**/ 785, /**/ 784, /**/ 783, /**/ 782, /**/ 781, /**/ 780, /**/ 779, /**/ 778, /**/ 777, /**/ 776, /**/ 775, /**/ 774, /**/ 773, /**/ 772, /**/ 771, /**/ 770, /**/ 769, /**/ 768, /**/ 767, /**/ 766, /**/ 765, /**/ 764, /**/ 763, /**/ 762, /**/ 761, /**/ 760, /**/ 759, /**/ 758, /**/ 757, /**/ 756, /**/ 755, /**/ 754, /**/ 753, /**/ 752, /**/ 751, /**/ 750, /**/ 749, /**/ 748, /**/ 747, /**/ 746, /**/ 745, /**/ 744, /**/ 743, /**/ 742, /**/ 741, /**/ 740, /**/ 739, /**/ 738, /**/ 737, /**/ 736, /**/ 735, /**/ 734, /**/ 733, /**/ 732, /**/ 731, /**/ 730, /**/ 729, /**/ 728, /**/ 727, /**/ 726, /**/ 725, /**/ 724, /**/ 723, /**/ 722, /**/ 721, /**/ 720, /**/ 719, /**/ 718, /**/ 717, /**/ 716, /**/ 715, /**/ 714, /**/ 713, /**/ 712, /**/ 711, /**/ 710, /**/ 709, /**/ 708, /**/ 707, /**/ 706, /**/ 705, /**/ 704, /**/ 703, /**/ 702, /**/ 701, /**/ 700, /**/ 699, /**/ 698, /**/ 697, /**/ 696, /**/ 695, /**/ 694, /**/ 693, /**/ 692, /**/ 691, /**/ 690, /**/ 689, /**/ 688, /**/ 687, /**/ 686, /**/ 685, /**/ 684, /**/ 683, /**/ 682, /**/ 681, /**/ 680, /**/ 679, /**/ 678, /**/ 677, /**/ 676, /**/ 675, /**/ 674, /**/ 673, /**/ 672, /**/ 671, /**/ 670, /**/ 669, /**/ 668, /**/ 667, /**/ 666, /**/ 665, /**/ 664, /**/ 663, /**/ 662, /**/ 661, /**/ 660, /**/ 659, /**/ 658, /**/ 657, /**/ 656, /**/ 655, /**/ 654, /**/ 653, /**/ 652, /**/ 651, /**/ 650, /**/ 649, /**/ 648, /**/ 647, /**/ 646, /**/ 645, /**/ 644, /**/ 643, /**/ 642, /**/ 641, /**/ 640, /**/ 639, /**/ 638, /**/ 637, /**/ 636, /**/ 635, /**/ 634, /**/ 633, /**/ 632, /**/ 631, /**/ 630, /**/ 629, /**/ 628, /**/ 627, /**/ 626, /**/ 625, /**/ 624, /**/ 623, /**/ 622, /**/ 621, /**/ 620, /**/ 619, /**/ 618, /**/ 617, /**/ 616, /**/ 615, /**/ 614, /**/ 613, /**/ 612, /**/ 611, /**/ 610, /**/ 609, /**/ 608, /**/ 607, /**/ 606, /**/ 605, /**/ 604, /**/ 603, /**/ 602, /**/ 601, /**/ 600, /**/ 599, /**/ 598, /**/ 597, /**/ 596, /**/ 595, /**/ 594, /**/ 593, /**/ 592, /**/ 591, /**/ 590, /**/ 589, /**/ 588, /**/ 587, /**/ 586, /**/ 585, /**/ 584, /**/ 583, /**/ 582, /**/ 581, /**/ 580, /**/ 579, /**/ 578, /**/ 577, /**/ 576, /**/ 575, /**/ 574, /**/ 573, /**/ 572, /**/ 571, /**/ 570, /**/ 569, /**/ 568, /**/ 567, /**/ 566, /**/ 565, /**/ 564, /**/ 563, /**/ 562, /**/ 561, /**/ 560, /**/ 559, /**/ 558, /**/ 557, /**/ 556, /**/ 555, /**/ 554, /**/ 553, /**/ 552, /**/ 551, /**/ 550, /**/ 549, /**/ 548, /**/ 547, /**/ 546, /**/ 545, /**/ 544, /**/ 543, /**/ 542, /**/ 541, /**/ 540, /**/ 539, /**/ 538, /**/ 537, /**/ 536, /**/ 535, /**/ 534, /**/ 533, /**/ 532, /**/ 531, /**/ 530, /**/ 529, /**/ 528, /**/ 527, /**/ 526, /**/ 525, /**/ 524, /**/ 523, /**/ 522, /**/ 521, /**/ 520, /**/ 519, /**/ 518, /**/ 517, /**/ 516, /**/ 515, /**/ 514, /**/ 513, /**/ 512, /**/ 511, /**/ 510, /**/ 509, /**/ 508, /**/ 507, /**/ 506, /**/ 505, /**/ 504, /**/ 503, /**/ 502, /**/ 501, /**/ 500, /**/ 499, /**/ 498, /**/ 497, /**/ 496, /**/ 495, /**/ 494, /**/ 493, /**/ 492, /**/ 491, /**/ 490, /**/ 489, /**/ 488, /**/ 487, /**/ 486, /**/ 485, /**/ 484, /**/ 483, /**/ 482, /**/ 481, /**/ 480, /**/ 479, /**/ 478, /**/ 477, /**/ 476, /**/ 475, /**/ 474, /**/ 473, /**/ 472, /**/ 471, /**/ 470, /**/ 469, /**/ 468, /**/ 467, /**/ 466, /**/ 465, /**/ 464, /**/ 463, /**/ 462, /**/ 461, /**/ 460, /**/ 459, /**/ 458, /**/ 457, /**/ 456, /**/ 455, /**/ 454, /**/ 453, /**/ 452, /**/ 451, /**/ 450, /**/ 449, /**/ 448, /**/ 447, /**/ 446, /**/ 445, /**/ 444, /**/ 443, /**/ 442, /**/ 441, /**/ 440, /**/ 439, /**/ 438, /**/ 437, /**/ 436, /**/ 435, /**/ 434, /**/ 433, /**/ 432, /**/ 431, /**/ 430, /**/ 429, /**/ 428, /**/ 427, /**/ 426, /**/ 425, /**/ 424, /**/ 423, /**/ 422, /**/ 421, /**/ 420, /**/ 419, /**/ 418, /**/ 417, /**/ 416, /**/ 415, /**/ 414, /**/ 413, /**/ 412, /**/ 411, /**/ 410, /**/ 409, /**/ 408, /**/ 407, /**/ 406, /**/ 405, /**/ 404, /**/ 403, /**/ 402, /**/ 401, /**/ 400, /**/ 399, /**/ 398, /**/ 397, /**/ 396, /**/ 395, /**/ 394, /**/ 393, /**/ 392, /**/ 391, /**/ 390, /**/ 389, /**/ 388, /**/ 387, /**/ 386, /**/ 385, /**/ 384, /**/ 383, /**/ 382, /**/ 381, /**/ 380, /**/ 379, /**/ 378, /**/ 377, /**/ 376, /**/ 375, /**/ 374, /**/ 373, /**/ 372, /**/ 371, /**/ 370, /**/ 369, /**/ 368, /**/ 367, /**/ 366, /**/ 365, /**/ 364, /**/ 363, /**/ 362, /**/ 361, /**/ 360, /**/ 359, /**/ 358, /**/ 357, /**/ 356, /**/ 355, /**/ 354, /**/ 353, /**/ 352, /**/ 351, /**/ 350, /**/ 349, /**/ 348, /**/ 347, /**/ 346, /**/ 345, /**/ 344, /**/ 343, /**/ 342, /**/ 341, /**/ 340, /**/ 339, /**/ 338, /**/ 337, /**/ 336, /**/ 335, /**/ 334, /**/ 333, /**/ 332, /**/ 331, /**/ 330, /**/ 329, /**/ 328, /**/ 327, /**/ 326, /**/ 325, /**/ 324, /**/ 323, /**/ 322, /**/ 321, /**/ 320, /**/ 319, /**/ 318, /**/ 317, /**/ 316, /**/ 315, /**/ 314, /**/ 313, /**/ 312, /**/ 311, /**/ 310, /**/ 309, /**/ 308, /**/ 307, /**/ 306, /**/ 305, /**/ 304, /**/ 303, /**/ 302, /**/ 301, /**/ 300, /**/ 299, /**/ 298, /**/ 297, /**/ 296, /**/ 295, /**/ 294, /**/ 293, /**/ 292, /**/ 291, /**/ 290, /**/ 289, /**/ 288, /**/ 287, /**/ 286, /**/ 285, /**/ 284, /**/ 283, /**/ 282, /**/ 281, /**/ 280, /**/ 279, /**/ 278, /**/ 277, /**/ 276, /**/ 275, /**/ 274, /**/ 273, /**/ 272, /**/ 271, /**/ 270, /**/ 269, /**/ 268, /**/ 267, /**/ 266, /**/ 265, /**/ 264, /**/ 263, /**/ 262, /**/ 261, /**/ 260, /**/ 259, /**/ 258, /**/ 257, /**/ 256, /**/ 255, /**/ 254, /**/ 253, /**/ 252, /**/ 251, /**/ 250, /**/ 249, /**/ 248, /**/ 247, /**/ 246, /**/ 245, /**/ 244, /**/ 243, /**/ 242, /**/ 241, /**/ 240, /**/ 239, /**/ 238, /**/ 237, /**/ 236, /**/ 235, /**/ 234, /**/ 233, /**/ 232, /**/ 231, /**/ 230, /**/ 229, /**/ 228, /**/ 227, /**/ 226, /**/ 225, /**/ 224, /**/ 223, /**/ 222, /**/ 221, /**/ 220, /**/ 219, /**/ 218, /**/ 217, /**/ 216, /**/ 215, /**/ 214, /**/ 213, /**/ 212, /**/ 211, /**/ 210, /**/ 209, /**/ 208, /**/ 207, /**/ 206, /**/ 205, /**/ 204, /**/ 203, /**/ 202, /**/ 201, /**/ 200, /**/ 199, /**/ 198, /**/ 197, /**/ 196, /**/ 195, /**/ 194, /**/ 193, /**/ 192, /**/ 191, /**/ 190, /**/ 189, /**/ 188, /**/ 187, /**/ 186, /**/ 185, /**/ 184, /**/ 183, /**/ 182, /**/ 181, /**/ 180, /**/ 179, /**/ 178, /**/ 177, /**/ 176, /**/ 175, /**/ 174, /**/ 173, /**/ 172, /**/ 171, /**/ 170, /**/ 169, /**/ 168, /**/ 167, /**/ 166, /**/ 165, /**/ 164, /**/ 163, /**/ 162, /**/ 161, /**/ 160, /**/ 159, /**/ 158, /**/ 157, /**/ 156, /**/ 155, /**/ 154, /**/ 153, /**/ 152, /**/ 151, /**/ 150, /**/ 149, /**/ 148, /**/ 147, /**/ 146, /**/ 145, /**/ 144, /**/ 143, /**/ 142, /**/ 141, /**/ 140, /**/ 139, /**/ 138, /**/ 137, /**/ 136, /**/ 135, /**/ 134, /**/ 133, /**/ 132, /**/ 131, /**/ 130, /**/ 129, /**/ 128, /**/ 127, /**/ 126, /**/ 125, /**/ 124, /**/ 123, /**/ 122, /**/ 121, /**/ 120, /**/ 119, /**/ 118, /**/ 117, /**/ 116, /**/ 115, /**/ 114, /**/ 113, /**/ 112, /**/ 111, /**/ 110, /**/ 109, /**/ 108, /**/ 107, /**/ 106, /**/ 105, /**/ 104, /**/ 103, /**/ 102, /**/ 101, /**/ 100, /**/ 99, /**/ 98, /**/ 97, /**/ 96, /**/ 95, /**/ 94, /**/ 93, /**/ 92, /**/ 91, /**/ 90, /**/ 89, /**/ 88, /**/ 87, /**/ 86, /**/ 85, /**/ 84, /**/ 83, /**/ 82, /**/ 81, /**/ 80, /**/ 79, /**/ 78, /**/ 77, /**/ 76, /**/ 75, /**/ 74, /**/ 73, /**/ 72, /**/ 71, /**/ 70, /**/ 69, /**/ 68, /**/ 67, /**/ 66, /**/ 65, /**/ 64, /**/ 63, /**/ 62, /**/ 61, /**/ 60, /**/ 59, /**/ 58, /**/ 57, /**/ 56, /**/ 55, /**/ 54, /**/ 53, /**/ 52, /**/ 51, /**/ 50, /**/ 49, /**/ 48, /**/ 47, /**/ 46, /**/ 45, /**/ 44, /**/ 43, /**/ 42, /**/ 41, /**/ 40, /**/ 39, /**/ 38, /**/ 37, /**/ 36, /**/ 35, /**/ 34, /**/ 33, /**/ 32, /**/ 31, /**/ 30, /**/ 29, /**/ 28, /**/ 27, /**/ 26, /**/ 25, /**/ 24, /**/ 23, /**/ 22, /**/ 21, /**/ 20, /**/ 19, /**/ 18, /**/ 17, /**/ 16, /**/ 15, /**/ 14, /**/ 13, /**/ 12, /**/ 11, /**/ 10, /**/ 9, /**/ 8, /**/ 7, /**/ 6, /**/ 5, /**/ 4, /**/ 3, /**/ 2, /**/ 1, /**/ 0 }; /* * Place to put a short description when adding a feature with a patch. * Keep it short, e.g.,: "relative numbers", "persistent undo". * Also add a comment marker to separate the lines. * See the official Vim patches for the diff format: It must use a context of * one line only. Create it by hand or use "diff -C2" and edit the patch. */ static char *(extra_patches[]) = { /* Add your patch description below this line */ /**/ NULL }; int highest_patch(void) { int i; int h = 0; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] > h) h = included_patches[i]; return h; } #if defined(FEAT_EVAL) || defined(PROTO) /* * Return TRUE if patch "n" has been included. */ int has_patch(int n) { int i; for (i = 0; included_patches[i] != 0; ++i) if (included_patches[i] == n) return TRUE; return FALSE; } #endif void ex_version(exarg_T *eap) { /* * Ignore a ":version 9.99" command. */ if (*eap->arg == NUL) { msg_putchar('\n'); list_version(); } } /* * List all features aligned in columns, dictionary style. */ static void list_features(void) { int i; int ncol; int nrow; int nfeat = 0; int width = 0; /* Find the length of the longest feature name, use that + 1 as the column * width */ for (i = 0; features[i] != NULL; ++i) { int l = (int)STRLEN(features[i]); if (l > width) width = l; ++nfeat; } width += 1; if (Columns < width) { /* Not enough screen columns - show one per line */ for (i = 0; features[i] != NULL; ++i) { version_msg(features[i]); if (msg_col > 0) msg_putchar('\n'); } return; } /* The rightmost column doesn't need a separator. * Sacrifice it to fit in one more column if possible. */ ncol = (int) (Columns + 1) / width; nrow = nfeat / ncol + (nfeat % ncol ? 1 : 0); /* i counts columns then rows. idx counts rows then columns. */ for (i = 0; !got_int && i < nrow * ncol; ++i) { int idx = (i / ncol) + (i % ncol) * nrow; if (idx < nfeat) { int last_col = (i + 1) % ncol == 0; msg_puts((char_u *)features[idx]); if (last_col) { if (msg_col > 0) msg_putchar('\n'); } else { while (msg_col % width) msg_putchar(' '); } } else { if (msg_col > 0) msg_putchar('\n'); } } } void list_version(void) { int i; int first; char *s = ""; /* * When adding features here, don't forget to update the list of * internal variables in eval.c! */ MSG(longVersion); #ifdef WIN3264 # ifdef FEAT_GUI_W32 # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit GUI version")); # else MSG_PUTS(_("\nMS-Windows 32-bit GUI version")); # endif # ifdef FEAT_OLE MSG_PUTS(_(" with OLE support")); # endif # else # ifdef _WIN64 MSG_PUTS(_("\nMS-Windows 64-bit console version")); # else MSG_PUTS(_("\nMS-Windows 32-bit console version")); # endif # endif #endif #if defined(MACOS_X) # if defined(MACOS_X_DARWIN) MSG_PUTS(_("\nmacOS version")); # else MSG_PUTS(_("\nmacOS version w/o darwin feat.")); # endif #endif #ifdef VMS MSG_PUTS(_("\nOpenVMS version")); # ifdef HAVE_PATHDEF if (*compiled_arch != NUL) { MSG_PUTS(" - "); MSG_PUTS(compiled_arch); } # endif #endif /* Print the list of patch numbers if there is at least one. */ /* Print a range when patches are consecutive: "1-10, 12, 15-40, 42-45" */ if (included_patches[0] != 0) { MSG_PUTS(_("\nIncluded patches: ")); first = -1; /* find last one */ for (i = 0; included_patches[i] != 0; ++i) ; while (--i >= 0) { if (first < 0) first = included_patches[i]; if (i == 0 || included_patches[i - 1] != included_patches[i] + 1) { MSG_PUTS(s); s = ", "; msg_outnum((long)first); if (first != included_patches[i]) { MSG_PUTS("-"); msg_outnum((long)included_patches[i]); } first = -1; } } } /* Print the list of extra patch descriptions if there is at least one. */ if (extra_patches[0] != NULL) { MSG_PUTS(_("\nExtra patches: ")); s = ""; for (i = 0; extra_patches[i] != NULL; ++i) { MSG_PUTS(s); s = ", "; MSG_PUTS(extra_patches[i]); } } #ifdef MODIFIED_BY MSG_PUTS("\n"); MSG_PUTS(_("Modified by ")); MSG_PUTS(MODIFIED_BY); #endif #ifdef HAVE_PATHDEF if (*compiled_user != NUL || *compiled_sys != NUL) { MSG_PUTS(_("\nCompiled ")); if (*compiled_user != NUL) { MSG_PUTS(_("by ")); MSG_PUTS(compiled_user); } if (*compiled_sys != NUL) { MSG_PUTS("@"); MSG_PUTS(compiled_sys); } } #endif #ifdef FEAT_HUGE MSG_PUTS(_("\nHuge version ")); #else # ifdef FEAT_BIG MSG_PUTS(_("\nBig version ")); # else # ifdef FEAT_NORMAL MSG_PUTS(_("\nNormal version ")); # else # ifdef FEAT_SMALL MSG_PUTS(_("\nSmall version ")); # else MSG_PUTS(_("\nTiny version ")); # endif # endif # endif #endif #ifndef FEAT_GUI MSG_PUTS(_("without GUI.")); #else # ifdef FEAT_GUI_GTK # ifdef USE_GTK3 MSG_PUTS(_("with GTK3 GUI.")); # else # ifdef FEAT_GUI_GNOME MSG_PUTS(_("with GTK2-GNOME GUI.")); # else MSG_PUTS(_("with GTK2 GUI.")); # endif # endif # else # ifdef FEAT_GUI_MOTIF MSG_PUTS(_("with X11-Motif GUI.")); # else # ifdef FEAT_GUI_ATHENA # ifdef FEAT_GUI_NEXTAW MSG_PUTS(_("with X11-neXtaw GUI.")); # else MSG_PUTS(_("with X11-Athena GUI.")); # endif # else # ifdef FEAT_GUI_PHOTON MSG_PUTS(_("with Photon GUI.")); # else # if defined(MSWIN) MSG_PUTS(_("with GUI.")); # else # if defined(TARGET_API_MAC_CARBON) && TARGET_API_MAC_CARBON MSG_PUTS(_("with Carbon GUI.")); # else # if defined(TARGET_API_MAC_OSX) && TARGET_API_MAC_OSX MSG_PUTS(_("with Cocoa GUI.")); # else # endif # endif # endif # endif # endif # endif # endif #endif version_msg(_(" Features included (+) or not (-):\n")); list_features(); #ifdef SYS_VIMRC_FILE version_msg(_(" system vimrc file: \"")); version_msg(SYS_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE version_msg(_(" user vimrc file: \"")); version_msg(USR_VIMRC_FILE); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE2 version_msg(_(" 2nd user vimrc file: \"")); version_msg(USR_VIMRC_FILE2); version_msg("\"\n"); #endif #ifdef USR_VIMRC_FILE3 version_msg(_(" 3rd user vimrc file: \"")); version_msg(USR_VIMRC_FILE3); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE version_msg(_(" user exrc file: \"")); version_msg(USR_EXRC_FILE); version_msg("\"\n"); #endif #ifdef USR_EXRC_FILE2 version_msg(_(" 2nd user exrc file: \"")); version_msg(USR_EXRC_FILE2); version_msg("\"\n"); #endif #ifdef FEAT_GUI # ifdef SYS_GVIMRC_FILE version_msg(_(" system gvimrc file: \"")); version_msg(SYS_GVIMRC_FILE); version_msg("\"\n"); # endif version_msg(_(" user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE); version_msg("\"\n"); # ifdef USR_GVIMRC_FILE2 version_msg(_("2nd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE2); version_msg("\"\n"); # endif # ifdef USR_GVIMRC_FILE3 version_msg(_("3rd user gvimrc file: \"")); version_msg(USR_GVIMRC_FILE3); version_msg("\"\n"); # endif #endif version_msg(_(" defaults file: \"")); version_msg(VIM_DEFAULTS_FILE); version_msg("\"\n"); #ifdef FEAT_GUI # ifdef SYS_MENU_FILE version_msg(_(" system menu file: \"")); version_msg(SYS_MENU_FILE); version_msg("\"\n"); # endif #endif #ifdef HAVE_PATHDEF if (*default_vim_dir != NUL) { version_msg(_(" fall-back for $VIM: \"")); version_msg((char *)default_vim_dir); version_msg("\"\n"); } if (*default_vimruntime_dir != NUL) { version_msg(_(" f-b for $VIMRUNTIME: \"")); version_msg((char *)default_vimruntime_dir); version_msg("\"\n"); } version_msg(_("Compilation: ")); version_msg((char *)all_cflags); version_msg("\n"); #ifdef VMS if (*compiler_version != NUL) { version_msg(_("Compiler: ")); version_msg((char *)compiler_version); version_msg("\n"); } #endif version_msg(_("Linking: ")); version_msg((char *)all_lflags); #endif #ifdef DEBUG version_msg("\n"); version_msg(_(" DEBUG BUILD")); #endif } /* * Output a string for the version message. If it's going to wrap, output a * newline, unless the message is too long to fit on the screen anyway. */ static void version_msg(char *s) { int len = (int)STRLEN(s); if (!got_int && len < (int)Columns && msg_col + len >= (int)Columns && *s != '\n') msg_putchar('\n'); if (!got_int) MSG_PUTS(s); } static void do_intro_line(int row, char_u *mesg, int add_version, int attr); /* * Show the intro message when not editing a file. */ void maybe_intro_message(void) { if (BUFEMPTY() && curbuf->b_fname == NULL && firstwin->w_next == NULL && vim_strchr(p_shm, SHM_INTRO) == NULL) intro_message(FALSE); } /* * Give an introductory message about Vim. * Only used when starting Vim on an empty file, without a file name. * Or with the ":intro" command (for Sven :-). */ void intro_message( int colon) /* TRUE for ":intro" */ { int i; int row; int blanklines; int sponsor; char *p; static char *(lines[]) = { N_("VIM - Vi IMproved"), "", N_("version "), N_("by Bram Moolenaar et al."), #ifdef MODIFIED_BY " ", #endif N_("Vim is open source and freely distributable"), "", N_("Help poor children in Uganda!"), N_("type :help iccf<Enter> for information "), "", N_("type :q<Enter> to exit "), N_("type :help<Enter> or <F1> for on-line help"), N_("type :help version8<Enter> for version info"), NULL, "", N_("Running in Vi compatible mode"), N_("type :set nocp<Enter> for Vim defaults"), N_("type :help cp-default<Enter> for info on this"), }; #ifdef FEAT_GUI static char *(gui_lines[]) = { NULL, NULL, NULL, NULL, #ifdef MODIFIED_BY NULL, #endif NULL, NULL, NULL, N_("menu Help->Orphans for information "), NULL, N_("Running modeless, typed text is inserted"), N_("menu Edit->Global Settings->Toggle Insert Mode "), N_(" for two modes "), NULL, NULL, NULL, N_("menu Edit->Global Settings->Toggle Vi Compatible"), N_(" for Vim defaults "), }; #endif /* blanklines = screen height - # message lines */ blanklines = (int)Rows - ((sizeof(lines) / sizeof(char *)) - 1); if (!p_cp) blanklines += 4; /* add 4 for not showing "Vi compatible" message */ /* Don't overwrite a statusline. Depends on 'cmdheight'. */ if (p_ls > 1) blanklines -= Rows - topframe->fr_height; if (blanklines < 0) blanklines = 0; /* Show the sponsor and register message one out of four times, the Uganda * message two out of four times. */ sponsor = (int)time(NULL); sponsor = ((sponsor & 2) == 0) - ((sponsor & 4) == 0); /* start displaying the message lines after half of the blank lines */ row = blanklines / 2; if ((row >= 2 && Columns >= 50) || colon) { for (i = 0; i < (int)(sizeof(lines) / sizeof(char *)); ++i) { p = lines[i]; #ifdef FEAT_GUI if (p_im && gui.in_use && gui_lines[i] != NULL) p = gui_lines[i]; #endif if (p == NULL) { if (!p_cp) break; continue; } if (sponsor != 0) { if (strstr(p, "children") != NULL) p = sponsor < 0 ? N_("Sponsor Vim development!") : N_("Become a registered Vim user!"); else if (strstr(p, "iccf") != NULL) p = sponsor < 0 ? N_("type :help sponsor<Enter> for information ") : N_("type :help register<Enter> for information "); else if (strstr(p, "Orphans") != NULL) p = N_("menu Help->Sponsor/Register for information "); } if (*p != NUL) do_intro_line(row, (char_u *)_(p), i == 2, 0); ++row; } } /* Make the wait-return message appear just below the text. */ if (colon) msg_row = row; } static void do_intro_line( int row, char_u *mesg, int add_version, int attr) { char_u vers[20]; int col; char_u *p; int l; int clen; #ifdef MODIFIED_BY # define MODBY_LEN 150 char_u modby[MODBY_LEN]; if (*mesg == ' ') { vim_strncpy(modby, (char_u *)_("Modified by "), MODBY_LEN - 1); l = (int)STRLEN(modby); vim_strncpy(modby + l, (char_u *)MODIFIED_BY, MODBY_LEN - l - 1); mesg = modby; } #endif /* Center the message horizontally. */ col = vim_strsize(mesg); if (add_version) { STRCPY(vers, mediumVersion); if (highest_patch()) { /* Check for 9.9x or 9.9xx, alpha/beta version */ if (isalpha((int)vers[3])) { int len = (isalpha((int)vers[4])) ? 5 : 4; sprintf((char *)vers + len, ".%d%s", highest_patch(), mediumVersion + len); } else sprintf((char *)vers + 3, ".%d", highest_patch()); } col += (int)STRLEN(vers); } col = (Columns - col) / 2; if (col < 0) col = 0; /* Split up in parts to highlight <> items differently. */ for (p = mesg; *p != NUL; p += l) { clen = 0; for (l = 0; p[l] != NUL && (l == 0 || (p[l] != '<' && p[l - 1] != '>')); ++l) { #ifdef FEAT_MBYTE if (has_mbyte) { clen += ptr2cells(p + l); l += (*mb_ptr2len)(p + l) - 1; } else #endif clen += byte2cells(p[l]); } screen_puts_len(p, l, row, col, *p == '<' ? HL_ATTR(HLF_8) : attr); col += clen; } /* Add the version number to the version line. */ if (add_version) screen_puts(vers, row, col, 0); } /* * ":intro": clear screen, display intro screen and wait for return. */ void ex_intro(exarg_T *eap UNUSED) { screenclear(); intro_message(TRUE); wait_return(TRUE); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2958_3
crossvul-cpp_data_good_3769_0
/* * binfmt_misc.c * * Copyright (C) 1997 Richard Günther * * binfmt_misc detects binaries via a magic or filename extension and invokes * a specified wrapper. This should obsolete binfmt_java, binfmt_em86 and * binfmt_mz. * * 1997-04-25 first version * [...] * 1997-05-19 cleanup * 1997-06-26 hpa: pass the real filename rather than argv[0] * 1997-06-30 minor cleanup * 1997-08-09 removed extension stripping, locking cleanup * 2001-02-28 AV: rewritten into something that resembles C. Original didn't. */ #include <linux/module.h> #include <linux/init.h> #include <linux/sched.h> #include <linux/magic.h> #include <linux/binfmts.h> #include <linux/slab.h> #include <linux/ctype.h> #include <linux/file.h> #include <linux/pagemap.h> #include <linux/namei.h> #include <linux/mount.h> #include <linux/syscalls.h> #include <linux/fs.h> #include <asm/uaccess.h> enum { VERBOSE_STATUS = 1 /* make it zero to save 400 bytes kernel memory */ }; static LIST_HEAD(entries); static int enabled = 1; enum {Enabled, Magic}; #define MISC_FMT_PRESERVE_ARGV0 (1<<31) #define MISC_FMT_OPEN_BINARY (1<<30) #define MISC_FMT_CREDENTIALS (1<<29) typedef struct { struct list_head list; unsigned long flags; /* type, status, etc. */ int offset; /* offset of magic */ int size; /* size of magic/mask */ char *magic; /* magic or filename extension */ char *mask; /* mask, NULL for exact match */ char *interpreter; /* filename of interpreter */ char *name; struct dentry *dentry; } Node; static DEFINE_RWLOCK(entries_lock); static struct file_system_type bm_fs_type; static struct vfsmount *bm_mnt; static int entry_count; /* * Check if we support the binfmt * if we do, return the node, else NULL * locking is done in load_misc_binary */ static Node *check_file(struct linux_binprm *bprm) { char *p = strrchr(bprm->interp, '.'); struct list_head *l; list_for_each(l, &entries) { Node *e = list_entry(l, Node, list); char *s; int j; if (!test_bit(Enabled, &e->flags)) continue; if (!test_bit(Magic, &e->flags)) { if (p && !strcmp(e->magic, p + 1)) return e; continue; } s = bprm->buf + e->offset; if (e->mask) { for (j = 0; j < e->size; j++) if ((*s++ ^ e->magic[j]) & e->mask[j]) break; } else { for (j = 0; j < e->size; j++) if ((*s++ ^ e->magic[j])) break; } if (j == e->size) return e; } return NULL; } /* * the loader itself */ static int load_misc_binary(struct linux_binprm *bprm) { Node *fmt; struct file * interp_file = NULL; char iname[BINPRM_BUF_SIZE]; const char *iname_addr = iname; int retval; int fd_binary = -1; retval = -ENOEXEC; if (!enabled) goto _ret; /* to keep locking time low, we copy the interpreter string */ read_lock(&entries_lock); fmt = check_file(bprm); if (fmt) strlcpy(iname, fmt->interpreter, BINPRM_BUF_SIZE); read_unlock(&entries_lock); if (!fmt) goto _ret; if (!(fmt->flags & MISC_FMT_PRESERVE_ARGV0)) { retval = remove_arg_zero(bprm); if (retval) goto _ret; } if (fmt->flags & MISC_FMT_OPEN_BINARY) { /* if the binary should be opened on behalf of the * interpreter than keep it open and assign descriptor * to it */ fd_binary = get_unused_fd(); if (fd_binary < 0) { retval = fd_binary; goto _ret; } fd_install(fd_binary, bprm->file); /* if the binary is not readable than enforce mm->dumpable=0 regardless of the interpreter's permissions */ would_dump(bprm, bprm->file); allow_write_access(bprm->file); bprm->file = NULL; /* mark the bprm that fd should be passed to interp */ bprm->interp_flags |= BINPRM_FLAGS_EXECFD; bprm->interp_data = fd_binary; } else { allow_write_access(bprm->file); fput(bprm->file); bprm->file = NULL; } /* make argv[1] be the path to the binary */ retval = copy_strings_kernel (1, &bprm->interp, bprm); if (retval < 0) goto _error; bprm->argc++; /* add the interp as argv[0] */ retval = copy_strings_kernel (1, &iname_addr, bprm); if (retval < 0) goto _error; bprm->argc ++; /* Update interp in case binfmt_script needs it. */ retval = bprm_change_interp(iname, bprm); if (retval < 0) goto _error; interp_file = open_exec (iname); retval = PTR_ERR (interp_file); if (IS_ERR (interp_file)) goto _error; bprm->file = interp_file; if (fmt->flags & MISC_FMT_CREDENTIALS) { /* * No need to call prepare_binprm(), it's already been * done. bprm->buf is stale, update from interp_file. */ memset(bprm->buf, 0, BINPRM_BUF_SIZE); retval = kernel_read(bprm->file, 0, bprm->buf, BINPRM_BUF_SIZE); } else retval = prepare_binprm (bprm); if (retval < 0) goto _error; retval = search_binary_handler(bprm); if (retval < 0) goto _error; _ret: return retval; _error: if (fd_binary > 0) sys_close(fd_binary); bprm->interp_flags = 0; bprm->interp_data = 0; goto _ret; } /* Command parsers */ /* * parses and copies one argument enclosed in del from *sp to *dp, * recognising the \x special. * returns pointer to the copied argument or NULL in case of an * error (and sets err) or null argument length. */ static char *scanarg(char *s, char del) { char c; while ((c = *s++) != del) { if (c == '\\' && *s == 'x') { s++; if (!isxdigit(*s++)) return NULL; if (!isxdigit(*s++)) return NULL; } } return s; } static int unquote(char *from) { char c = 0, *s = from, *p = from; while ((c = *s++) != '\0') { if (c == '\\' && *s == 'x') { s++; c = toupper(*s++); *p = (c - (isdigit(c) ? '0' : 'A' - 10)) << 4; c = toupper(*s++); *p++ |= c - (isdigit(c) ? '0' : 'A' - 10); continue; } *p++ = c; } return p - from; } static char * check_special_flags (char * sfs, Node * e) { char * p = sfs; int cont = 1; /* special flags */ while (cont) { switch (*p) { case 'P': p++; e->flags |= MISC_FMT_PRESERVE_ARGV0; break; case 'O': p++; e->flags |= MISC_FMT_OPEN_BINARY; break; case 'C': p++; /* this flags also implies the open-binary flag */ e->flags |= (MISC_FMT_CREDENTIALS | MISC_FMT_OPEN_BINARY); break; default: cont = 0; } } return p; } /* * This registers a new binary format, it recognises the syntax * ':name:type:offset:magic:mask:interpreter:flags' * where the ':' is the IFS, that can be chosen with the first char */ static Node *create_entry(const char __user *buffer, size_t count) { Node *e; int memsize, err; char *buf, *p; char del; /* some sanity checks */ err = -EINVAL; if ((count < 11) || (count > 256)) goto out; err = -ENOMEM; memsize = sizeof(Node) + count + 8; e = kmalloc(memsize, GFP_USER); if (!e) goto out; p = buf = (char *)e + sizeof(Node); memset(e, 0, sizeof(Node)); if (copy_from_user(buf, buffer, count)) goto Efault; del = *p++; /* delimeter */ memset(buf+count, del, 8); e->name = p; p = strchr(p, del); if (!p) goto Einval; *p++ = '\0'; if (!e->name[0] || !strcmp(e->name, ".") || !strcmp(e->name, "..") || strchr(e->name, '/')) goto Einval; switch (*p++) { case 'E': e->flags = 1<<Enabled; break; case 'M': e->flags = (1<<Enabled) | (1<<Magic); break; default: goto Einval; } if (*p++ != del) goto Einval; if (test_bit(Magic, &e->flags)) { char *s = strchr(p, del); if (!s) goto Einval; *s++ = '\0'; e->offset = simple_strtoul(p, &p, 10); if (*p++) goto Einval; e->magic = p; p = scanarg(p, del); if (!p) goto Einval; p[-1] = '\0'; if (!e->magic[0]) goto Einval; e->mask = p; p = scanarg(p, del); if (!p) goto Einval; p[-1] = '\0'; if (!e->mask[0]) e->mask = NULL; e->size = unquote(e->magic); if (e->mask && unquote(e->mask) != e->size) goto Einval; if (e->size + e->offset > BINPRM_BUF_SIZE) goto Einval; } else { p = strchr(p, del); if (!p) goto Einval; *p++ = '\0'; e->magic = p; p = strchr(p, del); if (!p) goto Einval; *p++ = '\0'; if (!e->magic[0] || strchr(e->magic, '/')) goto Einval; p = strchr(p, del); if (!p) goto Einval; *p++ = '\0'; } e->interpreter = p; p = strchr(p, del); if (!p) goto Einval; *p++ = '\0'; if (!e->interpreter[0]) goto Einval; p = check_special_flags (p, e); if (*p == '\n') p++; if (p != buf + count) goto Einval; return e; out: return ERR_PTR(err); Efault: kfree(e); return ERR_PTR(-EFAULT); Einval: kfree(e); return ERR_PTR(-EINVAL); } /* * Set status of entry/binfmt_misc: * '1' enables, '0' disables and '-1' clears entry/binfmt_misc */ static int parse_command(const char __user *buffer, size_t count) { char s[4]; if (!count) return 0; if (count > 3) return -EINVAL; if (copy_from_user(s, buffer, count)) return -EFAULT; if (s[count-1] == '\n') count--; if (count == 1 && s[0] == '0') return 1; if (count == 1 && s[0] == '1') return 2; if (count == 2 && s[0] == '-' && s[1] == '1') return 3; return -EINVAL; } /* generic stuff */ static void entry_status(Node *e, char *page) { char *dp; char *status = "disabled"; const char * flags = "flags: "; if (test_bit(Enabled, &e->flags)) status = "enabled"; if (!VERBOSE_STATUS) { sprintf(page, "%s\n", status); return; } sprintf(page, "%s\ninterpreter %s\n", status, e->interpreter); dp = page + strlen(page); /* print the special flags */ sprintf (dp, "%s", flags); dp += strlen (flags); if (e->flags & MISC_FMT_PRESERVE_ARGV0) { *dp ++ = 'P'; } if (e->flags & MISC_FMT_OPEN_BINARY) { *dp ++ = 'O'; } if (e->flags & MISC_FMT_CREDENTIALS) { *dp ++ = 'C'; } *dp ++ = '\n'; if (!test_bit(Magic, &e->flags)) { sprintf(dp, "extension .%s\n", e->magic); } else { int i; sprintf(dp, "offset %i\nmagic ", e->offset); dp = page + strlen(page); for (i = 0; i < e->size; i++) { sprintf(dp, "%02x", 0xff & (int) (e->magic[i])); dp += 2; } if (e->mask) { sprintf(dp, "\nmask "); dp += 6; for (i = 0; i < e->size; i++) { sprintf(dp, "%02x", 0xff & (int) (e->mask[i])); dp += 2; } } *dp++ = '\n'; *dp = '\0'; } } static struct inode *bm_get_inode(struct super_block *sb, int mode) { struct inode * inode = new_inode(sb); if (inode) { inode->i_ino = get_next_ino(); inode->i_mode = mode; inode->i_atime = inode->i_mtime = inode->i_ctime = current_fs_time(inode->i_sb); } return inode; } static void bm_evict_inode(struct inode *inode) { clear_inode(inode); kfree(inode->i_private); } static void kill_node(Node *e) { struct dentry *dentry; write_lock(&entries_lock); dentry = e->dentry; if (dentry) { list_del_init(&e->list); e->dentry = NULL; } write_unlock(&entries_lock); if (dentry) { drop_nlink(dentry->d_inode); d_drop(dentry); dput(dentry); simple_release_fs(&bm_mnt, &entry_count); } } /* /<entry> */ static ssize_t bm_entry_read(struct file * file, char __user * buf, size_t nbytes, loff_t *ppos) { Node *e = file->f_path.dentry->d_inode->i_private; ssize_t res; char *page; if (!(page = (char*) __get_free_page(GFP_KERNEL))) return -ENOMEM; entry_status(e, page); res = simple_read_from_buffer(buf, nbytes, ppos, page, strlen(page)); free_page((unsigned long) page); return res; } static ssize_t bm_entry_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { struct dentry *root; Node *e = file->f_path.dentry->d_inode->i_private; int res = parse_command(buffer, count); switch (res) { case 1: clear_bit(Enabled, &e->flags); break; case 2: set_bit(Enabled, &e->flags); break; case 3: root = dget(file->f_path.dentry->d_sb->s_root); mutex_lock(&root->d_inode->i_mutex); kill_node(e); mutex_unlock(&root->d_inode->i_mutex); dput(root); break; default: return res; } return count; } static const struct file_operations bm_entry_operations = { .read = bm_entry_read, .write = bm_entry_write, .llseek = default_llseek, }; /* /register */ static ssize_t bm_register_write(struct file *file, const char __user *buffer, size_t count, loff_t *ppos) { Node *e; struct inode *inode; struct dentry *root, *dentry; struct super_block *sb = file->f_path.dentry->d_sb; int err = 0; e = create_entry(buffer, count); if (IS_ERR(e)) return PTR_ERR(e); root = dget(sb->s_root); mutex_lock(&root->d_inode->i_mutex); dentry = lookup_one_len(e->name, root, strlen(e->name)); err = PTR_ERR(dentry); if (IS_ERR(dentry)) goto out; err = -EEXIST; if (dentry->d_inode) goto out2; inode = bm_get_inode(sb, S_IFREG | 0644); err = -ENOMEM; if (!inode) goto out2; err = simple_pin_fs(&bm_fs_type, &bm_mnt, &entry_count); if (err) { iput(inode); inode = NULL; goto out2; } e->dentry = dget(dentry); inode->i_private = e; inode->i_fop = &bm_entry_operations; d_instantiate(dentry, inode); write_lock(&entries_lock); list_add(&e->list, &entries); write_unlock(&entries_lock); err = 0; out2: dput(dentry); out: mutex_unlock(&root->d_inode->i_mutex); dput(root); if (err) { kfree(e); return -EINVAL; } return count; } static const struct file_operations bm_register_operations = { .write = bm_register_write, .llseek = noop_llseek, }; /* /status */ static ssize_t bm_status_read(struct file *file, char __user *buf, size_t nbytes, loff_t *ppos) { char *s = enabled ? "enabled\n" : "disabled\n"; return simple_read_from_buffer(buf, nbytes, ppos, s, strlen(s)); } static ssize_t bm_status_write(struct file * file, const char __user * buffer, size_t count, loff_t *ppos) { int res = parse_command(buffer, count); struct dentry *root; switch (res) { case 1: enabled = 0; break; case 2: enabled = 1; break; case 3: root = dget(file->f_path.dentry->d_sb->s_root); mutex_lock(&root->d_inode->i_mutex); while (!list_empty(&entries)) kill_node(list_entry(entries.next, Node, list)); mutex_unlock(&root->d_inode->i_mutex); dput(root); default: return res; } return count; } static const struct file_operations bm_status_operations = { .read = bm_status_read, .write = bm_status_write, .llseek = default_llseek, }; /* Superblock handling */ static const struct super_operations s_ops = { .statfs = simple_statfs, .evict_inode = bm_evict_inode, }; static int bm_fill_super(struct super_block * sb, void * data, int silent) { static struct tree_descr bm_files[] = { [2] = {"status", &bm_status_operations, S_IWUSR|S_IRUGO}, [3] = {"register", &bm_register_operations, S_IWUSR}, /* last one */ {""} }; int err = simple_fill_super(sb, BINFMTFS_MAGIC, bm_files); if (!err) sb->s_op = &s_ops; return err; } static struct dentry *bm_mount(struct file_system_type *fs_type, int flags, const char *dev_name, void *data) { return mount_single(fs_type, flags, data, bm_fill_super); } static struct linux_binfmt misc_format = { .module = THIS_MODULE, .load_binary = load_misc_binary, }; static struct file_system_type bm_fs_type = { .owner = THIS_MODULE, .name = "binfmt_misc", .mount = bm_mount, .kill_sb = kill_litter_super, }; static int __init init_misc_binfmt(void) { int err = register_filesystem(&bm_fs_type); if (!err) insert_binfmt(&misc_format); return err; } static void __exit exit_misc_binfmt(void) { unregister_binfmt(&misc_format); unregister_filesystem(&bm_fs_type); } core_initcall(init_misc_binfmt); module_exit(exit_misc_binfmt); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/good_3769_0
crossvul-cpp_data_good_2864_1
/* * FPU signal frame handling routines. */ #include <linux/compat.h> #include <linux/cpu.h> #include <asm/fpu/internal.h> #include <asm/fpu/signal.h> #include <asm/fpu/regset.h> #include <asm/fpu/xstate.h> #include <asm/sigframe.h> #include <asm/trace/fpu.h> static struct _fpx_sw_bytes fx_sw_reserved, fx_sw_reserved_ia32; /* * Check for the presence of extended state information in the * user fpstate pointer in the sigcontext. */ static inline int check_for_xstate(struct fxregs_state __user *buf, void __user *fpstate, struct _fpx_sw_bytes *fx_sw) { int min_xstate_size = sizeof(struct fxregs_state) + sizeof(struct xstate_header); unsigned int magic2; if (__copy_from_user(fx_sw, &buf->sw_reserved[0], sizeof(*fx_sw))) return -1; /* Check for the first magic field and other error scenarios. */ if (fx_sw->magic1 != FP_XSTATE_MAGIC1 || fx_sw->xstate_size < min_xstate_size || fx_sw->xstate_size > fpu_user_xstate_size || fx_sw->xstate_size > fx_sw->extended_size) return -1; /* * Check for the presence of second magic word at the end of memory * layout. This detects the case where the user just copied the legacy * fpstate layout with out copying the extended state information * in the memory layout. */ if (__get_user(magic2, (__u32 __user *)(fpstate + fx_sw->xstate_size)) || magic2 != FP_XSTATE_MAGIC2) return -1; return 0; } /* * Signal frame handlers. */ static inline int save_fsave_header(struct task_struct *tsk, void __user *buf) { if (use_fxsr()) { struct xregs_state *xsave = &tsk->thread.fpu.state.xsave; struct user_i387_ia32_struct env; struct _fpstate_32 __user *fp = buf; convert_from_fxsr(&env, tsk); if (__copy_to_user(buf, &env, sizeof(env)) || __put_user(xsave->i387.swd, &fp->status) || __put_user(X86_FXSR_MAGIC, &fp->magic)) return -1; } else { struct fregs_state __user *fp = buf; u32 swd; if (__get_user(swd, &fp->swd) || __put_user(swd, &fp->status)) return -1; } return 0; } static inline int save_xstate_epilog(void __user *buf, int ia32_frame) { struct xregs_state __user *x = buf; struct _fpx_sw_bytes *sw_bytes; u32 xfeatures; int err; /* Setup the bytes not touched by the [f]xsave and reserved for SW. */ sw_bytes = ia32_frame ? &fx_sw_reserved_ia32 : &fx_sw_reserved; err = __copy_to_user(&x->i387.sw_reserved, sw_bytes, sizeof(*sw_bytes)); if (!use_xsave()) return err; err |= __put_user(FP_XSTATE_MAGIC2, (__u32 *)(buf + fpu_user_xstate_size)); /* * Read the xfeatures which we copied (directly from the cpu or * from the state in task struct) to the user buffers. */ err |= __get_user(xfeatures, (__u32 *)&x->header.xfeatures); /* * For legacy compatible, we always set FP/SSE bits in the bit * vector while saving the state to the user context. This will * enable us capturing any changes(during sigreturn) to * the FP/SSE bits by the legacy applications which don't touch * xfeatures in the xsave header. * * xsave aware apps can change the xfeatures in the xsave * header as well as change any contents in the memory layout. * xrestore as part of sigreturn will capture all the changes. */ xfeatures |= XFEATURE_MASK_FPSSE; err |= __put_user(xfeatures, (__u32 *)&x->header.xfeatures); return err; } static inline int copy_fpregs_to_sigframe(struct xregs_state __user *buf) { int err; if (use_xsave()) err = copy_xregs_to_user(buf); else if (use_fxsr()) err = copy_fxregs_to_user((struct fxregs_state __user *) buf); else err = copy_fregs_to_user((struct fregs_state __user *) buf); if (unlikely(err) && __clear_user(buf, fpu_user_xstate_size)) err = -EFAULT; return err; } /* * Save the fpu, extended register state to the user signal frame. * * 'buf_fx' is the 64-byte aligned pointer at which the [f|fx|x]save * state is copied. * 'buf' points to the 'buf_fx' or to the fsave header followed by 'buf_fx'. * * buf == buf_fx for 64-bit frames and 32-bit fsave frame. * buf != buf_fx for 32-bit frames with fxstate. * * If the fpu, extended register state is live, save the state directly * to the user frame pointed by the aligned pointer 'buf_fx'. Otherwise, * copy the thread's fpu state to the user frame starting at 'buf_fx'. * * If this is a 32-bit frame with fxstate, put a fsave header before * the aligned state at 'buf_fx'. * * For [f]xsave state, update the SW reserved fields in the [f]xsave frame * indicating the absence/presence of the extended state to the user. */ int copy_fpstate_to_sigframe(void __user *buf, void __user *buf_fx, int size) { struct fpu *fpu = &current->thread.fpu; struct xregs_state *xsave = &fpu->state.xsave; struct task_struct *tsk = current; int ia32_fxstate = (buf != buf_fx); ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) || IS_ENABLED(CONFIG_IA32_EMULATION)); if (!access_ok(VERIFY_WRITE, buf, size)) return -EACCES; if (!static_cpu_has(X86_FEATURE_FPU)) return fpregs_soft_get(current, NULL, 0, sizeof(struct user_i387_ia32_struct), NULL, (struct _fpstate_32 __user *) buf) ? -1 : 1; if (fpu->fpstate_active || using_compacted_format()) { /* Save the live register state to the user directly. */ if (copy_fpregs_to_sigframe(buf_fx)) return -1; /* Update the thread's fxstate to save the fsave header. */ if (ia32_fxstate) copy_fxregs_to_kernel(fpu); } else { /* * It is a *bug* if kernel uses compacted-format for xsave * area and we copy it out directly to a signal frame. It * should have been handled above by saving the registers * directly. */ if (boot_cpu_has(X86_FEATURE_XSAVES)) { WARN_ONCE(1, "x86/fpu: saving compacted-format xsave area to a signal frame!\n"); return -1; } fpstate_sanitize_xstate(fpu); if (__copy_to_user(buf_fx, xsave, fpu_user_xstate_size)) return -1; } /* Save the fsave header for the 32-bit frames. */ if ((ia32_fxstate || !use_fxsr()) && save_fsave_header(tsk, buf)) return -1; if (use_fxsr() && save_xstate_epilog(buf_fx, ia32_fxstate)) return -1; return 0; } static inline void sanitize_restored_xstate(struct task_struct *tsk, struct user_i387_ia32_struct *ia32_env, u64 xfeatures, int fx_only) { struct xregs_state *xsave = &tsk->thread.fpu.state.xsave; struct xstate_header *header = &xsave->header; if (use_xsave()) { /* These bits must be zero. */ memset(header->reserved, 0, 48); /* * Init the state that is not present in the memory * layout and not enabled by the OS. */ if (fx_only) header->xfeatures = XFEATURE_MASK_FPSSE; else header->xfeatures &= (xfeatures_mask & xfeatures); } if (use_fxsr()) { /* * mscsr reserved bits must be masked to zero for security * reasons. */ xsave->i387.mxcsr &= mxcsr_feature_mask; convert_to_fxsr(tsk, ia32_env); } } /* * Restore the extended state if present. Otherwise, restore the FP/SSE state. */ static inline int copy_user_to_fpregs_zeroing(void __user *buf, u64 xbv, int fx_only) { if (use_xsave()) { if ((unsigned long)buf % 64 || fx_only) { u64 init_bv = xfeatures_mask & ~XFEATURE_MASK_FPSSE; copy_kernel_to_xregs(&init_fpstate.xsave, init_bv); return copy_user_to_fxregs(buf); } else { u64 init_bv = xfeatures_mask & ~xbv; if (unlikely(init_bv)) copy_kernel_to_xregs(&init_fpstate.xsave, init_bv); return copy_user_to_xregs(buf, xbv); } } else if (use_fxsr()) { return copy_user_to_fxregs(buf); } else return copy_user_to_fregs(buf); } static int __fpu__restore_sig(void __user *buf, void __user *buf_fx, int size) { int ia32_fxstate = (buf != buf_fx); struct task_struct *tsk = current; struct fpu *fpu = &tsk->thread.fpu; int state_size = fpu_kernel_xstate_size; u64 xfeatures = 0; int fx_only = 0; ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) || IS_ENABLED(CONFIG_IA32_EMULATION)); if (!buf) { fpu__clear(fpu); return 0; } if (!access_ok(VERIFY_READ, buf, size)) return -EACCES; fpu__activate_curr(fpu); if (!static_cpu_has(X86_FEATURE_FPU)) return fpregs_soft_set(current, NULL, 0, sizeof(struct user_i387_ia32_struct), NULL, buf) != 0; if (use_xsave()) { struct _fpx_sw_bytes fx_sw_user; if (unlikely(check_for_xstate(buf_fx, buf_fx, &fx_sw_user))) { /* * Couldn't find the extended state information in the * memory layout. Restore just the FP/SSE and init all * the other extended state. */ state_size = sizeof(struct fxregs_state); fx_only = 1; trace_x86_fpu_xstate_check_failed(fpu); } else { state_size = fx_sw_user.xstate_size; xfeatures = fx_sw_user.xfeatures; } } if (ia32_fxstate) { /* * For 32-bit frames with fxstate, copy the user state to the * thread's fpu state, reconstruct fxstate from the fsave * header. Sanitize the copied state etc. */ struct fpu *fpu = &tsk->thread.fpu; struct user_i387_ia32_struct env; int err = 0; /* * Drop the current fpu which clears fpu->fpstate_active. This ensures * that any context-switch during the copy of the new state, * avoids the intermediate state from getting restored/saved. * Thus avoiding the new restored state from getting corrupted. * We will be ready to restore/save the state only after * fpu->fpstate_active is again set. */ fpu__drop(fpu); if (using_compacted_format()) { err = copy_user_to_xstate(&fpu->state.xsave, buf_fx); } else { err = __copy_from_user(&fpu->state.xsave, buf_fx, state_size); /* xcomp_bv must be 0 when using uncompacted format */ if (!err && state_size > offsetof(struct xregs_state, header) && fpu->state.xsave.header.xcomp_bv) err = -EINVAL; } if (err || __copy_from_user(&env, buf, sizeof(env))) { fpstate_init(&fpu->state); trace_x86_fpu_init_state(fpu); err = -1; } else { sanitize_restored_xstate(tsk, &env, xfeatures, fx_only); } fpu->fpstate_active = 1; preempt_disable(); fpu__restore(fpu); preempt_enable(); return err; } else { /* * For 64-bit frames and 32-bit fsave frames, restore the user * state to the registers directly (with exceptions handled). */ user_fpu_begin(); if (copy_user_to_fpregs_zeroing(buf_fx, xfeatures, fx_only)) { fpu__clear(fpu); return -1; } } return 0; } static inline int xstate_sigframe_size(void) { return use_xsave() ? fpu_user_xstate_size + FP_XSTATE_MAGIC2_SIZE : fpu_user_xstate_size; } /* * Restore FPU state from a sigframe: */ int fpu__restore_sig(void __user *buf, int ia32_frame) { void __user *buf_fx = buf; int size = xstate_sigframe_size(); if (ia32_frame && use_fxsr()) { buf_fx = buf + sizeof(struct fregs_state); size += sizeof(struct fregs_state); } return __fpu__restore_sig(buf, buf_fx, size); } unsigned long fpu__alloc_mathframe(unsigned long sp, int ia32_frame, unsigned long *buf_fx, unsigned long *size) { unsigned long frame_size = xstate_sigframe_size(); *buf_fx = sp = round_down(sp - frame_size, 64); if (ia32_frame && use_fxsr()) { frame_size += sizeof(struct fregs_state); sp -= sizeof(struct fregs_state); } *size = frame_size; return sp; } /* * Prepare the SW reserved portion of the fxsave memory layout, indicating * the presence of the extended state information in the memory layout * pointed by the fpstate pointer in the sigcontext. * This will be saved when ever the FP and extended state context is * saved on the user stack during the signal handler delivery to the user. */ void fpu__init_prepare_fx_sw_frame(void) { int size = fpu_user_xstate_size + FP_XSTATE_MAGIC2_SIZE; fx_sw_reserved.magic1 = FP_XSTATE_MAGIC1; fx_sw_reserved.extended_size = size; fx_sw_reserved.xfeatures = xfeatures_mask; fx_sw_reserved.xstate_size = fpu_user_xstate_size; if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) { int fsave_header_size = sizeof(struct fregs_state); fx_sw_reserved_ia32 = fx_sw_reserved; fx_sw_reserved_ia32.extended_size = size + fsave_header_size; } }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2864_1
crossvul-cpp_data_bad_1626_0
/* * linux/fs/namespace.c * * (C) Copyright Al Viro 2000, 2001 * Released under GPL v2. * * Based on code from fs/super.c, copyright Linus Torvalds and others. * Heavily rewritten. */ #include <linux/syscalls.h> #include <linux/export.h> #include <linux/capability.h> #include <linux/mnt_namespace.h> #include <linux/user_namespace.h> #include <linux/namei.h> #include <linux/security.h> #include <linux/idr.h> #include <linux/init.h> /* init_rootfs */ #include <linux/fs_struct.h> /* get_fs_root et.al. */ #include <linux/fsnotify.h> /* fsnotify_vfsmount_delete */ #include <linux/uaccess.h> #include <linux/proc_ns.h> #include <linux/magic.h> #include <linux/bootmem.h> #include <linux/task_work.h> #include "pnode.h" #include "internal.h" static unsigned int m_hash_mask __read_mostly; static unsigned int m_hash_shift __read_mostly; static unsigned int mp_hash_mask __read_mostly; static unsigned int mp_hash_shift __read_mostly; static __initdata unsigned long mhash_entries; static int __init set_mhash_entries(char *str) { if (!str) return 0; mhash_entries = simple_strtoul(str, &str, 0); return 1; } __setup("mhash_entries=", set_mhash_entries); static __initdata unsigned long mphash_entries; static int __init set_mphash_entries(char *str) { if (!str) return 0; mphash_entries = simple_strtoul(str, &str, 0); return 1; } __setup("mphash_entries=", set_mphash_entries); static u64 event; static DEFINE_IDA(mnt_id_ida); static DEFINE_IDA(mnt_group_ida); static DEFINE_SPINLOCK(mnt_id_lock); static int mnt_id_start = 0; static int mnt_group_start = 1; static struct hlist_head *mount_hashtable __read_mostly; static struct hlist_head *mountpoint_hashtable __read_mostly; static struct kmem_cache *mnt_cache __read_mostly; static DECLARE_RWSEM(namespace_sem); /* /sys/fs */ struct kobject *fs_kobj; EXPORT_SYMBOL_GPL(fs_kobj); /* * vfsmount lock may be taken for read to prevent changes to the * vfsmount hash, ie. during mountpoint lookups or walking back * up the tree. * * It should be taken for write in all cases where the vfsmount * tree or hash is modified or when a vfsmount structure is modified. */ __cacheline_aligned_in_smp DEFINE_SEQLOCK(mount_lock); static inline struct hlist_head *m_hash(struct vfsmount *mnt, struct dentry *dentry) { unsigned long tmp = ((unsigned long)mnt / L1_CACHE_BYTES); tmp += ((unsigned long)dentry / L1_CACHE_BYTES); tmp = tmp + (tmp >> m_hash_shift); return &mount_hashtable[tmp & m_hash_mask]; } static inline struct hlist_head *mp_hash(struct dentry *dentry) { unsigned long tmp = ((unsigned long)dentry / L1_CACHE_BYTES); tmp = tmp + (tmp >> mp_hash_shift); return &mountpoint_hashtable[tmp & mp_hash_mask]; } /* * allocation is serialized by namespace_sem, but we need the spinlock to * serialize with freeing. */ static int mnt_alloc_id(struct mount *mnt) { int res; retry: ida_pre_get(&mnt_id_ida, GFP_KERNEL); spin_lock(&mnt_id_lock); res = ida_get_new_above(&mnt_id_ida, mnt_id_start, &mnt->mnt_id); if (!res) mnt_id_start = mnt->mnt_id + 1; spin_unlock(&mnt_id_lock); if (res == -EAGAIN) goto retry; return res; } static void mnt_free_id(struct mount *mnt) { int id = mnt->mnt_id; spin_lock(&mnt_id_lock); ida_remove(&mnt_id_ida, id); if (mnt_id_start > id) mnt_id_start = id; spin_unlock(&mnt_id_lock); } /* * Allocate a new peer group ID * * mnt_group_ida is protected by namespace_sem */ static int mnt_alloc_group_id(struct mount *mnt) { int res; if (!ida_pre_get(&mnt_group_ida, GFP_KERNEL)) return -ENOMEM; res = ida_get_new_above(&mnt_group_ida, mnt_group_start, &mnt->mnt_group_id); if (!res) mnt_group_start = mnt->mnt_group_id + 1; return res; } /* * Release a peer group ID */ void mnt_release_group_id(struct mount *mnt) { int id = mnt->mnt_group_id; ida_remove(&mnt_group_ida, id); if (mnt_group_start > id) mnt_group_start = id; mnt->mnt_group_id = 0; } /* * vfsmount lock must be held for read */ static inline void mnt_add_count(struct mount *mnt, int n) { #ifdef CONFIG_SMP this_cpu_add(mnt->mnt_pcp->mnt_count, n); #else preempt_disable(); mnt->mnt_count += n; preempt_enable(); #endif } /* * vfsmount lock must be held for write */ unsigned int mnt_get_count(struct mount *mnt) { #ifdef CONFIG_SMP unsigned int count = 0; int cpu; for_each_possible_cpu(cpu) { count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_count; } return count; #else return mnt->mnt_count; #endif } static void drop_mountpoint(struct fs_pin *p) { struct mount *m = container_of(p, struct mount, mnt_umount); dput(m->mnt_ex_mountpoint); pin_remove(p); mntput(&m->mnt); } static struct mount *alloc_vfsmnt(const char *name) { struct mount *mnt = kmem_cache_zalloc(mnt_cache, GFP_KERNEL); if (mnt) { int err; err = mnt_alloc_id(mnt); if (err) goto out_free_cache; if (name) { mnt->mnt_devname = kstrdup_const(name, GFP_KERNEL); if (!mnt->mnt_devname) goto out_free_id; } #ifdef CONFIG_SMP mnt->mnt_pcp = alloc_percpu(struct mnt_pcp); if (!mnt->mnt_pcp) goto out_free_devname; this_cpu_add(mnt->mnt_pcp->mnt_count, 1); #else mnt->mnt_count = 1; mnt->mnt_writers = 0; #endif INIT_HLIST_NODE(&mnt->mnt_hash); INIT_LIST_HEAD(&mnt->mnt_child); INIT_LIST_HEAD(&mnt->mnt_mounts); INIT_LIST_HEAD(&mnt->mnt_list); INIT_LIST_HEAD(&mnt->mnt_expire); INIT_LIST_HEAD(&mnt->mnt_share); INIT_LIST_HEAD(&mnt->mnt_slave_list); INIT_LIST_HEAD(&mnt->mnt_slave); INIT_HLIST_NODE(&mnt->mnt_mp_list); #ifdef CONFIG_FSNOTIFY INIT_HLIST_HEAD(&mnt->mnt_fsnotify_marks); #endif init_fs_pin(&mnt->mnt_umount, drop_mountpoint); } return mnt; #ifdef CONFIG_SMP out_free_devname: kfree_const(mnt->mnt_devname); #endif out_free_id: mnt_free_id(mnt); out_free_cache: kmem_cache_free(mnt_cache, mnt); return NULL; } /* * Most r/o checks on a fs are for operations that take * discrete amounts of time, like a write() or unlink(). * We must keep track of when those operations start * (for permission checks) and when they end, so that * we can determine when writes are able to occur to * a filesystem. */ /* * __mnt_is_readonly: check whether a mount is read-only * @mnt: the mount to check for its write status * * This shouldn't be used directly ouside of the VFS. * It does not guarantee that the filesystem will stay * r/w, just that it is right *now*. This can not and * should not be used in place of IS_RDONLY(inode). * mnt_want/drop_write() will _keep_ the filesystem * r/w. */ int __mnt_is_readonly(struct vfsmount *mnt) { if (mnt->mnt_flags & MNT_READONLY) return 1; if (mnt->mnt_sb->s_flags & MS_RDONLY) return 1; return 0; } EXPORT_SYMBOL_GPL(__mnt_is_readonly); static inline void mnt_inc_writers(struct mount *mnt) { #ifdef CONFIG_SMP this_cpu_inc(mnt->mnt_pcp->mnt_writers); #else mnt->mnt_writers++; #endif } static inline void mnt_dec_writers(struct mount *mnt) { #ifdef CONFIG_SMP this_cpu_dec(mnt->mnt_pcp->mnt_writers); #else mnt->mnt_writers--; #endif } static unsigned int mnt_get_writers(struct mount *mnt) { #ifdef CONFIG_SMP unsigned int count = 0; int cpu; for_each_possible_cpu(cpu) { count += per_cpu_ptr(mnt->mnt_pcp, cpu)->mnt_writers; } return count; #else return mnt->mnt_writers; #endif } static int mnt_is_readonly(struct vfsmount *mnt) { if (mnt->mnt_sb->s_readonly_remount) return 1; /* Order wrt setting s_flags/s_readonly_remount in do_remount() */ smp_rmb(); return __mnt_is_readonly(mnt); } /* * Most r/o & frozen checks on a fs are for operations that take discrete * amounts of time, like a write() or unlink(). We must keep track of when * those operations start (for permission checks) and when they end, so that we * can determine when writes are able to occur to a filesystem. */ /** * __mnt_want_write - get write access to a mount without freeze protection * @m: the mount on which to take a write * * This tells the low-level filesystem that a write is about to be performed to * it, and makes sure that writes are allowed (mnt it read-write) before * returning success. This operation does not protect against filesystem being * frozen. When the write operation is finished, __mnt_drop_write() must be * called. This is effectively a refcount. */ int __mnt_want_write(struct vfsmount *m) { struct mount *mnt = real_mount(m); int ret = 0; preempt_disable(); mnt_inc_writers(mnt); /* * The store to mnt_inc_writers must be visible before we pass * MNT_WRITE_HOLD loop below, so that the slowpath can see our * incremented count after it has set MNT_WRITE_HOLD. */ smp_mb(); while (ACCESS_ONCE(mnt->mnt.mnt_flags) & MNT_WRITE_HOLD) cpu_relax(); /* * After the slowpath clears MNT_WRITE_HOLD, mnt_is_readonly will * be set to match its requirements. So we must not load that until * MNT_WRITE_HOLD is cleared. */ smp_rmb(); if (mnt_is_readonly(m)) { mnt_dec_writers(mnt); ret = -EROFS; } preempt_enable(); return ret; } /** * mnt_want_write - get write access to a mount * @m: the mount on which to take a write * * This tells the low-level filesystem that a write is about to be performed to * it, and makes sure that writes are allowed (mount is read-write, filesystem * is not frozen) before returning success. When the write operation is * finished, mnt_drop_write() must be called. This is effectively a refcount. */ int mnt_want_write(struct vfsmount *m) { int ret; sb_start_write(m->mnt_sb); ret = __mnt_want_write(m); if (ret) sb_end_write(m->mnt_sb); return ret; } EXPORT_SYMBOL_GPL(mnt_want_write); /** * mnt_clone_write - get write access to a mount * @mnt: the mount on which to take a write * * This is effectively like mnt_want_write, except * it must only be used to take an extra write reference * on a mountpoint that we already know has a write reference * on it. This allows some optimisation. * * After finished, mnt_drop_write must be called as usual to * drop the reference. */ int mnt_clone_write(struct vfsmount *mnt) { /* superblock may be r/o */ if (__mnt_is_readonly(mnt)) return -EROFS; preempt_disable(); mnt_inc_writers(real_mount(mnt)); preempt_enable(); return 0; } EXPORT_SYMBOL_GPL(mnt_clone_write); /** * __mnt_want_write_file - get write access to a file's mount * @file: the file who's mount on which to take a write * * This is like __mnt_want_write, but it takes a file and can * do some optimisations if the file is open for write already */ int __mnt_want_write_file(struct file *file) { if (!(file->f_mode & FMODE_WRITER)) return __mnt_want_write(file->f_path.mnt); else return mnt_clone_write(file->f_path.mnt); } /** * mnt_want_write_file - get write access to a file's mount * @file: the file who's mount on which to take a write * * This is like mnt_want_write, but it takes a file and can * do some optimisations if the file is open for write already */ int mnt_want_write_file(struct file *file) { int ret; sb_start_write(file->f_path.mnt->mnt_sb); ret = __mnt_want_write_file(file); if (ret) sb_end_write(file->f_path.mnt->mnt_sb); return ret; } EXPORT_SYMBOL_GPL(mnt_want_write_file); /** * __mnt_drop_write - give up write access to a mount * @mnt: the mount on which to give up write access * * Tells the low-level filesystem that we are done * performing writes to it. Must be matched with * __mnt_want_write() call above. */ void __mnt_drop_write(struct vfsmount *mnt) { preempt_disable(); mnt_dec_writers(real_mount(mnt)); preempt_enable(); } /** * mnt_drop_write - give up write access to a mount * @mnt: the mount on which to give up write access * * Tells the low-level filesystem that we are done performing writes to it and * also allows filesystem to be frozen again. Must be matched with * mnt_want_write() call above. */ void mnt_drop_write(struct vfsmount *mnt) { __mnt_drop_write(mnt); sb_end_write(mnt->mnt_sb); } EXPORT_SYMBOL_GPL(mnt_drop_write); void __mnt_drop_write_file(struct file *file) { __mnt_drop_write(file->f_path.mnt); } void mnt_drop_write_file(struct file *file) { mnt_drop_write(file->f_path.mnt); } EXPORT_SYMBOL(mnt_drop_write_file); static int mnt_make_readonly(struct mount *mnt) { int ret = 0; lock_mount_hash(); mnt->mnt.mnt_flags |= MNT_WRITE_HOLD; /* * After storing MNT_WRITE_HOLD, we'll read the counters. This store * should be visible before we do. */ smp_mb(); /* * With writers on hold, if this value is zero, then there are * definitely no active writers (although held writers may subsequently * increment the count, they'll have to wait, and decrement it after * seeing MNT_READONLY). * * It is OK to have counter incremented on one CPU and decremented on * another: the sum will add up correctly. The danger would be when we * sum up each counter, if we read a counter before it is incremented, * but then read another CPU's count which it has been subsequently * decremented from -- we would see more decrements than we should. * MNT_WRITE_HOLD protects against this scenario, because * mnt_want_write first increments count, then smp_mb, then spins on * MNT_WRITE_HOLD, so it can't be decremented by another CPU while * we're counting up here. */ if (mnt_get_writers(mnt) > 0) ret = -EBUSY; else mnt->mnt.mnt_flags |= MNT_READONLY; /* * MNT_READONLY must become visible before ~MNT_WRITE_HOLD, so writers * that become unheld will see MNT_READONLY. */ smp_wmb(); mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD; unlock_mount_hash(); return ret; } static void __mnt_unmake_readonly(struct mount *mnt) { lock_mount_hash(); mnt->mnt.mnt_flags &= ~MNT_READONLY; unlock_mount_hash(); } int sb_prepare_remount_readonly(struct super_block *sb) { struct mount *mnt; int err = 0; /* Racy optimization. Recheck the counter under MNT_WRITE_HOLD */ if (atomic_long_read(&sb->s_remove_count)) return -EBUSY; lock_mount_hash(); list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) { if (!(mnt->mnt.mnt_flags & MNT_READONLY)) { mnt->mnt.mnt_flags |= MNT_WRITE_HOLD; smp_mb(); if (mnt_get_writers(mnt) > 0) { err = -EBUSY; break; } } } if (!err && atomic_long_read(&sb->s_remove_count)) err = -EBUSY; if (!err) { sb->s_readonly_remount = 1; smp_wmb(); } list_for_each_entry(mnt, &sb->s_mounts, mnt_instance) { if (mnt->mnt.mnt_flags & MNT_WRITE_HOLD) mnt->mnt.mnt_flags &= ~MNT_WRITE_HOLD; } unlock_mount_hash(); return err; } static void free_vfsmnt(struct mount *mnt) { kfree_const(mnt->mnt_devname); #ifdef CONFIG_SMP free_percpu(mnt->mnt_pcp); #endif kmem_cache_free(mnt_cache, mnt); } static void delayed_free_vfsmnt(struct rcu_head *head) { free_vfsmnt(container_of(head, struct mount, mnt_rcu)); } /* call under rcu_read_lock */ bool legitimize_mnt(struct vfsmount *bastard, unsigned seq) { struct mount *mnt; if (read_seqretry(&mount_lock, seq)) return false; if (bastard == NULL) return true; mnt = real_mount(bastard); mnt_add_count(mnt, 1); if (likely(!read_seqretry(&mount_lock, seq))) return true; if (bastard->mnt_flags & MNT_SYNC_UMOUNT) { mnt_add_count(mnt, -1); return false; } rcu_read_unlock(); mntput(bastard); rcu_read_lock(); return false; } /* * find the first mount at @dentry on vfsmount @mnt. * call under rcu_read_lock() */ struct mount *__lookup_mnt(struct vfsmount *mnt, struct dentry *dentry) { struct hlist_head *head = m_hash(mnt, dentry); struct mount *p; hlist_for_each_entry_rcu(p, head, mnt_hash) if (&p->mnt_parent->mnt == mnt && p->mnt_mountpoint == dentry) return p; return NULL; } /* * find the last mount at @dentry on vfsmount @mnt. * mount_lock must be held. */ struct mount *__lookup_mnt_last(struct vfsmount *mnt, struct dentry *dentry) { struct mount *p, *res = NULL; p = __lookup_mnt(mnt, dentry); if (!p) goto out; if (!(p->mnt.mnt_flags & MNT_UMOUNT)) res = p; hlist_for_each_entry_continue(p, mnt_hash) { if (&p->mnt_parent->mnt != mnt || p->mnt_mountpoint != dentry) break; if (!(p->mnt.mnt_flags & MNT_UMOUNT)) res = p; } out: return res; } /* * lookup_mnt - Return the first child mount mounted at path * * "First" means first mounted chronologically. If you create the * following mounts: * * mount /dev/sda1 /mnt * mount /dev/sda2 /mnt * mount /dev/sda3 /mnt * * Then lookup_mnt() on the base /mnt dentry in the root mount will * return successively the root dentry and vfsmount of /dev/sda1, then * /dev/sda2, then /dev/sda3, then NULL. * * lookup_mnt takes a reference to the found vfsmount. */ struct vfsmount *lookup_mnt(struct path *path) { struct mount *child_mnt; struct vfsmount *m; unsigned seq; rcu_read_lock(); do { seq = read_seqbegin(&mount_lock); child_mnt = __lookup_mnt(path->mnt, path->dentry); m = child_mnt ? &child_mnt->mnt : NULL; } while (!legitimize_mnt(m, seq)); rcu_read_unlock(); return m; } /* * __is_local_mountpoint - Test to see if dentry is a mountpoint in the * current mount namespace. * * The common case is dentries are not mountpoints at all and that * test is handled inline. For the slow case when we are actually * dealing with a mountpoint of some kind, walk through all of the * mounts in the current mount namespace and test to see if the dentry * is a mountpoint. * * The mount_hashtable is not usable in the context because we * need to identify all mounts that may be in the current mount * namespace not just a mount that happens to have some specified * parent mount. */ bool __is_local_mountpoint(struct dentry *dentry) { struct mnt_namespace *ns = current->nsproxy->mnt_ns; struct mount *mnt; bool is_covered = false; if (!d_mountpoint(dentry)) goto out; down_read(&namespace_sem); list_for_each_entry(mnt, &ns->list, mnt_list) { is_covered = (mnt->mnt_mountpoint == dentry); if (is_covered) break; } up_read(&namespace_sem); out: return is_covered; } static struct mountpoint *lookup_mountpoint(struct dentry *dentry) { struct hlist_head *chain = mp_hash(dentry); struct mountpoint *mp; hlist_for_each_entry(mp, chain, m_hash) { if (mp->m_dentry == dentry) { /* might be worth a WARN_ON() */ if (d_unlinked(dentry)) return ERR_PTR(-ENOENT); mp->m_count++; return mp; } } return NULL; } static struct mountpoint *new_mountpoint(struct dentry *dentry) { struct hlist_head *chain = mp_hash(dentry); struct mountpoint *mp; int ret; mp = kmalloc(sizeof(struct mountpoint), GFP_KERNEL); if (!mp) return ERR_PTR(-ENOMEM); ret = d_set_mounted(dentry); if (ret) { kfree(mp); return ERR_PTR(ret); } mp->m_dentry = dentry; mp->m_count = 1; hlist_add_head(&mp->m_hash, chain); INIT_HLIST_HEAD(&mp->m_list); return mp; } static void put_mountpoint(struct mountpoint *mp) { if (!--mp->m_count) { struct dentry *dentry = mp->m_dentry; BUG_ON(!hlist_empty(&mp->m_list)); spin_lock(&dentry->d_lock); dentry->d_flags &= ~DCACHE_MOUNTED; spin_unlock(&dentry->d_lock); hlist_del(&mp->m_hash); kfree(mp); } } static inline int check_mnt(struct mount *mnt) { return mnt->mnt_ns == current->nsproxy->mnt_ns; } /* * vfsmount lock must be held for write */ static void touch_mnt_namespace(struct mnt_namespace *ns) { if (ns) { ns->event = ++event; wake_up_interruptible(&ns->poll); } } /* * vfsmount lock must be held for write */ static void __touch_mnt_namespace(struct mnt_namespace *ns) { if (ns && ns->event != event) { ns->event = event; wake_up_interruptible(&ns->poll); } } /* * vfsmount lock must be held for write */ static void unhash_mnt(struct mount *mnt) { mnt->mnt_parent = mnt; mnt->mnt_mountpoint = mnt->mnt.mnt_root; list_del_init(&mnt->mnt_child); hlist_del_init_rcu(&mnt->mnt_hash); hlist_del_init(&mnt->mnt_mp_list); put_mountpoint(mnt->mnt_mp); mnt->mnt_mp = NULL; } /* * vfsmount lock must be held for write */ static void detach_mnt(struct mount *mnt, struct path *old_path) { old_path->dentry = mnt->mnt_mountpoint; old_path->mnt = &mnt->mnt_parent->mnt; unhash_mnt(mnt); } /* * vfsmount lock must be held for write */ static void umount_mnt(struct mount *mnt) { /* old mountpoint will be dropped when we can do that */ mnt->mnt_ex_mountpoint = mnt->mnt_mountpoint; unhash_mnt(mnt); } /* * vfsmount lock must be held for write */ void mnt_set_mountpoint(struct mount *mnt, struct mountpoint *mp, struct mount *child_mnt) { mp->m_count++; mnt_add_count(mnt, 1); /* essentially, that's mntget */ child_mnt->mnt_mountpoint = dget(mp->m_dentry); child_mnt->mnt_parent = mnt; child_mnt->mnt_mp = mp; hlist_add_head(&child_mnt->mnt_mp_list, &mp->m_list); } /* * vfsmount lock must be held for write */ static void attach_mnt(struct mount *mnt, struct mount *parent, struct mountpoint *mp) { mnt_set_mountpoint(parent, mp, mnt); hlist_add_head_rcu(&mnt->mnt_hash, m_hash(&parent->mnt, mp->m_dentry)); list_add_tail(&mnt->mnt_child, &parent->mnt_mounts); } static void attach_shadowed(struct mount *mnt, struct mount *parent, struct mount *shadows) { if (shadows) { hlist_add_behind_rcu(&mnt->mnt_hash, &shadows->mnt_hash); list_add(&mnt->mnt_child, &shadows->mnt_child); } else { hlist_add_head_rcu(&mnt->mnt_hash, m_hash(&parent->mnt, mnt->mnt_mountpoint)); list_add_tail(&mnt->mnt_child, &parent->mnt_mounts); } } /* * vfsmount lock must be held for write */ static void commit_tree(struct mount *mnt, struct mount *shadows) { struct mount *parent = mnt->mnt_parent; struct mount *m; LIST_HEAD(head); struct mnt_namespace *n = parent->mnt_ns; BUG_ON(parent == mnt); list_add_tail(&head, &mnt->mnt_list); list_for_each_entry(m, &head, mnt_list) m->mnt_ns = n; list_splice(&head, n->list.prev); attach_shadowed(mnt, parent, shadows); touch_mnt_namespace(n); } static struct mount *next_mnt(struct mount *p, struct mount *root) { struct list_head *next = p->mnt_mounts.next; if (next == &p->mnt_mounts) { while (1) { if (p == root) return NULL; next = p->mnt_child.next; if (next != &p->mnt_parent->mnt_mounts) break; p = p->mnt_parent; } } return list_entry(next, struct mount, mnt_child); } static struct mount *skip_mnt_tree(struct mount *p) { struct list_head *prev = p->mnt_mounts.prev; while (prev != &p->mnt_mounts) { p = list_entry(prev, struct mount, mnt_child); prev = p->mnt_mounts.prev; } return p; } struct vfsmount * vfs_kern_mount(struct file_system_type *type, int flags, const char *name, void *data) { struct mount *mnt; struct dentry *root; if (!type) return ERR_PTR(-ENODEV); mnt = alloc_vfsmnt(name); if (!mnt) return ERR_PTR(-ENOMEM); if (flags & MS_KERNMOUNT) mnt->mnt.mnt_flags = MNT_INTERNAL; root = mount_fs(type, flags, name, data); if (IS_ERR(root)) { mnt_free_id(mnt); free_vfsmnt(mnt); return ERR_CAST(root); } mnt->mnt.mnt_root = root; mnt->mnt.mnt_sb = root->d_sb; mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; lock_mount_hash(); list_add_tail(&mnt->mnt_instance, &root->d_sb->s_mounts); unlock_mount_hash(); return &mnt->mnt; } EXPORT_SYMBOL_GPL(vfs_kern_mount); static struct mount *clone_mnt(struct mount *old, struct dentry *root, int flag) { struct super_block *sb = old->mnt.mnt_sb; struct mount *mnt; int err; mnt = alloc_vfsmnt(old->mnt_devname); if (!mnt) return ERR_PTR(-ENOMEM); if (flag & (CL_SLAVE | CL_PRIVATE | CL_SHARED_TO_SLAVE)) mnt->mnt_group_id = 0; /* not a peer of original */ else mnt->mnt_group_id = old->mnt_group_id; if ((flag & CL_MAKE_SHARED) && !mnt->mnt_group_id) { err = mnt_alloc_group_id(mnt); if (err) goto out_free; } mnt->mnt.mnt_flags = old->mnt.mnt_flags & ~(MNT_WRITE_HOLD|MNT_MARKED); /* Don't allow unprivileged users to change mount flags */ if (flag & CL_UNPRIVILEGED) { mnt->mnt.mnt_flags |= MNT_LOCK_ATIME; if (mnt->mnt.mnt_flags & MNT_READONLY) mnt->mnt.mnt_flags |= MNT_LOCK_READONLY; if (mnt->mnt.mnt_flags & MNT_NODEV) mnt->mnt.mnt_flags |= MNT_LOCK_NODEV; if (mnt->mnt.mnt_flags & MNT_NOSUID) mnt->mnt.mnt_flags |= MNT_LOCK_NOSUID; if (mnt->mnt.mnt_flags & MNT_NOEXEC) mnt->mnt.mnt_flags |= MNT_LOCK_NOEXEC; } /* Don't allow unprivileged users to reveal what is under a mount */ if ((flag & CL_UNPRIVILEGED) && (!(flag & CL_EXPIRE) || list_empty(&old->mnt_expire))) mnt->mnt.mnt_flags |= MNT_LOCKED; atomic_inc(&sb->s_active); mnt->mnt.mnt_sb = sb; mnt->mnt.mnt_root = dget(root); mnt->mnt_mountpoint = mnt->mnt.mnt_root; mnt->mnt_parent = mnt; lock_mount_hash(); list_add_tail(&mnt->mnt_instance, &sb->s_mounts); unlock_mount_hash(); if ((flag & CL_SLAVE) || ((flag & CL_SHARED_TO_SLAVE) && IS_MNT_SHARED(old))) { list_add(&mnt->mnt_slave, &old->mnt_slave_list); mnt->mnt_master = old; CLEAR_MNT_SHARED(mnt); } else if (!(flag & CL_PRIVATE)) { if ((flag & CL_MAKE_SHARED) || IS_MNT_SHARED(old)) list_add(&mnt->mnt_share, &old->mnt_share); if (IS_MNT_SLAVE(old)) list_add(&mnt->mnt_slave, &old->mnt_slave); mnt->mnt_master = old->mnt_master; } if (flag & CL_MAKE_SHARED) set_mnt_shared(mnt); /* stick the duplicate mount on the same expiry list * as the original if that was on one */ if (flag & CL_EXPIRE) { if (!list_empty(&old->mnt_expire)) list_add(&mnt->mnt_expire, &old->mnt_expire); } return mnt; out_free: mnt_free_id(mnt); free_vfsmnt(mnt); return ERR_PTR(err); } static void cleanup_mnt(struct mount *mnt) { /* * This probably indicates that somebody messed * up a mnt_want/drop_write() pair. If this * happens, the filesystem was probably unable * to make r/w->r/o transitions. */ /* * The locking used to deal with mnt_count decrement provides barriers, * so mnt_get_writers() below is safe. */ WARN_ON(mnt_get_writers(mnt)); if (unlikely(mnt->mnt_pins.first)) mnt_pin_kill(mnt); fsnotify_vfsmount_delete(&mnt->mnt); dput(mnt->mnt.mnt_root); deactivate_super(mnt->mnt.mnt_sb); mnt_free_id(mnt); call_rcu(&mnt->mnt_rcu, delayed_free_vfsmnt); } static void __cleanup_mnt(struct rcu_head *head) { cleanup_mnt(container_of(head, struct mount, mnt_rcu)); } static LLIST_HEAD(delayed_mntput_list); static void delayed_mntput(struct work_struct *unused) { struct llist_node *node = llist_del_all(&delayed_mntput_list); struct llist_node *next; for (; node; node = next) { next = llist_next(node); cleanup_mnt(llist_entry(node, struct mount, mnt_llist)); } } static DECLARE_DELAYED_WORK(delayed_mntput_work, delayed_mntput); static void mntput_no_expire(struct mount *mnt) { rcu_read_lock(); mnt_add_count(mnt, -1); if (likely(mnt->mnt_ns)) { /* shouldn't be the last one */ rcu_read_unlock(); return; } lock_mount_hash(); if (mnt_get_count(mnt)) { rcu_read_unlock(); unlock_mount_hash(); return; } if (unlikely(mnt->mnt.mnt_flags & MNT_DOOMED)) { rcu_read_unlock(); unlock_mount_hash(); return; } mnt->mnt.mnt_flags |= MNT_DOOMED; rcu_read_unlock(); list_del(&mnt->mnt_instance); if (unlikely(!list_empty(&mnt->mnt_mounts))) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { umount_mnt(p); } } unlock_mount_hash(); if (likely(!(mnt->mnt.mnt_flags & MNT_INTERNAL))) { struct task_struct *task = current; if (likely(!(task->flags & PF_KTHREAD))) { init_task_work(&mnt->mnt_rcu, __cleanup_mnt); if (!task_work_add(task, &mnt->mnt_rcu, true)) return; } if (llist_add(&mnt->mnt_llist, &delayed_mntput_list)) schedule_delayed_work(&delayed_mntput_work, 1); return; } cleanup_mnt(mnt); } void mntput(struct vfsmount *mnt) { if (mnt) { struct mount *m = real_mount(mnt); /* avoid cacheline pingpong, hope gcc doesn't get "smart" */ if (unlikely(m->mnt_expiry_mark)) m->mnt_expiry_mark = 0; mntput_no_expire(m); } } EXPORT_SYMBOL(mntput); struct vfsmount *mntget(struct vfsmount *mnt) { if (mnt) mnt_add_count(real_mount(mnt), 1); return mnt; } EXPORT_SYMBOL(mntget); struct vfsmount *mnt_clone_internal(struct path *path) { struct mount *p; p = clone_mnt(real_mount(path->mnt), path->dentry, CL_PRIVATE); if (IS_ERR(p)) return ERR_CAST(p); p->mnt.mnt_flags |= MNT_INTERNAL; return &p->mnt; } static inline void mangle(struct seq_file *m, const char *s) { seq_escape(m, s, " \t\n\\"); } /* * Simple .show_options callback for filesystems which don't want to * implement more complex mount option showing. * * See also save_mount_options(). */ int generic_show_options(struct seq_file *m, struct dentry *root) { const char *options; rcu_read_lock(); options = rcu_dereference(root->d_sb->s_options); if (options != NULL && options[0]) { seq_putc(m, ','); mangle(m, options); } rcu_read_unlock(); return 0; } EXPORT_SYMBOL(generic_show_options); /* * If filesystem uses generic_show_options(), this function should be * called from the fill_super() callback. * * The .remount_fs callback usually needs to be handled in a special * way, to make sure, that previous options are not overwritten if the * remount fails. * * Also note, that if the filesystem's .remount_fs function doesn't * reset all options to their default value, but changes only newly * given options, then the displayed options will not reflect reality * any more. */ void save_mount_options(struct super_block *sb, char *options) { BUG_ON(sb->s_options); rcu_assign_pointer(sb->s_options, kstrdup(options, GFP_KERNEL)); } EXPORT_SYMBOL(save_mount_options); void replace_mount_options(struct super_block *sb, char *options) { char *old = sb->s_options; rcu_assign_pointer(sb->s_options, options); if (old) { synchronize_rcu(); kfree(old); } } EXPORT_SYMBOL(replace_mount_options); #ifdef CONFIG_PROC_FS /* iterator; we want it to have access to namespace_sem, thus here... */ static void *m_start(struct seq_file *m, loff_t *pos) { struct proc_mounts *p = proc_mounts(m); down_read(&namespace_sem); if (p->cached_event == p->ns->event) { void *v = p->cached_mount; if (*pos == p->cached_index) return v; if (*pos == p->cached_index + 1) { v = seq_list_next(v, &p->ns->list, &p->cached_index); return p->cached_mount = v; } } p->cached_event = p->ns->event; p->cached_mount = seq_list_start(&p->ns->list, *pos); p->cached_index = *pos; return p->cached_mount; } static void *m_next(struct seq_file *m, void *v, loff_t *pos) { struct proc_mounts *p = proc_mounts(m); p->cached_mount = seq_list_next(v, &p->ns->list, pos); p->cached_index = *pos; return p->cached_mount; } static void m_stop(struct seq_file *m, void *v) { up_read(&namespace_sem); } static int m_show(struct seq_file *m, void *v) { struct proc_mounts *p = proc_mounts(m); struct mount *r = list_entry(v, struct mount, mnt_list); return p->show(m, &r->mnt); } const struct seq_operations mounts_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = m_show, }; #endif /* CONFIG_PROC_FS */ /** * may_umount_tree - check if a mount tree is busy * @mnt: root of mount tree * * This is called to check if a tree of mounts has any * open files, pwds, chroots or sub mounts that are * busy. */ int may_umount_tree(struct vfsmount *m) { struct mount *mnt = real_mount(m); int actual_refs = 0; int minimum_refs = 0; struct mount *p; BUG_ON(!m); /* write lock needed for mnt_get_count */ lock_mount_hash(); for (p = mnt; p; p = next_mnt(p, mnt)) { actual_refs += mnt_get_count(p); minimum_refs += 2; } unlock_mount_hash(); if (actual_refs > minimum_refs) return 0; return 1; } EXPORT_SYMBOL(may_umount_tree); /** * may_umount - check if a mount point is busy * @mnt: root of mount * * This is called to check if a mount point has any * open files, pwds, chroots or sub mounts. If the * mount has sub mounts this will return busy * regardless of whether the sub mounts are busy. * * Doesn't take quota and stuff into account. IOW, in some cases it will * give false negatives. The main reason why it's here is that we need * a non-destructive way to look for easily umountable filesystems. */ int may_umount(struct vfsmount *mnt) { int ret = 1; down_read(&namespace_sem); lock_mount_hash(); if (propagate_mount_busy(real_mount(mnt), 2)) ret = 0; unlock_mount_hash(); up_read(&namespace_sem); return ret; } EXPORT_SYMBOL(may_umount); static HLIST_HEAD(unmounted); /* protected by namespace_sem */ static void namespace_unlock(void) { struct hlist_head head; hlist_move_list(&unmounted, &head); up_write(&namespace_sem); if (likely(hlist_empty(&head))) return; synchronize_rcu(); group_pin_kill(&head); } static inline void namespace_lock(void) { down_write(&namespace_sem); } enum umount_tree_flags { UMOUNT_SYNC = 1, UMOUNT_PROPAGATE = 2, }; /* * mount_lock must be held * namespace_sem must be held for write */ static void umount_tree(struct mount *mnt, enum umount_tree_flags how) { LIST_HEAD(tmp_list); struct mount *p; if (how & UMOUNT_PROPAGATE) propagate_mount_unlock(mnt); /* Gather the mounts to umount */ for (p = mnt; p; p = next_mnt(p, mnt)) { p->mnt.mnt_flags |= MNT_UMOUNT; list_move(&p->mnt_list, &tmp_list); } /* Hide the mounts from mnt_mounts */ list_for_each_entry(p, &tmp_list, mnt_list) { list_del_init(&p->mnt_child); } /* Add propogated mounts to the tmp_list */ if (how & UMOUNT_PROPAGATE) propagate_umount(&tmp_list); while (!list_empty(&tmp_list)) { bool disconnect; p = list_first_entry(&tmp_list, struct mount, mnt_list); list_del_init(&p->mnt_expire); list_del_init(&p->mnt_list); __touch_mnt_namespace(p->mnt_ns); p->mnt_ns = NULL; if (how & UMOUNT_SYNC) p->mnt.mnt_flags |= MNT_SYNC_UMOUNT; disconnect = !IS_MNT_LOCKED_AND_LAZY(p); pin_insert_group(&p->mnt_umount, &p->mnt_parent->mnt, disconnect ? &unmounted : NULL); if (mnt_has_parent(p)) { mnt_add_count(p->mnt_parent, -1); if (!disconnect) { /* Don't forget about p */ list_add_tail(&p->mnt_child, &p->mnt_parent->mnt_mounts); } else { umount_mnt(p); } } change_mnt_propagation(p, MS_PRIVATE); } } static void shrink_submounts(struct mount *mnt); static int do_umount(struct mount *mnt, int flags) { struct super_block *sb = mnt->mnt.mnt_sb; int retval; retval = security_sb_umount(&mnt->mnt, flags); if (retval) return retval; /* * Allow userspace to request a mountpoint be expired rather than * unmounting unconditionally. Unmount only happens if: * (1) the mark is already set (the mark is cleared by mntput()) * (2) the usage count == 1 [parent vfsmount] + 1 [sys_umount] */ if (flags & MNT_EXPIRE) { if (&mnt->mnt == current->fs->root.mnt || flags & (MNT_FORCE | MNT_DETACH)) return -EINVAL; /* * probably don't strictly need the lock here if we examined * all race cases, but it's a slowpath. */ lock_mount_hash(); if (mnt_get_count(mnt) != 2) { unlock_mount_hash(); return -EBUSY; } unlock_mount_hash(); if (!xchg(&mnt->mnt_expiry_mark, 1)) return -EAGAIN; } /* * If we may have to abort operations to get out of this * mount, and they will themselves hold resources we must * allow the fs to do things. In the Unix tradition of * 'Gee thats tricky lets do it in userspace' the umount_begin * might fail to complete on the first run through as other tasks * must return, and the like. Thats for the mount program to worry * about for the moment. */ if (flags & MNT_FORCE && sb->s_op->umount_begin) { sb->s_op->umount_begin(sb); } /* * No sense to grab the lock for this test, but test itself looks * somewhat bogus. Suggestions for better replacement? * Ho-hum... In principle, we might treat that as umount + switch * to rootfs. GC would eventually take care of the old vfsmount. * Actually it makes sense, especially if rootfs would contain a * /reboot - static binary that would close all descriptors and * call reboot(9). Then init(8) could umount root and exec /reboot. */ if (&mnt->mnt == current->fs->root.mnt && !(flags & MNT_DETACH)) { /* * Special case for "unmounting" root ... * we just try to remount it readonly. */ if (!capable(CAP_SYS_ADMIN)) return -EPERM; down_write(&sb->s_umount); if (!(sb->s_flags & MS_RDONLY)) retval = do_remount_sb(sb, MS_RDONLY, NULL, 0); up_write(&sb->s_umount); return retval; } namespace_lock(); lock_mount_hash(); event++; if (flags & MNT_DETACH) { if (!list_empty(&mnt->mnt_list)) umount_tree(mnt, UMOUNT_PROPAGATE); retval = 0; } else { shrink_submounts(mnt); retval = -EBUSY; if (!propagate_mount_busy(mnt, 2)) { if (!list_empty(&mnt->mnt_list)) umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC); retval = 0; } } unlock_mount_hash(); namespace_unlock(); return retval; } /* * __detach_mounts - lazily unmount all mounts on the specified dentry * * During unlink, rmdir, and d_drop it is possible to loose the path * to an existing mountpoint, and wind up leaking the mount. * detach_mounts allows lazily unmounting those mounts instead of * leaking them. * * The caller may hold dentry->d_inode->i_mutex. */ void __detach_mounts(struct dentry *dentry) { struct mountpoint *mp; struct mount *mnt; namespace_lock(); mp = lookup_mountpoint(dentry); if (IS_ERR_OR_NULL(mp)) goto out_unlock; lock_mount_hash(); while (!hlist_empty(&mp->m_list)) { mnt = hlist_entry(mp->m_list.first, struct mount, mnt_mp_list); if (mnt->mnt.mnt_flags & MNT_UMOUNT) { struct mount *p, *tmp; list_for_each_entry_safe(p, tmp, &mnt->mnt_mounts, mnt_child) { hlist_add_head(&p->mnt_umount.s_list, &unmounted); umount_mnt(p); } } else umount_tree(mnt, 0); } unlock_mount_hash(); put_mountpoint(mp); out_unlock: namespace_unlock(); } /* * Is the caller allowed to modify his namespace? */ static inline bool may_mount(void) { return ns_capable(current->nsproxy->mnt_ns->user_ns, CAP_SYS_ADMIN); } /* * Now umount can handle mount points as well as block devices. * This is important for filesystems which use unnamed block devices. * * We now support a flag for forced unmount like the other 'big iron' * unixes. Our API is identical to OSF/1 to avoid making a mess of AMD */ SYSCALL_DEFINE2(umount, char __user *, name, int, flags) { struct path path; struct mount *mnt; int retval; int lookup_flags = 0; if (flags & ~(MNT_FORCE | MNT_DETACH | MNT_EXPIRE | UMOUNT_NOFOLLOW)) return -EINVAL; if (!may_mount()) return -EPERM; if (!(flags & UMOUNT_NOFOLLOW)) lookup_flags |= LOOKUP_FOLLOW; retval = user_path_mountpoint_at(AT_FDCWD, name, lookup_flags, &path); if (retval) goto out; mnt = real_mount(path.mnt); retval = -EINVAL; if (path.dentry != path.mnt->mnt_root) goto dput_and_out; if (!check_mnt(mnt)) goto dput_and_out; if (mnt->mnt.mnt_flags & MNT_LOCKED) goto dput_and_out; retval = -EPERM; if (flags & MNT_FORCE && !capable(CAP_SYS_ADMIN)) goto dput_and_out; retval = do_umount(mnt, flags); dput_and_out: /* we mustn't call path_put() as that would clear mnt_expiry_mark */ dput(path.dentry); mntput_no_expire(mnt); out: return retval; } #ifdef __ARCH_WANT_SYS_OLDUMOUNT /* * The 2.0 compatible umount. No flags. */ SYSCALL_DEFINE1(oldumount, char __user *, name) { return sys_umount(name, 0); } #endif static bool is_mnt_ns_file(struct dentry *dentry) { /* Is this a proxy for a mount namespace? */ return dentry->d_op == &ns_dentry_operations && dentry->d_fsdata == &mntns_operations; } struct mnt_namespace *to_mnt_ns(struct ns_common *ns) { return container_of(ns, struct mnt_namespace, ns); } static bool mnt_ns_loop(struct dentry *dentry) { /* Could bind mounting the mount namespace inode cause a * mount namespace loop? */ struct mnt_namespace *mnt_ns; if (!is_mnt_ns_file(dentry)) return false; mnt_ns = to_mnt_ns(get_proc_ns(dentry->d_inode)); return current->nsproxy->mnt_ns->seq >= mnt_ns->seq; } struct mount *copy_tree(struct mount *mnt, struct dentry *dentry, int flag) { struct mount *res, *p, *q, *r, *parent; if (!(flag & CL_COPY_UNBINDABLE) && IS_MNT_UNBINDABLE(mnt)) return ERR_PTR(-EINVAL); if (!(flag & CL_COPY_MNT_NS_FILE) && is_mnt_ns_file(dentry)) return ERR_PTR(-EINVAL); res = q = clone_mnt(mnt, dentry, flag); if (IS_ERR(q)) return q; q->mnt_mountpoint = mnt->mnt_mountpoint; p = mnt; list_for_each_entry(r, &mnt->mnt_mounts, mnt_child) { struct mount *s; if (!is_subdir(r->mnt_mountpoint, dentry)) continue; for (s = r; s; s = next_mnt(s, r)) { struct mount *t = NULL; if (!(flag & CL_COPY_UNBINDABLE) && IS_MNT_UNBINDABLE(s)) { s = skip_mnt_tree(s); continue; } if (!(flag & CL_COPY_MNT_NS_FILE) && is_mnt_ns_file(s->mnt.mnt_root)) { s = skip_mnt_tree(s); continue; } while (p != s->mnt_parent) { p = p->mnt_parent; q = q->mnt_parent; } p = s; parent = q; q = clone_mnt(p, p->mnt.mnt_root, flag); if (IS_ERR(q)) goto out; lock_mount_hash(); list_add_tail(&q->mnt_list, &res->mnt_list); mnt_set_mountpoint(parent, p->mnt_mp, q); if (!list_empty(&parent->mnt_mounts)) { t = list_last_entry(&parent->mnt_mounts, struct mount, mnt_child); if (t->mnt_mp != p->mnt_mp) t = NULL; } attach_shadowed(q, parent, t); unlock_mount_hash(); } } return res; out: if (res) { lock_mount_hash(); umount_tree(res, UMOUNT_SYNC); unlock_mount_hash(); } return q; } /* Caller should check returned pointer for errors */ struct vfsmount *collect_mounts(struct path *path) { struct mount *tree; namespace_lock(); if (!check_mnt(real_mount(path->mnt))) tree = ERR_PTR(-EINVAL); else tree = copy_tree(real_mount(path->mnt), path->dentry, CL_COPY_ALL | CL_PRIVATE); namespace_unlock(); if (IS_ERR(tree)) return ERR_CAST(tree); return &tree->mnt; } void drop_collected_mounts(struct vfsmount *mnt) { namespace_lock(); lock_mount_hash(); umount_tree(real_mount(mnt), UMOUNT_SYNC); unlock_mount_hash(); namespace_unlock(); } /** * clone_private_mount - create a private clone of a path * * This creates a new vfsmount, which will be the clone of @path. The new will * not be attached anywhere in the namespace and will be private (i.e. changes * to the originating mount won't be propagated into this). * * Release with mntput(). */ struct vfsmount *clone_private_mount(struct path *path) { struct mount *old_mnt = real_mount(path->mnt); struct mount *new_mnt; if (IS_MNT_UNBINDABLE(old_mnt)) return ERR_PTR(-EINVAL); down_read(&namespace_sem); new_mnt = clone_mnt(old_mnt, path->dentry, CL_PRIVATE); up_read(&namespace_sem); if (IS_ERR(new_mnt)) return ERR_CAST(new_mnt); return &new_mnt->mnt; } EXPORT_SYMBOL_GPL(clone_private_mount); int iterate_mounts(int (*f)(struct vfsmount *, void *), void *arg, struct vfsmount *root) { struct mount *mnt; int res = f(root, arg); if (res) return res; list_for_each_entry(mnt, &real_mount(root)->mnt_list, mnt_list) { res = f(&mnt->mnt, arg); if (res) return res; } return 0; } static void cleanup_group_ids(struct mount *mnt, struct mount *end) { struct mount *p; for (p = mnt; p != end; p = next_mnt(p, mnt)) { if (p->mnt_group_id && !IS_MNT_SHARED(p)) mnt_release_group_id(p); } } static int invent_group_ids(struct mount *mnt, bool recurse) { struct mount *p; for (p = mnt; p; p = recurse ? next_mnt(p, mnt) : NULL) { if (!p->mnt_group_id && !IS_MNT_SHARED(p)) { int err = mnt_alloc_group_id(p); if (err) { cleanup_group_ids(mnt, p); return err; } } } return 0; } /* * @source_mnt : mount tree to be attached * @nd : place the mount tree @source_mnt is attached * @parent_nd : if non-null, detach the source_mnt from its parent and * store the parent mount and mountpoint dentry. * (done when source_mnt is moved) * * NOTE: in the table below explains the semantics when a source mount * of a given type is attached to a destination mount of a given type. * --------------------------------------------------------------------------- * | BIND MOUNT OPERATION | * |************************************************************************** * | source-->| shared | private | slave | unbindable | * | dest | | | | | * | | | | | | | * | v | | | | | * |************************************************************************** * | shared | shared (++) | shared (+) | shared(+++)| invalid | * | | | | | | * |non-shared| shared (+) | private | slave (*) | invalid | * *************************************************************************** * A bind operation clones the source mount and mounts the clone on the * destination mount. * * (++) the cloned mount is propagated to all the mounts in the propagation * tree of the destination mount and the cloned mount is added to * the peer group of the source mount. * (+) the cloned mount is created under the destination mount and is marked * as shared. The cloned mount is added to the peer group of the source * mount. * (+++) the mount is propagated to all the mounts in the propagation tree * of the destination mount and the cloned mount is made slave * of the same master as that of the source mount. The cloned mount * is marked as 'shared and slave'. * (*) the cloned mount is made a slave of the same master as that of the * source mount. * * --------------------------------------------------------------------------- * | MOVE MOUNT OPERATION | * |************************************************************************** * | source-->| shared | private | slave | unbindable | * | dest | | | | | * | | | | | | | * | v | | | | | * |************************************************************************** * | shared | shared (+) | shared (+) | shared(+++) | invalid | * | | | | | | * |non-shared| shared (+*) | private | slave (*) | unbindable | * *************************************************************************** * * (+) the mount is moved to the destination. And is then propagated to * all the mounts in the propagation tree of the destination mount. * (+*) the mount is moved to the destination. * (+++) the mount is moved to the destination and is then propagated to * all the mounts belonging to the destination mount's propagation tree. * the mount is marked as 'shared and slave'. * (*) the mount continues to be a slave at the new location. * * if the source mount is a tree, the operations explained above is * applied to each mount in the tree. * Must be called without spinlocks held, since this function can sleep * in allocations. */ static int attach_recursive_mnt(struct mount *source_mnt, struct mount *dest_mnt, struct mountpoint *dest_mp, struct path *parent_path) { HLIST_HEAD(tree_list); struct mount *child, *p; struct hlist_node *n; int err; if (IS_MNT_SHARED(dest_mnt)) { err = invent_group_ids(source_mnt, true); if (err) goto out; err = propagate_mnt(dest_mnt, dest_mp, source_mnt, &tree_list); lock_mount_hash(); if (err) goto out_cleanup_ids; for (p = source_mnt; p; p = next_mnt(p, source_mnt)) set_mnt_shared(p); } else { lock_mount_hash(); } if (parent_path) { detach_mnt(source_mnt, parent_path); attach_mnt(source_mnt, dest_mnt, dest_mp); touch_mnt_namespace(source_mnt->mnt_ns); } else { mnt_set_mountpoint(dest_mnt, dest_mp, source_mnt); commit_tree(source_mnt, NULL); } hlist_for_each_entry_safe(child, n, &tree_list, mnt_hash) { struct mount *q; hlist_del_init(&child->mnt_hash); q = __lookup_mnt_last(&child->mnt_parent->mnt, child->mnt_mountpoint); commit_tree(child, q); } unlock_mount_hash(); return 0; out_cleanup_ids: while (!hlist_empty(&tree_list)) { child = hlist_entry(tree_list.first, struct mount, mnt_hash); umount_tree(child, UMOUNT_SYNC); } unlock_mount_hash(); cleanup_group_ids(source_mnt, NULL); out: return err; } static struct mountpoint *lock_mount(struct path *path) { struct vfsmount *mnt; struct dentry *dentry = path->dentry; retry: mutex_lock(&dentry->d_inode->i_mutex); if (unlikely(cant_mount(dentry))) { mutex_unlock(&dentry->d_inode->i_mutex); return ERR_PTR(-ENOENT); } namespace_lock(); mnt = lookup_mnt(path); if (likely(!mnt)) { struct mountpoint *mp = lookup_mountpoint(dentry); if (!mp) mp = new_mountpoint(dentry); if (IS_ERR(mp)) { namespace_unlock(); mutex_unlock(&dentry->d_inode->i_mutex); return mp; } return mp; } namespace_unlock(); mutex_unlock(&path->dentry->d_inode->i_mutex); path_put(path); path->mnt = mnt; dentry = path->dentry = dget(mnt->mnt_root); goto retry; } static void unlock_mount(struct mountpoint *where) { struct dentry *dentry = where->m_dentry; put_mountpoint(where); namespace_unlock(); mutex_unlock(&dentry->d_inode->i_mutex); } static int graft_tree(struct mount *mnt, struct mount *p, struct mountpoint *mp) { if (mnt->mnt.mnt_sb->s_flags & MS_NOUSER) return -EINVAL; if (d_is_dir(mp->m_dentry) != d_is_dir(mnt->mnt.mnt_root)) return -ENOTDIR; return attach_recursive_mnt(mnt, p, mp, NULL); } /* * Sanity check the flags to change_mnt_propagation. */ static int flags_to_propagation_type(int flags) { int type = flags & ~(MS_REC | MS_SILENT); /* Fail if any non-propagation flags are set */ if (type & ~(MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)) return 0; /* Only one propagation flag should be set */ if (!is_power_of_2(type)) return 0; return type; } /* * recursively change the type of the mountpoint. */ static int do_change_type(struct path *path, int flag) { struct mount *m; struct mount *mnt = real_mount(path->mnt); int recurse = flag & MS_REC; int type; int err = 0; if (path->dentry != path->mnt->mnt_root) return -EINVAL; type = flags_to_propagation_type(flag); if (!type) return -EINVAL; namespace_lock(); if (type == MS_SHARED) { err = invent_group_ids(mnt, recurse); if (err) goto out_unlock; } lock_mount_hash(); for (m = mnt; m; m = (recurse ? next_mnt(m, mnt) : NULL)) change_mnt_propagation(m, type); unlock_mount_hash(); out_unlock: namespace_unlock(); return err; } static bool has_locked_children(struct mount *mnt, struct dentry *dentry) { struct mount *child; list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) { if (!is_subdir(child->mnt_mountpoint, dentry)) continue; if (child->mnt.mnt_flags & MNT_LOCKED) return true; } return false; } /* * do loopback mount. */ static int do_loopback(struct path *path, const char *old_name, int recurse) { struct path old_path; struct mount *mnt = NULL, *old, *parent; struct mountpoint *mp; int err; if (!old_name || !*old_name) return -EINVAL; err = kern_path(old_name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &old_path); if (err) return err; err = -EINVAL; if (mnt_ns_loop(old_path.dentry)) goto out; mp = lock_mount(path); err = PTR_ERR(mp); if (IS_ERR(mp)) goto out; old = real_mount(old_path.mnt); parent = real_mount(path->mnt); err = -EINVAL; if (IS_MNT_UNBINDABLE(old)) goto out2; if (!check_mnt(parent)) goto out2; if (!check_mnt(old) && old_path.dentry->d_op != &ns_dentry_operations) goto out2; if (!recurse && has_locked_children(old, old_path.dentry)) goto out2; if (recurse) mnt = copy_tree(old, old_path.dentry, CL_COPY_MNT_NS_FILE); else mnt = clone_mnt(old, old_path.dentry, 0); if (IS_ERR(mnt)) { err = PTR_ERR(mnt); goto out2; } mnt->mnt.mnt_flags &= ~MNT_LOCKED; err = graft_tree(mnt, parent, mp); if (err) { lock_mount_hash(); umount_tree(mnt, UMOUNT_SYNC); unlock_mount_hash(); } out2: unlock_mount(mp); out: path_put(&old_path); return err; } static int change_mount_flags(struct vfsmount *mnt, int ms_flags) { int error = 0; int readonly_request = 0; if (ms_flags & MS_RDONLY) readonly_request = 1; if (readonly_request == __mnt_is_readonly(mnt)) return 0; if (readonly_request) error = mnt_make_readonly(real_mount(mnt)); else __mnt_unmake_readonly(real_mount(mnt)); return error; } /* * change filesystem flags. dir should be a physical root of filesystem. * If you've mounted a non-root directory somewhere and want to do remount * on it - tough luck. */ static int do_remount(struct path *path, int flags, int mnt_flags, void *data) { int err; struct super_block *sb = path->mnt->mnt_sb; struct mount *mnt = real_mount(path->mnt); if (!check_mnt(mnt)) return -EINVAL; if (path->dentry != path->mnt->mnt_root) return -EINVAL; /* Don't allow changing of locked mnt flags. * * No locks need to be held here while testing the various * MNT_LOCK flags because those flags can never be cleared * once they are set. */ if ((mnt->mnt.mnt_flags & MNT_LOCK_READONLY) && !(mnt_flags & MNT_READONLY)) { return -EPERM; } if ((mnt->mnt.mnt_flags & MNT_LOCK_NODEV) && !(mnt_flags & MNT_NODEV)) { /* Was the nodev implicitly added in mount? */ if ((mnt->mnt_ns->user_ns != &init_user_ns) && !(sb->s_type->fs_flags & FS_USERNS_DEV_MOUNT)) { mnt_flags |= MNT_NODEV; } else { return -EPERM; } } if ((mnt->mnt.mnt_flags & MNT_LOCK_NOSUID) && !(mnt_flags & MNT_NOSUID)) { return -EPERM; } if ((mnt->mnt.mnt_flags & MNT_LOCK_NOEXEC) && !(mnt_flags & MNT_NOEXEC)) { return -EPERM; } if ((mnt->mnt.mnt_flags & MNT_LOCK_ATIME) && ((mnt->mnt.mnt_flags & MNT_ATIME_MASK) != (mnt_flags & MNT_ATIME_MASK))) { return -EPERM; } err = security_sb_remount(sb, data); if (err) return err; down_write(&sb->s_umount); if (flags & MS_BIND) err = change_mount_flags(path->mnt, flags); else if (!capable(CAP_SYS_ADMIN)) err = -EPERM; else err = do_remount_sb(sb, flags, data, 0); if (!err) { lock_mount_hash(); mnt_flags |= mnt->mnt.mnt_flags & ~MNT_USER_SETTABLE_MASK; mnt->mnt.mnt_flags = mnt_flags; touch_mnt_namespace(mnt->mnt_ns); unlock_mount_hash(); } up_write(&sb->s_umount); return err; } static inline int tree_contains_unbindable(struct mount *mnt) { struct mount *p; for (p = mnt; p; p = next_mnt(p, mnt)) { if (IS_MNT_UNBINDABLE(p)) return 1; } return 0; } static int do_move_mount(struct path *path, const char *old_name) { struct path old_path, parent_path; struct mount *p; struct mount *old; struct mountpoint *mp; int err; if (!old_name || !*old_name) return -EINVAL; err = kern_path(old_name, LOOKUP_FOLLOW, &old_path); if (err) return err; mp = lock_mount(path); err = PTR_ERR(mp); if (IS_ERR(mp)) goto out; old = real_mount(old_path.mnt); p = real_mount(path->mnt); err = -EINVAL; if (!check_mnt(p) || !check_mnt(old)) goto out1; if (old->mnt.mnt_flags & MNT_LOCKED) goto out1; err = -EINVAL; if (old_path.dentry != old_path.mnt->mnt_root) goto out1; if (!mnt_has_parent(old)) goto out1; if (d_is_dir(path->dentry) != d_is_dir(old_path.dentry)) goto out1; /* * Don't move a mount residing in a shared parent. */ if (IS_MNT_SHARED(old->mnt_parent)) goto out1; /* * Don't move a mount tree containing unbindable mounts to a destination * mount which is shared. */ if (IS_MNT_SHARED(p) && tree_contains_unbindable(old)) goto out1; err = -ELOOP; for (; mnt_has_parent(p); p = p->mnt_parent) if (p == old) goto out1; err = attach_recursive_mnt(old, real_mount(path->mnt), mp, &parent_path); if (err) goto out1; /* if the mount is moved, it should no longer be expire * automatically */ list_del_init(&old->mnt_expire); out1: unlock_mount(mp); out: if (!err) path_put(&parent_path); path_put(&old_path); return err; } static struct vfsmount *fs_set_subtype(struct vfsmount *mnt, const char *fstype) { int err; const char *subtype = strchr(fstype, '.'); if (subtype) { subtype++; err = -EINVAL; if (!subtype[0]) goto err; } else subtype = ""; mnt->mnt_sb->s_subtype = kstrdup(subtype, GFP_KERNEL); err = -ENOMEM; if (!mnt->mnt_sb->s_subtype) goto err; return mnt; err: mntput(mnt); return ERR_PTR(err); } /* * add a mount into a namespace's mount tree */ static int do_add_mount(struct mount *newmnt, struct path *path, int mnt_flags) { struct mountpoint *mp; struct mount *parent; int err; mnt_flags &= ~MNT_INTERNAL_FLAGS; mp = lock_mount(path); if (IS_ERR(mp)) return PTR_ERR(mp); parent = real_mount(path->mnt); err = -EINVAL; if (unlikely(!check_mnt(parent))) { /* that's acceptable only for automounts done in private ns */ if (!(mnt_flags & MNT_SHRINKABLE)) goto unlock; /* ... and for those we'd better have mountpoint still alive */ if (!parent->mnt_ns) goto unlock; } /* Refuse the same filesystem on the same mount point */ err = -EBUSY; if (path->mnt->mnt_sb == newmnt->mnt.mnt_sb && path->mnt->mnt_root == path->dentry) goto unlock; err = -EINVAL; if (d_is_symlink(newmnt->mnt.mnt_root)) goto unlock; newmnt->mnt.mnt_flags = mnt_flags; err = graft_tree(newmnt, parent, mp); unlock: unlock_mount(mp); return err; } /* * create a new mount for userspace and request it to be added into the * namespace's tree */ static int do_new_mount(struct path *path, const char *fstype, int flags, int mnt_flags, const char *name, void *data) { struct file_system_type *type; struct user_namespace *user_ns = current->nsproxy->mnt_ns->user_ns; struct vfsmount *mnt; int err; if (!fstype) return -EINVAL; type = get_fs_type(fstype); if (!type) return -ENODEV; if (user_ns != &init_user_ns) { if (!(type->fs_flags & FS_USERNS_MOUNT)) { put_filesystem(type); return -EPERM; } /* Only in special cases allow devices from mounts * created outside the initial user namespace. */ if (!(type->fs_flags & FS_USERNS_DEV_MOUNT)) { flags |= MS_NODEV; mnt_flags |= MNT_NODEV | MNT_LOCK_NODEV; } } mnt = vfs_kern_mount(type, flags, name, data); if (!IS_ERR(mnt) && (type->fs_flags & FS_HAS_SUBTYPE) && !mnt->mnt_sb->s_subtype) mnt = fs_set_subtype(mnt, fstype); put_filesystem(type); if (IS_ERR(mnt)) return PTR_ERR(mnt); err = do_add_mount(real_mount(mnt), path, mnt_flags); if (err) mntput(mnt); return err; } int finish_automount(struct vfsmount *m, struct path *path) { struct mount *mnt = real_mount(m); int err; /* The new mount record should have at least 2 refs to prevent it being * expired before we get a chance to add it */ BUG_ON(mnt_get_count(mnt) < 2); if (m->mnt_sb == path->mnt->mnt_sb && m->mnt_root == path->dentry) { err = -ELOOP; goto fail; } err = do_add_mount(mnt, path, path->mnt->mnt_flags | MNT_SHRINKABLE); if (!err) return 0; fail: /* remove m from any expiration list it may be on */ if (!list_empty(&mnt->mnt_expire)) { namespace_lock(); list_del_init(&mnt->mnt_expire); namespace_unlock(); } mntput(m); mntput(m); return err; } /** * mnt_set_expiry - Put a mount on an expiration list * @mnt: The mount to list. * @expiry_list: The list to add the mount to. */ void mnt_set_expiry(struct vfsmount *mnt, struct list_head *expiry_list) { namespace_lock(); list_add_tail(&real_mount(mnt)->mnt_expire, expiry_list); namespace_unlock(); } EXPORT_SYMBOL(mnt_set_expiry); /* * process a list of expirable mountpoints with the intent of discarding any * mountpoints that aren't in use and haven't been touched since last we came * here */ void mark_mounts_for_expiry(struct list_head *mounts) { struct mount *mnt, *next; LIST_HEAD(graveyard); if (list_empty(mounts)) return; namespace_lock(); lock_mount_hash(); /* extract from the expiration list every vfsmount that matches the * following criteria: * - only referenced by its parent vfsmount * - still marked for expiry (marked on the last call here; marks are * cleared by mntput()) */ list_for_each_entry_safe(mnt, next, mounts, mnt_expire) { if (!xchg(&mnt->mnt_expiry_mark, 1) || propagate_mount_busy(mnt, 1)) continue; list_move(&mnt->mnt_expire, &graveyard); } while (!list_empty(&graveyard)) { mnt = list_first_entry(&graveyard, struct mount, mnt_expire); touch_mnt_namespace(mnt->mnt_ns); umount_tree(mnt, UMOUNT_PROPAGATE|UMOUNT_SYNC); } unlock_mount_hash(); namespace_unlock(); } EXPORT_SYMBOL_GPL(mark_mounts_for_expiry); /* * Ripoff of 'select_parent()' * * search the list of submounts for a given mountpoint, and move any * shrinkable submounts to the 'graveyard' list. */ static int select_submounts(struct mount *parent, struct list_head *graveyard) { struct mount *this_parent = parent; struct list_head *next; int found = 0; repeat: next = this_parent->mnt_mounts.next; resume: while (next != &this_parent->mnt_mounts) { struct list_head *tmp = next; struct mount *mnt = list_entry(tmp, struct mount, mnt_child); next = tmp->next; if (!(mnt->mnt.mnt_flags & MNT_SHRINKABLE)) continue; /* * Descend a level if the d_mounts list is non-empty. */ if (!list_empty(&mnt->mnt_mounts)) { this_parent = mnt; goto repeat; } if (!propagate_mount_busy(mnt, 1)) { list_move_tail(&mnt->mnt_expire, graveyard); found++; } } /* * All done at this level ... ascend and resume the search */ if (this_parent != parent) { next = this_parent->mnt_child.next; this_parent = this_parent->mnt_parent; goto resume; } return found; } /* * process a list of expirable mountpoints with the intent of discarding any * submounts of a specific parent mountpoint * * mount_lock must be held for write */ static void shrink_submounts(struct mount *mnt) { LIST_HEAD(graveyard); struct mount *m; /* extract submounts of 'mountpoint' from the expiration list */ while (select_submounts(mnt, &graveyard)) { while (!list_empty(&graveyard)) { m = list_first_entry(&graveyard, struct mount, mnt_expire); touch_mnt_namespace(m->mnt_ns); umount_tree(m, UMOUNT_PROPAGATE|UMOUNT_SYNC); } } } /* * Some copy_from_user() implementations do not return the exact number of * bytes remaining to copy on a fault. But copy_mount_options() requires that. * Note that this function differs from copy_from_user() in that it will oops * on bad values of `to', rather than returning a short copy. */ static long exact_copy_from_user(void *to, const void __user * from, unsigned long n) { char *t = to; const char __user *f = from; char c; if (!access_ok(VERIFY_READ, from, n)) return n; while (n) { if (__get_user(c, f)) { memset(t, 0, n); break; } *t++ = c; f++; n--; } return n; } int copy_mount_options(const void __user * data, unsigned long *where) { int i; unsigned long page; unsigned long size; *where = 0; if (!data) return 0; if (!(page = __get_free_page(GFP_KERNEL))) return -ENOMEM; /* We only care that *some* data at the address the user * gave us is valid. Just in case, we'll zero * the remainder of the page. */ /* copy_from_user cannot cross TASK_SIZE ! */ size = TASK_SIZE - (unsigned long)data; if (size > PAGE_SIZE) size = PAGE_SIZE; i = size - exact_copy_from_user((void *)page, data, size); if (!i) { free_page(page); return -EFAULT; } if (i != PAGE_SIZE) memset((char *)page + i, 0, PAGE_SIZE - i); *where = page; return 0; } char *copy_mount_string(const void __user *data) { return data ? strndup_user(data, PAGE_SIZE) : NULL; } /* * Flags is a 32-bit value that allows up to 31 non-fs dependent flags to * be given to the mount() call (ie: read-only, no-dev, no-suid etc). * * data is a (void *) that can point to any structure up to * PAGE_SIZE-1 bytes, which can contain arbitrary fs-dependent * information (or be NULL). * * Pre-0.97 versions of mount() didn't have a flags word. * When the flags word was introduced its top half was required * to have the magic value 0xC0ED, and this remained so until 2.4.0-test9. * Therefore, if this magic number is present, it carries no information * and must be discarded. */ long do_mount(const char *dev_name, const char __user *dir_name, const char *type_page, unsigned long flags, void *data_page) { struct path path; int retval = 0; int mnt_flags = 0; /* Discard magic */ if ((flags & MS_MGC_MSK) == MS_MGC_VAL) flags &= ~MS_MGC_MSK; /* Basic sanity checks */ if (data_page) ((char *)data_page)[PAGE_SIZE - 1] = 0; /* ... and get the mountpoint */ retval = user_path(dir_name, &path); if (retval) return retval; retval = security_sb_mount(dev_name, &path, type_page, flags, data_page); if (!retval && !may_mount()) retval = -EPERM; if (retval) goto dput_out; /* Default to relatime unless overriden */ if (!(flags & MS_NOATIME)) mnt_flags |= MNT_RELATIME; /* Separate the per-mountpoint flags */ if (flags & MS_NOSUID) mnt_flags |= MNT_NOSUID; if (flags & MS_NODEV) mnt_flags |= MNT_NODEV; if (flags & MS_NOEXEC) mnt_flags |= MNT_NOEXEC; if (flags & MS_NOATIME) mnt_flags |= MNT_NOATIME; if (flags & MS_NODIRATIME) mnt_flags |= MNT_NODIRATIME; if (flags & MS_STRICTATIME) mnt_flags &= ~(MNT_RELATIME | MNT_NOATIME); if (flags & MS_RDONLY) mnt_flags |= MNT_READONLY; /* The default atime for remount is preservation */ if ((flags & MS_REMOUNT) && ((flags & (MS_NOATIME | MS_NODIRATIME | MS_RELATIME | MS_STRICTATIME)) == 0)) { mnt_flags &= ~MNT_ATIME_MASK; mnt_flags |= path.mnt->mnt_flags & MNT_ATIME_MASK; } flags &= ~(MS_NOSUID | MS_NOEXEC | MS_NODEV | MS_ACTIVE | MS_BORN | MS_NOATIME | MS_NODIRATIME | MS_RELATIME| MS_KERNMOUNT | MS_STRICTATIME); if (flags & MS_REMOUNT) retval = do_remount(&path, flags & ~MS_REMOUNT, mnt_flags, data_page); else if (flags & MS_BIND) retval = do_loopback(&path, dev_name, flags & MS_REC); else if (flags & (MS_SHARED | MS_PRIVATE | MS_SLAVE | MS_UNBINDABLE)) retval = do_change_type(&path, flags); else if (flags & MS_MOVE) retval = do_move_mount(&path, dev_name); else retval = do_new_mount(&path, type_page, flags, mnt_flags, dev_name, data_page); dput_out: path_put(&path); return retval; } static void free_mnt_ns(struct mnt_namespace *ns) { ns_free_inum(&ns->ns); put_user_ns(ns->user_ns); kfree(ns); } /* * Assign a sequence number so we can detect when we attempt to bind * mount a reference to an older mount namespace into the current * mount namespace, preventing reference counting loops. A 64bit * number incrementing at 10Ghz will take 12,427 years to wrap which * is effectively never, so we can ignore the possibility. */ static atomic64_t mnt_ns_seq = ATOMIC64_INIT(1); static struct mnt_namespace *alloc_mnt_ns(struct user_namespace *user_ns) { struct mnt_namespace *new_ns; int ret; new_ns = kmalloc(sizeof(struct mnt_namespace), GFP_KERNEL); if (!new_ns) return ERR_PTR(-ENOMEM); ret = ns_alloc_inum(&new_ns->ns); if (ret) { kfree(new_ns); return ERR_PTR(ret); } new_ns->ns.ops = &mntns_operations; new_ns->seq = atomic64_add_return(1, &mnt_ns_seq); atomic_set(&new_ns->count, 1); new_ns->root = NULL; INIT_LIST_HEAD(&new_ns->list); init_waitqueue_head(&new_ns->poll); new_ns->event = 0; new_ns->user_ns = get_user_ns(user_ns); return new_ns; } struct mnt_namespace *copy_mnt_ns(unsigned long flags, struct mnt_namespace *ns, struct user_namespace *user_ns, struct fs_struct *new_fs) { struct mnt_namespace *new_ns; struct vfsmount *rootmnt = NULL, *pwdmnt = NULL; struct mount *p, *q; struct mount *old; struct mount *new; int copy_flags; BUG_ON(!ns); if (likely(!(flags & CLONE_NEWNS))) { get_mnt_ns(ns); return ns; } old = ns->root; new_ns = alloc_mnt_ns(user_ns); if (IS_ERR(new_ns)) return new_ns; namespace_lock(); /* First pass: copy the tree topology */ copy_flags = CL_COPY_UNBINDABLE | CL_EXPIRE; if (user_ns != ns->user_ns) copy_flags |= CL_SHARED_TO_SLAVE | CL_UNPRIVILEGED; new = copy_tree(old, old->mnt.mnt_root, copy_flags); if (IS_ERR(new)) { namespace_unlock(); free_mnt_ns(new_ns); return ERR_CAST(new); } new_ns->root = new; list_add_tail(&new_ns->list, &new->mnt_list); /* * Second pass: switch the tsk->fs->* elements and mark new vfsmounts * as belonging to new namespace. We have already acquired a private * fs_struct, so tsk->fs->lock is not needed. */ p = old; q = new; while (p) { q->mnt_ns = new_ns; if (new_fs) { if (&p->mnt == new_fs->root.mnt) { new_fs->root.mnt = mntget(&q->mnt); rootmnt = &p->mnt; } if (&p->mnt == new_fs->pwd.mnt) { new_fs->pwd.mnt = mntget(&q->mnt); pwdmnt = &p->mnt; } } p = next_mnt(p, old); q = next_mnt(q, new); if (!q) break; while (p->mnt.mnt_root != q->mnt.mnt_root) p = next_mnt(p, old); } namespace_unlock(); if (rootmnt) mntput(rootmnt); if (pwdmnt) mntput(pwdmnt); return new_ns; } /** * create_mnt_ns - creates a private namespace and adds a root filesystem * @mnt: pointer to the new root filesystem mountpoint */ static struct mnt_namespace *create_mnt_ns(struct vfsmount *m) { struct mnt_namespace *new_ns = alloc_mnt_ns(&init_user_ns); if (!IS_ERR(new_ns)) { struct mount *mnt = real_mount(m); mnt->mnt_ns = new_ns; new_ns->root = mnt; list_add(&mnt->mnt_list, &new_ns->list); } else { mntput(m); } return new_ns; } struct dentry *mount_subtree(struct vfsmount *mnt, const char *name) { struct mnt_namespace *ns; struct super_block *s; struct path path; int err; ns = create_mnt_ns(mnt); if (IS_ERR(ns)) return ERR_CAST(ns); err = vfs_path_lookup(mnt->mnt_root, mnt, name, LOOKUP_FOLLOW|LOOKUP_AUTOMOUNT, &path); put_mnt_ns(ns); if (err) return ERR_PTR(err); /* trade a vfsmount reference for active sb one */ s = path.mnt->mnt_sb; atomic_inc(&s->s_active); mntput(path.mnt); /* lock the sucker */ down_write(&s->s_umount); /* ... and return the root of (sub)tree on it */ return path.dentry; } EXPORT_SYMBOL(mount_subtree); SYSCALL_DEFINE5(mount, char __user *, dev_name, char __user *, dir_name, char __user *, type, unsigned long, flags, void __user *, data) { int ret; char *kernel_type; char *kernel_dev; unsigned long data_page; kernel_type = copy_mount_string(type); ret = PTR_ERR(kernel_type); if (IS_ERR(kernel_type)) goto out_type; kernel_dev = copy_mount_string(dev_name); ret = PTR_ERR(kernel_dev); if (IS_ERR(kernel_dev)) goto out_dev; ret = copy_mount_options(data, &data_page); if (ret < 0) goto out_data; ret = do_mount(kernel_dev, dir_name, kernel_type, flags, (void *) data_page); free_page(data_page); out_data: kfree(kernel_dev); out_dev: kfree(kernel_type); out_type: return ret; } /* * Return true if path is reachable from root * * namespace_sem or mount_lock is held */ bool is_path_reachable(struct mount *mnt, struct dentry *dentry, const struct path *root) { while (&mnt->mnt != root->mnt && mnt_has_parent(mnt)) { dentry = mnt->mnt_mountpoint; mnt = mnt->mnt_parent; } return &mnt->mnt == root->mnt && is_subdir(dentry, root->dentry); } int path_is_under(struct path *path1, struct path *path2) { int res; read_seqlock_excl(&mount_lock); res = is_path_reachable(real_mount(path1->mnt), path1->dentry, path2); read_sequnlock_excl(&mount_lock); return res; } EXPORT_SYMBOL(path_is_under); /* * pivot_root Semantics: * Moves the root file system of the current process to the directory put_old, * makes new_root as the new root file system of the current process, and sets * root/cwd of all processes which had them on the current root to new_root. * * Restrictions: * The new_root and put_old must be directories, and must not be on the * same file system as the current process root. The put_old must be * underneath new_root, i.e. adding a non-zero number of /.. to the string * pointed to by put_old must yield the same directory as new_root. No other * file system may be mounted on put_old. After all, new_root is a mountpoint. * * Also, the current root cannot be on the 'rootfs' (initial ramfs) filesystem. * See Documentation/filesystems/ramfs-rootfs-initramfs.txt for alternatives * in this situation. * * Notes: * - we don't move root/cwd if they are not at the root (reason: if something * cared enough to change them, it's probably wrong to force them elsewhere) * - it's okay to pick a root that isn't the root of a file system, e.g. * /nfs/my_root where /nfs is the mount point. It must be a mountpoint, * though, so you may need to say mount --bind /nfs/my_root /nfs/my_root * first. */ SYSCALL_DEFINE2(pivot_root, const char __user *, new_root, const char __user *, put_old) { struct path new, old, parent_path, root_parent, root; struct mount *new_mnt, *root_mnt, *old_mnt; struct mountpoint *old_mp, *root_mp; int error; if (!may_mount()) return -EPERM; error = user_path_dir(new_root, &new); if (error) goto out0; error = user_path_dir(put_old, &old); if (error) goto out1; error = security_sb_pivotroot(&old, &new); if (error) goto out2; get_fs_root(current->fs, &root); old_mp = lock_mount(&old); error = PTR_ERR(old_mp); if (IS_ERR(old_mp)) goto out3; error = -EINVAL; new_mnt = real_mount(new.mnt); root_mnt = real_mount(root.mnt); old_mnt = real_mount(old.mnt); if (IS_MNT_SHARED(old_mnt) || IS_MNT_SHARED(new_mnt->mnt_parent) || IS_MNT_SHARED(root_mnt->mnt_parent)) goto out4; if (!check_mnt(root_mnt) || !check_mnt(new_mnt)) goto out4; if (new_mnt->mnt.mnt_flags & MNT_LOCKED) goto out4; error = -ENOENT; if (d_unlinked(new.dentry)) goto out4; error = -EBUSY; if (new_mnt == root_mnt || old_mnt == root_mnt) goto out4; /* loop, on the same file system */ error = -EINVAL; if (root.mnt->mnt_root != root.dentry) goto out4; /* not a mountpoint */ if (!mnt_has_parent(root_mnt)) goto out4; /* not attached */ root_mp = root_mnt->mnt_mp; if (new.mnt->mnt_root != new.dentry) goto out4; /* not a mountpoint */ if (!mnt_has_parent(new_mnt)) goto out4; /* not attached */ /* make sure we can reach put_old from new_root */ if (!is_path_reachable(old_mnt, old.dentry, &new)) goto out4; /* make certain new is below the root */ if (!is_path_reachable(new_mnt, new.dentry, &root)) goto out4; root_mp->m_count++; /* pin it so it won't go away */ lock_mount_hash(); detach_mnt(new_mnt, &parent_path); detach_mnt(root_mnt, &root_parent); if (root_mnt->mnt.mnt_flags & MNT_LOCKED) { new_mnt->mnt.mnt_flags |= MNT_LOCKED; root_mnt->mnt.mnt_flags &= ~MNT_LOCKED; } /* mount old root on put_old */ attach_mnt(root_mnt, old_mnt, old_mp); /* mount new_root on / */ attach_mnt(new_mnt, real_mount(root_parent.mnt), root_mp); touch_mnt_namespace(current->nsproxy->mnt_ns); /* A moved mount should not expire automatically */ list_del_init(&new_mnt->mnt_expire); unlock_mount_hash(); chroot_fs_refs(&root, &new); put_mountpoint(root_mp); error = 0; out4: unlock_mount(old_mp); if (!error) { path_put(&root_parent); path_put(&parent_path); } out3: path_put(&root); out2: path_put(&old); out1: path_put(&new); out0: return error; } static void __init init_mount_tree(void) { struct vfsmount *mnt; struct mnt_namespace *ns; struct path root; struct file_system_type *type; type = get_fs_type("rootfs"); if (!type) panic("Can't find rootfs type"); mnt = vfs_kern_mount(type, 0, "rootfs", NULL); put_filesystem(type); if (IS_ERR(mnt)) panic("Can't create rootfs"); ns = create_mnt_ns(mnt); if (IS_ERR(ns)) panic("Can't allocate initial namespace"); init_task.nsproxy->mnt_ns = ns; get_mnt_ns(ns); root.mnt = mnt; root.dentry = mnt->mnt_root; mnt->mnt_flags |= MNT_LOCKED; set_fs_pwd(current->fs, &root); set_fs_root(current->fs, &root); } void __init mnt_init(void) { unsigned u; int err; mnt_cache = kmem_cache_create("mnt_cache", sizeof(struct mount), 0, SLAB_HWCACHE_ALIGN | SLAB_PANIC, NULL); mount_hashtable = alloc_large_system_hash("Mount-cache", sizeof(struct hlist_head), mhash_entries, 19, 0, &m_hash_shift, &m_hash_mask, 0, 0); mountpoint_hashtable = alloc_large_system_hash("Mountpoint-cache", sizeof(struct hlist_head), mphash_entries, 19, 0, &mp_hash_shift, &mp_hash_mask, 0, 0); if (!mount_hashtable || !mountpoint_hashtable) panic("Failed to allocate mount hash table\n"); for (u = 0; u <= m_hash_mask; u++) INIT_HLIST_HEAD(&mount_hashtable[u]); for (u = 0; u <= mp_hash_mask; u++) INIT_HLIST_HEAD(&mountpoint_hashtable[u]); kernfs_init(); err = sysfs_init(); if (err) printk(KERN_WARNING "%s: sysfs_init error: %d\n", __func__, err); fs_kobj = kobject_create_and_add("fs", NULL); if (!fs_kobj) printk(KERN_WARNING "%s: kobj create error\n", __func__); init_rootfs(); init_mount_tree(); } void put_mnt_ns(struct mnt_namespace *ns) { if (!atomic_dec_and_test(&ns->count)) return; drop_collected_mounts(&ns->root->mnt); free_mnt_ns(ns); } struct vfsmount *kern_mount_data(struct file_system_type *type, void *data) { struct vfsmount *mnt; mnt = vfs_kern_mount(type, MS_KERNMOUNT, type->name, data); if (!IS_ERR(mnt)) { /* * it is a longterm mount, don't release mnt until * we unmount before file sys is unregistered */ real_mount(mnt)->mnt_ns = MNT_NS_INTERNAL; } return mnt; } EXPORT_SYMBOL_GPL(kern_mount_data); void kern_unmount(struct vfsmount *mnt) { /* release long term mount so mount point can be released */ if (!IS_ERR_OR_NULL(mnt)) { real_mount(mnt)->mnt_ns = NULL; synchronize_rcu(); /* yecchhh... */ mntput(mnt); } } EXPORT_SYMBOL(kern_unmount); bool our_mnt(struct vfsmount *mnt) { return check_mnt(real_mount(mnt)); } bool current_chrooted(void) { /* Does the current process have a non-standard root */ struct path ns_root; struct path fs_root; bool chrooted; /* Find the namespace root */ ns_root.mnt = &current->nsproxy->mnt_ns->root->mnt; ns_root.dentry = ns_root.mnt->mnt_root; path_get(&ns_root); while (d_mountpoint(ns_root.dentry) && follow_down_one(&ns_root)) ; get_fs_root(current->fs, &fs_root); chrooted = !path_equal(&fs_root, &ns_root); path_put(&fs_root); path_put(&ns_root); return chrooted; } bool fs_fully_visible(struct file_system_type *type) { struct mnt_namespace *ns = current->nsproxy->mnt_ns; struct mount *mnt; bool visible = false; if (unlikely(!ns)) return false; down_read(&namespace_sem); list_for_each_entry(mnt, &ns->list, mnt_list) { struct mount *child; if (mnt->mnt.mnt_sb->s_type != type) continue; /* This mount is not fully visible if there are any child mounts * that cover anything except for empty directories. */ list_for_each_entry(child, &mnt->mnt_mounts, mnt_child) { struct inode *inode = child->mnt_mountpoint->d_inode; if (!S_ISDIR(inode->i_mode)) goto next; if (inode->i_nlink > 2) goto next; } visible = true; goto found; next: ; } found: up_read(&namespace_sem); return visible; } static struct ns_common *mntns_get(struct task_struct *task) { struct ns_common *ns = NULL; struct nsproxy *nsproxy; task_lock(task); nsproxy = task->nsproxy; if (nsproxy) { ns = &nsproxy->mnt_ns->ns; get_mnt_ns(to_mnt_ns(ns)); } task_unlock(task); return ns; } static void mntns_put(struct ns_common *ns) { put_mnt_ns(to_mnt_ns(ns)); } static int mntns_install(struct nsproxy *nsproxy, struct ns_common *ns) { struct fs_struct *fs = current->fs; struct mnt_namespace *mnt_ns = to_mnt_ns(ns); struct path root; if (!ns_capable(mnt_ns->user_ns, CAP_SYS_ADMIN) || !ns_capable(current_user_ns(), CAP_SYS_CHROOT) || !ns_capable(current_user_ns(), CAP_SYS_ADMIN)) return -EPERM; if (fs->users != 1) return -EINVAL; get_mnt_ns(mnt_ns); put_mnt_ns(nsproxy->mnt_ns); nsproxy->mnt_ns = mnt_ns; /* Find the root */ root.mnt = &mnt_ns->root->mnt; root.dentry = mnt_ns->root->mnt.mnt_root; path_get(&root); while(d_mountpoint(root.dentry) && follow_down_one(&root)) ; /* Update the pwd and root */ set_fs_pwd(fs, &root); set_fs_root(fs, &root); path_put(&root); return 0; } const struct proc_ns_operations mntns_operations = { .name = "mnt", .type = CLONE_NEWNS, .get = mntns_get, .put = mntns_put, .install = mntns_install, };
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1626_0
crossvul-cpp_data_good_3401_0
/************************************************************************** * * Copyright © 2009-2015 VMware, Inc., Palo Alto, CA., USA * All Rights Reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sub license, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice (including the * next paragraph) shall be included in all copies or substantial portions * of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL * THE COPYRIGHT HOLDERS, AUTHORS AND/OR ITS SUPPLIERS BE LIABLE FOR ANY CLAIM, * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. * **************************************************************************/ #include "vmwgfx_drv.h" #include "vmwgfx_resource_priv.h" #include "vmwgfx_so.h" #include "vmwgfx_binding.h" #include <ttm/ttm_placement.h> #include "device_include/svga3d_surfacedefs.h" /** * struct vmw_user_surface - User-space visible surface resource * * @base: The TTM base object handling user-space visibility. * @srf: The surface metadata. * @size: TTM accounting size for the surface. * @master: master of the creating client. Used for security check. */ struct vmw_user_surface { struct ttm_prime_object prime; struct vmw_surface srf; uint32_t size; struct drm_master *master; struct ttm_base_object *backup_base; }; /** * struct vmw_surface_offset - Backing store mip level offset info * * @face: Surface face. * @mip: Mip level. * @bo_offset: Offset into backing store of this mip level. * */ struct vmw_surface_offset { uint32_t face; uint32_t mip; uint32_t bo_offset; }; static void vmw_user_surface_free(struct vmw_resource *res); static struct vmw_resource * vmw_user_surface_base_to_res(struct ttm_base_object *base); static int vmw_legacy_srf_bind(struct vmw_resource *res, struct ttm_validate_buffer *val_buf); static int vmw_legacy_srf_unbind(struct vmw_resource *res, bool readback, struct ttm_validate_buffer *val_buf); static int vmw_legacy_srf_create(struct vmw_resource *res); static int vmw_legacy_srf_destroy(struct vmw_resource *res); static int vmw_gb_surface_create(struct vmw_resource *res); static int vmw_gb_surface_bind(struct vmw_resource *res, struct ttm_validate_buffer *val_buf); static int vmw_gb_surface_unbind(struct vmw_resource *res, bool readback, struct ttm_validate_buffer *val_buf); static int vmw_gb_surface_destroy(struct vmw_resource *res); static const struct vmw_user_resource_conv user_surface_conv = { .object_type = VMW_RES_SURFACE, .base_obj_to_res = vmw_user_surface_base_to_res, .res_free = vmw_user_surface_free }; const struct vmw_user_resource_conv *user_surface_converter = &user_surface_conv; static uint64_t vmw_user_surface_size; static const struct vmw_res_func vmw_legacy_surface_func = { .res_type = vmw_res_surface, .needs_backup = false, .may_evict = true, .type_name = "legacy surfaces", .backup_placement = &vmw_srf_placement, .create = &vmw_legacy_srf_create, .destroy = &vmw_legacy_srf_destroy, .bind = &vmw_legacy_srf_bind, .unbind = &vmw_legacy_srf_unbind }; static const struct vmw_res_func vmw_gb_surface_func = { .res_type = vmw_res_surface, .needs_backup = true, .may_evict = true, .type_name = "guest backed surfaces", .backup_placement = &vmw_mob_placement, .create = vmw_gb_surface_create, .destroy = vmw_gb_surface_destroy, .bind = vmw_gb_surface_bind, .unbind = vmw_gb_surface_unbind }; /** * struct vmw_surface_dma - SVGA3D DMA command */ struct vmw_surface_dma { SVGA3dCmdHeader header; SVGA3dCmdSurfaceDMA body; SVGA3dCopyBox cb; SVGA3dCmdSurfaceDMASuffix suffix; }; /** * struct vmw_surface_define - SVGA3D Surface Define command */ struct vmw_surface_define { SVGA3dCmdHeader header; SVGA3dCmdDefineSurface body; }; /** * struct vmw_surface_destroy - SVGA3D Surface Destroy command */ struct vmw_surface_destroy { SVGA3dCmdHeader header; SVGA3dCmdDestroySurface body; }; /** * vmw_surface_dma_size - Compute fifo size for a dma command. * * @srf: Pointer to a struct vmw_surface * * Computes the required size for a surface dma command for backup or * restoration of the surface represented by @srf. */ static inline uint32_t vmw_surface_dma_size(const struct vmw_surface *srf) { return srf->num_sizes * sizeof(struct vmw_surface_dma); } /** * vmw_surface_define_size - Compute fifo size for a surface define command. * * @srf: Pointer to a struct vmw_surface * * Computes the required size for a surface define command for the definition * of the surface represented by @srf. */ static inline uint32_t vmw_surface_define_size(const struct vmw_surface *srf) { return sizeof(struct vmw_surface_define) + srf->num_sizes * sizeof(SVGA3dSize); } /** * vmw_surface_destroy_size - Compute fifo size for a surface destroy command. * * Computes the required size for a surface destroy command for the destruction * of a hw surface. */ static inline uint32_t vmw_surface_destroy_size(void) { return sizeof(struct vmw_surface_destroy); } /** * vmw_surface_destroy_encode - Encode a surface_destroy command. * * @id: The surface id * @cmd_space: Pointer to memory area in which the commands should be encoded. */ static void vmw_surface_destroy_encode(uint32_t id, void *cmd_space) { struct vmw_surface_destroy *cmd = (struct vmw_surface_destroy *) cmd_space; cmd->header.id = SVGA_3D_CMD_SURFACE_DESTROY; cmd->header.size = sizeof(cmd->body); cmd->body.sid = id; } /** * vmw_surface_define_encode - Encode a surface_define command. * * @srf: Pointer to a struct vmw_surface object. * @cmd_space: Pointer to memory area in which the commands should be encoded. */ static void vmw_surface_define_encode(const struct vmw_surface *srf, void *cmd_space) { struct vmw_surface_define *cmd = (struct vmw_surface_define *) cmd_space; struct drm_vmw_size *src_size; SVGA3dSize *cmd_size; uint32_t cmd_len; int i; cmd_len = sizeof(cmd->body) + srf->num_sizes * sizeof(SVGA3dSize); cmd->header.id = SVGA_3D_CMD_SURFACE_DEFINE; cmd->header.size = cmd_len; cmd->body.sid = srf->res.id; cmd->body.surfaceFlags = srf->flags; cmd->body.format = srf->format; for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) cmd->body.face[i].numMipLevels = srf->mip_levels[i]; cmd += 1; cmd_size = (SVGA3dSize *) cmd; src_size = srf->sizes; for (i = 0; i < srf->num_sizes; ++i, cmd_size++, src_size++) { cmd_size->width = src_size->width; cmd_size->height = src_size->height; cmd_size->depth = src_size->depth; } } /** * vmw_surface_dma_encode - Encode a surface_dma command. * * @srf: Pointer to a struct vmw_surface object. * @cmd_space: Pointer to memory area in which the commands should be encoded. * @ptr: Pointer to an SVGAGuestPtr indicating where the surface contents * should be placed or read from. * @to_surface: Boolean whether to DMA to the surface or from the surface. */ static void vmw_surface_dma_encode(struct vmw_surface *srf, void *cmd_space, const SVGAGuestPtr *ptr, bool to_surface) { uint32_t i; struct vmw_surface_dma *cmd = (struct vmw_surface_dma *)cmd_space; const struct svga3d_surface_desc *desc = svga3dsurface_get_desc(srf->format); for (i = 0; i < srf->num_sizes; ++i) { SVGA3dCmdHeader *header = &cmd->header; SVGA3dCmdSurfaceDMA *body = &cmd->body; SVGA3dCopyBox *cb = &cmd->cb; SVGA3dCmdSurfaceDMASuffix *suffix = &cmd->suffix; const struct vmw_surface_offset *cur_offset = &srf->offsets[i]; const struct drm_vmw_size *cur_size = &srf->sizes[i]; header->id = SVGA_3D_CMD_SURFACE_DMA; header->size = sizeof(*body) + sizeof(*cb) + sizeof(*suffix); body->guest.ptr = *ptr; body->guest.ptr.offset += cur_offset->bo_offset; body->guest.pitch = svga3dsurface_calculate_pitch(desc, cur_size); body->host.sid = srf->res.id; body->host.face = cur_offset->face; body->host.mipmap = cur_offset->mip; body->transfer = ((to_surface) ? SVGA3D_WRITE_HOST_VRAM : SVGA3D_READ_HOST_VRAM); cb->x = 0; cb->y = 0; cb->z = 0; cb->srcx = 0; cb->srcy = 0; cb->srcz = 0; cb->w = cur_size->width; cb->h = cur_size->height; cb->d = cur_size->depth; suffix->suffixSize = sizeof(*suffix); suffix->maximumOffset = svga3dsurface_get_image_buffer_size(desc, cur_size, body->guest.pitch); suffix->flags.discard = 0; suffix->flags.unsynchronized = 0; suffix->flags.reserved = 0; ++cmd; } }; /** * vmw_hw_surface_destroy - destroy a Device surface * * @res: Pointer to a struct vmw_resource embedded in a struct * vmw_surface. * * Destroys a the device surface associated with a struct vmw_surface if * any, and adjusts accounting and resource count accordingly. */ static void vmw_hw_surface_destroy(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; struct vmw_surface *srf; void *cmd; if (res->func->destroy == vmw_gb_surface_destroy) { (void) vmw_gb_surface_destroy(res); return; } if (res->id != -1) { cmd = vmw_fifo_reserve(dev_priv, vmw_surface_destroy_size()); if (unlikely(!cmd)) { DRM_ERROR("Failed reserving FIFO space for surface " "destruction.\n"); return; } vmw_surface_destroy_encode(res->id, cmd); vmw_fifo_commit(dev_priv, vmw_surface_destroy_size()); /* * used_memory_size_atomic, or separate lock * to avoid taking dev_priv::cmdbuf_mutex in * the destroy path. */ mutex_lock(&dev_priv->cmdbuf_mutex); srf = vmw_res_to_srf(res); dev_priv->used_memory_size -= res->backup_size; mutex_unlock(&dev_priv->cmdbuf_mutex); } vmw_fifo_resource_dec(dev_priv); } /** * vmw_legacy_srf_create - Create a device surface as part of the * resource validation process. * * @res: Pointer to a struct vmw_surface. * * If the surface doesn't have a hw id. * * Returns -EBUSY if there wasn't sufficient device resources to * complete the validation. Retry after freeing up resources. * * May return other errors if the kernel is out of guest resources. */ static int vmw_legacy_srf_create(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; struct vmw_surface *srf; uint32_t submit_size; uint8_t *cmd; int ret; if (likely(res->id != -1)) return 0; srf = vmw_res_to_srf(res); if (unlikely(dev_priv->used_memory_size + res->backup_size >= dev_priv->memory_size)) return -EBUSY; /* * Alloc id for the resource. */ ret = vmw_resource_alloc_id(res); if (unlikely(ret != 0)) { DRM_ERROR("Failed to allocate a surface id.\n"); goto out_no_id; } if (unlikely(res->id >= SVGA3D_MAX_SURFACE_IDS)) { ret = -EBUSY; goto out_no_fifo; } /* * Encode surface define- commands. */ submit_size = vmw_surface_define_size(srf); cmd = vmw_fifo_reserve(dev_priv, submit_size); if (unlikely(!cmd)) { DRM_ERROR("Failed reserving FIFO space for surface " "creation.\n"); ret = -ENOMEM; goto out_no_fifo; } vmw_surface_define_encode(srf, cmd); vmw_fifo_commit(dev_priv, submit_size); /* * Surface memory usage accounting. */ dev_priv->used_memory_size += res->backup_size; return 0; out_no_fifo: vmw_resource_release_id(res); out_no_id: return ret; } /** * vmw_legacy_srf_dma - Copy backup data to or from a legacy surface. * * @res: Pointer to a struct vmw_res embedded in a struct * vmw_surface. * @val_buf: Pointer to a struct ttm_validate_buffer containing * information about the backup buffer. * @bind: Boolean wether to DMA to the surface. * * Transfer backup data to or from a legacy surface as part of the * validation process. * May return other errors if the kernel is out of guest resources. * The backup buffer will be fenced or idle upon successful completion, * and if the surface needs persistent backup storage, the backup buffer * will also be returned reserved iff @bind is true. */ static int vmw_legacy_srf_dma(struct vmw_resource *res, struct ttm_validate_buffer *val_buf, bool bind) { SVGAGuestPtr ptr; struct vmw_fence_obj *fence; uint32_t submit_size; struct vmw_surface *srf = vmw_res_to_srf(res); uint8_t *cmd; struct vmw_private *dev_priv = res->dev_priv; BUG_ON(!val_buf->bo); submit_size = vmw_surface_dma_size(srf); cmd = vmw_fifo_reserve(dev_priv, submit_size); if (unlikely(!cmd)) { DRM_ERROR("Failed reserving FIFO space for surface " "DMA.\n"); return -ENOMEM; } vmw_bo_get_guest_ptr(val_buf->bo, &ptr); vmw_surface_dma_encode(srf, cmd, &ptr, bind); vmw_fifo_commit(dev_priv, submit_size); /* * Create a fence object and fence the backup buffer. */ (void) vmw_execbuf_fence_commands(NULL, dev_priv, &fence, NULL); vmw_fence_single_bo(val_buf->bo, fence); if (likely(fence != NULL)) vmw_fence_obj_unreference(&fence); return 0; } /** * vmw_legacy_srf_bind - Perform a legacy surface bind as part of the * surface validation process. * * @res: Pointer to a struct vmw_res embedded in a struct * vmw_surface. * @val_buf: Pointer to a struct ttm_validate_buffer containing * information about the backup buffer. * * This function will copy backup data to the surface if the * backup buffer is dirty. */ static int vmw_legacy_srf_bind(struct vmw_resource *res, struct ttm_validate_buffer *val_buf) { if (!res->backup_dirty) return 0; return vmw_legacy_srf_dma(res, val_buf, true); } /** * vmw_legacy_srf_unbind - Perform a legacy surface unbind as part of the * surface eviction process. * * @res: Pointer to a struct vmw_res embedded in a struct * vmw_surface. * @val_buf: Pointer to a struct ttm_validate_buffer containing * information about the backup buffer. * * This function will copy backup data from the surface. */ static int vmw_legacy_srf_unbind(struct vmw_resource *res, bool readback, struct ttm_validate_buffer *val_buf) { if (unlikely(readback)) return vmw_legacy_srf_dma(res, val_buf, false); return 0; } /** * vmw_legacy_srf_destroy - Destroy a device surface as part of a * resource eviction process. * * @res: Pointer to a struct vmw_res embedded in a struct * vmw_surface. */ static int vmw_legacy_srf_destroy(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; uint32_t submit_size; uint8_t *cmd; BUG_ON(res->id == -1); /* * Encode the dma- and surface destroy commands. */ submit_size = vmw_surface_destroy_size(); cmd = vmw_fifo_reserve(dev_priv, submit_size); if (unlikely(!cmd)) { DRM_ERROR("Failed reserving FIFO space for surface " "eviction.\n"); return -ENOMEM; } vmw_surface_destroy_encode(res->id, cmd); vmw_fifo_commit(dev_priv, submit_size); /* * Surface memory usage accounting. */ dev_priv->used_memory_size -= res->backup_size; /* * Release the surface ID. */ vmw_resource_release_id(res); return 0; } /** * vmw_surface_init - initialize a struct vmw_surface * * @dev_priv: Pointer to a device private struct. * @srf: Pointer to the struct vmw_surface to initialize. * @res_free: Pointer to a resource destructor used to free * the object. */ static int vmw_surface_init(struct vmw_private *dev_priv, struct vmw_surface *srf, void (*res_free) (struct vmw_resource *res)) { int ret; struct vmw_resource *res = &srf->res; BUG_ON(!res_free); if (!dev_priv->has_mob) vmw_fifo_resource_inc(dev_priv); ret = vmw_resource_init(dev_priv, res, true, res_free, (dev_priv->has_mob) ? &vmw_gb_surface_func : &vmw_legacy_surface_func); if (unlikely(ret != 0)) { if (!dev_priv->has_mob) vmw_fifo_resource_dec(dev_priv); res_free(res); return ret; } /* * The surface won't be visible to hardware until a * surface validate. */ INIT_LIST_HEAD(&srf->view_list); vmw_resource_activate(res, vmw_hw_surface_destroy); return ret; } /** * vmw_user_surface_base_to_res - TTM base object to resource converter for * user visible surfaces * * @base: Pointer to a TTM base object * * Returns the struct vmw_resource embedded in a struct vmw_surface * for the user-visible object identified by the TTM base object @base. */ static struct vmw_resource * vmw_user_surface_base_to_res(struct ttm_base_object *base) { return &(container_of(base, struct vmw_user_surface, prime.base)->srf.res); } /** * vmw_user_surface_free - User visible surface resource destructor * * @res: A struct vmw_resource embedded in a struct vmw_surface. */ static void vmw_user_surface_free(struct vmw_resource *res) { struct vmw_surface *srf = vmw_res_to_srf(res); struct vmw_user_surface *user_srf = container_of(srf, struct vmw_user_surface, srf); struct vmw_private *dev_priv = srf->res.dev_priv; uint32_t size = user_srf->size; if (user_srf->master) drm_master_put(&user_srf->master); kfree(srf->offsets); kfree(srf->sizes); kfree(srf->snooper.image); ttm_prime_object_kfree(user_srf, prime); ttm_mem_global_free(vmw_mem_glob(dev_priv), size); } /** * vmw_user_surface_free - User visible surface TTM base object destructor * * @p_base: Pointer to a pointer to a TTM base object * embedded in a struct vmw_user_surface. * * Drops the base object's reference on its resource, and the * pointer pointed to by *p_base is set to NULL. */ static void vmw_user_surface_base_release(struct ttm_base_object **p_base) { struct ttm_base_object *base = *p_base; struct vmw_user_surface *user_srf = container_of(base, struct vmw_user_surface, prime.base); struct vmw_resource *res = &user_srf->srf.res; *p_base = NULL; if (user_srf->backup_base) ttm_base_object_unref(&user_srf->backup_base); vmw_resource_unreference(&res); } /** * vmw_user_surface_destroy_ioctl - Ioctl function implementing * the user surface destroy functionality. * * @dev: Pointer to a struct drm_device. * @data: Pointer to data copied from / to user-space. * @file_priv: Pointer to a drm file private structure. */ int vmw_surface_destroy_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct drm_vmw_surface_arg *arg = (struct drm_vmw_surface_arg *)data; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; return ttm_ref_object_base_unref(tfile, arg->sid, TTM_REF_USAGE); } /** * vmw_user_surface_define_ioctl - Ioctl function implementing * the user surface define functionality. * * @dev: Pointer to a struct drm_device. * @data: Pointer to data copied from / to user-space. * @file_priv: Pointer to a drm file private structure. */ int vmw_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_surface_create_arg *arg = (union drm_vmw_surface_create_arg *)data; struct drm_vmw_surface_create_req *req = &arg->req; struct drm_vmw_surface_arg *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; int i, j; uint32_t cur_bo_offset; struct drm_vmw_size *cur_size; struct vmw_surface_offset *cur_offset; uint32_t num_sizes; uint32_t size; const struct svga3d_surface_desc *desc; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; num_sizes = 0; for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) { if (req->mip_levels[i] > DRM_VMW_MAX_MIP_LEVELS) return -EINVAL; num_sizes += req->mip_levels[i]; } if (num_sizes > DRM_VMW_MAX_SURFACE_FACES * DRM_VMW_MAX_MIP_LEVELS || num_sizes == 0) return -EINVAL; size = vmw_user_surface_size + 128 + ttm_round_pot(num_sizes * sizeof(struct drm_vmw_size)) + ttm_round_pot(num_sizes * sizeof(struct vmw_surface_offset)); desc = svga3dsurface_get_desc(req->format); if (unlikely(desc->block_desc == SVGA3DBLOCKDESC_NONE)) { DRM_ERROR("Invalid surface format for surface creation.\n"); DRM_ERROR("Format requested is: %d\n", req->format); return -EINVAL; } ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; ret = ttm_mem_global_alloc(vmw_mem_glob(dev_priv), size, false, true); if (unlikely(ret != 0)) { if (ret != -ERESTARTSYS) DRM_ERROR("Out of graphics memory for surface" " creation.\n"); goto out_unlock; } user_srf = kzalloc(sizeof(*user_srf), GFP_KERNEL); if (unlikely(!user_srf)) { ret = -ENOMEM; goto out_no_user_srf; } srf = &user_srf->srf; res = &srf->res; srf->flags = req->flags; srf->format = req->format; srf->scanout = req->scanout; memcpy(srf->mip_levels, req->mip_levels, sizeof(srf->mip_levels)); srf->num_sizes = num_sizes; user_srf->size = size; srf->sizes = memdup_user((struct drm_vmw_size __user *)(unsigned long) req->size_addr, sizeof(*srf->sizes) * srf->num_sizes); if (IS_ERR(srf->sizes)) { ret = PTR_ERR(srf->sizes); goto out_no_sizes; } srf->offsets = kmalloc_array(srf->num_sizes, sizeof(*srf->offsets), GFP_KERNEL); if (unlikely(!srf->offsets)) { ret = -ENOMEM; goto out_no_offsets; } srf->base_size = *srf->sizes; srf->autogen_filter = SVGA3D_TEX_FILTER_NONE; srf->multisample_count = 0; cur_bo_offset = 0; cur_offset = srf->offsets; cur_size = srf->sizes; for (i = 0; i < DRM_VMW_MAX_SURFACE_FACES; ++i) { for (j = 0; j < srf->mip_levels[i]; ++j) { uint32_t stride = svga3dsurface_calculate_pitch (desc, cur_size); cur_offset->face = i; cur_offset->mip = j; cur_offset->bo_offset = cur_bo_offset; cur_bo_offset += svga3dsurface_get_image_buffer_size (desc, cur_size, stride); ++cur_offset; ++cur_size; } } res->backup_size = cur_bo_offset; if (srf->scanout && srf->num_sizes == 1 && srf->sizes[0].width == 64 && srf->sizes[0].height == 64 && srf->format == SVGA3D_A8R8G8B8) { srf->snooper.image = kzalloc(64 * 64 * 4, GFP_KERNEL); if (!srf->snooper.image) { DRM_ERROR("Failed to allocate cursor_image\n"); ret = -ENOMEM; goto out_no_copy; } } else { srf->snooper.image = NULL; } user_srf->prime.base.shareable = false; user_srf->prime.base.tfile = NULL; if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); /** * From this point, the generic resource management functions * destroy the object on failure. */ ret = vmw_surface_init(dev_priv, srf, vmw_user_surface_free); if (unlikely(ret != 0)) goto out_unlock; /* * A gb-aware client referencing a shared surface will * expect a backup buffer to be present. */ if (dev_priv->has_mob && req->shareable) { uint32_t backup_handle; ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, true, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } } tmp = vmw_resource_reference(&srf->res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->sid = user_srf->prime.base.hash.key; vmw_resource_unreference(&res); ttm_read_unlock(&dev_priv->reservation_sem); return 0; out_no_copy: kfree(srf->offsets); out_no_offsets: kfree(srf->sizes); out_no_sizes: ttm_prime_object_kfree(user_srf, prime); out_no_user_srf: ttm_mem_global_free(vmw_mem_glob(dev_priv), size); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; } static int vmw_surface_handle_reference(struct vmw_private *dev_priv, struct drm_file *file_priv, uint32_t u_handle, enum drm_vmw_handle_type handle_type, struct ttm_base_object **base_p) { struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; struct vmw_user_surface *user_srf; uint32_t handle; struct ttm_base_object *base; int ret; bool require_exist = false; if (handle_type == DRM_VMW_HANDLE_PRIME) { ret = ttm_prime_fd_to_handle(tfile, u_handle, &handle); if (unlikely(ret != 0)) return ret; } else { if (unlikely(drm_is_render_client(file_priv))) require_exist = true; if (ACCESS_ONCE(vmw_fpriv(file_priv)->locked_master)) { DRM_ERROR("Locked master refused legacy " "surface reference.\n"); return -EACCES; } handle = u_handle; } ret = -EINVAL; base = ttm_base_object_lookup_for_ref(dev_priv->tdev, handle); if (unlikely(!base)) { DRM_ERROR("Could not find surface to reference.\n"); goto out_no_lookup; } if (unlikely(ttm_base_object_type(base) != VMW_RES_SURFACE)) { DRM_ERROR("Referenced object is not a surface.\n"); goto out_bad_resource; } if (handle_type != DRM_VMW_HANDLE_PRIME) { user_srf = container_of(base, struct vmw_user_surface, prime.base); /* * Make sure the surface creator has the same * authenticating master, or is already registered with us. */ if (drm_is_primary_client(file_priv) && user_srf->master != file_priv->master) require_exist = true; ret = ttm_ref_object_add(tfile, base, TTM_REF_USAGE, NULL, require_exist); if (unlikely(ret != 0)) { DRM_ERROR("Could not add a reference to a surface.\n"); goto out_bad_resource; } } *base_p = base; return 0; out_bad_resource: ttm_base_object_unref(&base); out_no_lookup: if (handle_type == DRM_VMW_HANDLE_PRIME) (void) ttm_ref_object_base_unref(tfile, handle, TTM_REF_USAGE); return ret; } /** * vmw_user_surface_define_ioctl - Ioctl function implementing * the user surface reference functionality. * * @dev: Pointer to a struct drm_device. * @data: Pointer to data copied from / to user-space. * @file_priv: Pointer to a drm file private structure. */ int vmw_surface_reference_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); union drm_vmw_surface_reference_arg *arg = (union drm_vmw_surface_reference_arg *)data; struct drm_vmw_surface_arg *req = &arg->req; struct drm_vmw_surface_create_req *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; struct vmw_surface *srf; struct vmw_user_surface *user_srf; struct drm_vmw_size __user *user_sizes; struct ttm_base_object *base; int ret; ret = vmw_surface_handle_reference(dev_priv, file_priv, req->sid, req->handle_type, &base); if (unlikely(ret != 0)) return ret; user_srf = container_of(base, struct vmw_user_surface, prime.base); srf = &user_srf->srf; rep->flags = srf->flags; rep->format = srf->format; memcpy(rep->mip_levels, srf->mip_levels, sizeof(srf->mip_levels)); user_sizes = (struct drm_vmw_size __user *)(unsigned long) rep->size_addr; if (user_sizes) ret = copy_to_user(user_sizes, &srf->base_size, sizeof(srf->base_size)); if (unlikely(ret != 0)) { DRM_ERROR("copy_to_user failed %p %u\n", user_sizes, srf->num_sizes); ttm_ref_object_base_unref(tfile, base->hash.key, TTM_REF_USAGE); ret = -EFAULT; } ttm_base_object_unref(&base); return ret; } /** * vmw_surface_define_encode - Encode a surface_define command. * * @srf: Pointer to a struct vmw_surface object. * @cmd_space: Pointer to memory area in which the commands should be encoded. */ static int vmw_gb_surface_create(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; struct vmw_surface *srf = vmw_res_to_srf(res); uint32_t cmd_len, cmd_id, submit_len; int ret; struct { SVGA3dCmdHeader header; SVGA3dCmdDefineGBSurface body; } *cmd; struct { SVGA3dCmdHeader header; SVGA3dCmdDefineGBSurface_v2 body; } *cmd2; if (likely(res->id != -1)) return 0; vmw_fifo_resource_inc(dev_priv); ret = vmw_resource_alloc_id(res); if (unlikely(ret != 0)) { DRM_ERROR("Failed to allocate a surface id.\n"); goto out_no_id; } if (unlikely(res->id >= VMWGFX_NUM_GB_SURFACE)) { ret = -EBUSY; goto out_no_fifo; } if (srf->array_size > 0) { /* has_dx checked on creation time. */ cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE_V2; cmd_len = sizeof(cmd2->body); submit_len = sizeof(*cmd2); } else { cmd_id = SVGA_3D_CMD_DEFINE_GB_SURFACE; cmd_len = sizeof(cmd->body); submit_len = sizeof(*cmd); } cmd = vmw_fifo_reserve(dev_priv, submit_len); cmd2 = (typeof(cmd2))cmd; if (unlikely(!cmd)) { DRM_ERROR("Failed reserving FIFO space for surface " "creation.\n"); ret = -ENOMEM; goto out_no_fifo; } if (srf->array_size > 0) { cmd2->header.id = cmd_id; cmd2->header.size = cmd_len; cmd2->body.sid = srf->res.id; cmd2->body.surfaceFlags = srf->flags; cmd2->body.format = cpu_to_le32(srf->format); cmd2->body.numMipLevels = srf->mip_levels[0]; cmd2->body.multisampleCount = srf->multisample_count; cmd2->body.autogenFilter = srf->autogen_filter; cmd2->body.size.width = srf->base_size.width; cmd2->body.size.height = srf->base_size.height; cmd2->body.size.depth = srf->base_size.depth; cmd2->body.arraySize = srf->array_size; } else { cmd->header.id = cmd_id; cmd->header.size = cmd_len; cmd->body.sid = srf->res.id; cmd->body.surfaceFlags = srf->flags; cmd->body.format = cpu_to_le32(srf->format); cmd->body.numMipLevels = srf->mip_levels[0]; cmd->body.multisampleCount = srf->multisample_count; cmd->body.autogenFilter = srf->autogen_filter; cmd->body.size.width = srf->base_size.width; cmd->body.size.height = srf->base_size.height; cmd->body.size.depth = srf->base_size.depth; } vmw_fifo_commit(dev_priv, submit_len); return 0; out_no_fifo: vmw_resource_release_id(res); out_no_id: vmw_fifo_resource_dec(dev_priv); return ret; } static int vmw_gb_surface_bind(struct vmw_resource *res, struct ttm_validate_buffer *val_buf) { struct vmw_private *dev_priv = res->dev_priv; struct { SVGA3dCmdHeader header; SVGA3dCmdBindGBSurface body; } *cmd1; struct { SVGA3dCmdHeader header; SVGA3dCmdUpdateGBSurface body; } *cmd2; uint32_t submit_size; struct ttm_buffer_object *bo = val_buf->bo; BUG_ON(bo->mem.mem_type != VMW_PL_MOB); submit_size = sizeof(*cmd1) + (res->backup_dirty ? sizeof(*cmd2) : 0); cmd1 = vmw_fifo_reserve(dev_priv, submit_size); if (unlikely(!cmd1)) { DRM_ERROR("Failed reserving FIFO space for surface " "binding.\n"); return -ENOMEM; } cmd1->header.id = SVGA_3D_CMD_BIND_GB_SURFACE; cmd1->header.size = sizeof(cmd1->body); cmd1->body.sid = res->id; cmd1->body.mobid = bo->mem.start; if (res->backup_dirty) { cmd2 = (void *) &cmd1[1]; cmd2->header.id = SVGA_3D_CMD_UPDATE_GB_SURFACE; cmd2->header.size = sizeof(cmd2->body); cmd2->body.sid = res->id; res->backup_dirty = false; } vmw_fifo_commit(dev_priv, submit_size); return 0; } static int vmw_gb_surface_unbind(struct vmw_resource *res, bool readback, struct ttm_validate_buffer *val_buf) { struct vmw_private *dev_priv = res->dev_priv; struct ttm_buffer_object *bo = val_buf->bo; struct vmw_fence_obj *fence; struct { SVGA3dCmdHeader header; SVGA3dCmdReadbackGBSurface body; } *cmd1; struct { SVGA3dCmdHeader header; SVGA3dCmdInvalidateGBSurface body; } *cmd2; struct { SVGA3dCmdHeader header; SVGA3dCmdBindGBSurface body; } *cmd3; uint32_t submit_size; uint8_t *cmd; BUG_ON(bo->mem.mem_type != VMW_PL_MOB); submit_size = sizeof(*cmd3) + (readback ? sizeof(*cmd1) : sizeof(*cmd2)); cmd = vmw_fifo_reserve(dev_priv, submit_size); if (unlikely(!cmd)) { DRM_ERROR("Failed reserving FIFO space for surface " "unbinding.\n"); return -ENOMEM; } if (readback) { cmd1 = (void *) cmd; cmd1->header.id = SVGA_3D_CMD_READBACK_GB_SURFACE; cmd1->header.size = sizeof(cmd1->body); cmd1->body.sid = res->id; cmd3 = (void *) &cmd1[1]; } else { cmd2 = (void *) cmd; cmd2->header.id = SVGA_3D_CMD_INVALIDATE_GB_SURFACE; cmd2->header.size = sizeof(cmd2->body); cmd2->body.sid = res->id; cmd3 = (void *) &cmd2[1]; } cmd3->header.id = SVGA_3D_CMD_BIND_GB_SURFACE; cmd3->header.size = sizeof(cmd3->body); cmd3->body.sid = res->id; cmd3->body.mobid = SVGA3D_INVALID_ID; vmw_fifo_commit(dev_priv, submit_size); /* * Create a fence object and fence the backup buffer. */ (void) vmw_execbuf_fence_commands(NULL, dev_priv, &fence, NULL); vmw_fence_single_bo(val_buf->bo, fence); if (likely(fence != NULL)) vmw_fence_obj_unreference(&fence); return 0; } static int vmw_gb_surface_destroy(struct vmw_resource *res) { struct vmw_private *dev_priv = res->dev_priv; struct vmw_surface *srf = vmw_res_to_srf(res); struct { SVGA3dCmdHeader header; SVGA3dCmdDestroyGBSurface body; } *cmd; if (likely(res->id == -1)) return 0; mutex_lock(&dev_priv->binding_mutex); vmw_view_surface_list_destroy(dev_priv, &srf->view_list); vmw_binding_res_list_scrub(&res->binding_head); cmd = vmw_fifo_reserve(dev_priv, sizeof(*cmd)); if (unlikely(!cmd)) { DRM_ERROR("Failed reserving FIFO space for surface " "destruction.\n"); mutex_unlock(&dev_priv->binding_mutex); return -ENOMEM; } cmd->header.id = SVGA_3D_CMD_DESTROY_GB_SURFACE; cmd->header.size = sizeof(cmd->body); cmd->body.sid = res->id; vmw_fifo_commit(dev_priv, sizeof(*cmd)); mutex_unlock(&dev_priv->binding_mutex); vmw_resource_release_id(res); vmw_fifo_resource_dec(dev_priv); return 0; } /** * vmw_gb_surface_define_ioctl - Ioctl function implementing * the user surface define functionality. * * @dev: Pointer to a struct drm_device. * @data: Pointer to data copied from / to user-space. * @file_priv: Pointer to a drm file private structure. */ int vmw_gb_surface_define_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; struct vmw_resource *res; struct vmw_resource *tmp; union drm_vmw_gb_surface_create_arg *arg = (union drm_vmw_gb_surface_create_arg *)data; struct drm_vmw_gb_surface_create_req *req = &arg->req; struct drm_vmw_gb_surface_create_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; int ret; uint32_t size; uint32_t backup_handle = 0; if (req->multisample_count != 0) return -EINVAL; if (req->mip_levels > DRM_VMW_MAX_MIP_LEVELS) return -EINVAL; if (unlikely(vmw_user_surface_size == 0)) vmw_user_surface_size = ttm_round_pot(sizeof(*user_srf)) + 128; size = vmw_user_surface_size + 128; /* Define a surface based on the parameters. */ ret = vmw_surface_gb_priv_define(dev, size, req->svga3d_flags, req->format, req->drm_surface_flags & drm_vmw_surface_flag_scanout, req->mip_levels, req->multisample_count, req->array_size, req->base_size, &srf); if (unlikely(ret != 0)) return ret; user_srf = container_of(srf, struct vmw_user_surface, srf); if (drm_is_primary_client(file_priv)) user_srf->master = drm_master_get(file_priv->master); ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; res = &user_srf->srf.res; if (req->buffer_handle != SVGA3D_INVALID_ID) { ret = vmw_user_dmabuf_lookup(tfile, req->buffer_handle, &res->backup, &user_srf->backup_base); if (ret == 0) { if (res->backup->base.num_pages * PAGE_SIZE < res->backup_size) { DRM_ERROR("Surface backup buffer is too small.\n"); vmw_dmabuf_unreference(&res->backup); ret = -EINVAL; goto out_unlock; } else { backup_handle = req->buffer_handle; } } } else if (req->drm_surface_flags & drm_vmw_surface_flag_create_buffer) ret = vmw_user_dmabuf_alloc(dev_priv, tfile, res->backup_size, req->drm_surface_flags & drm_vmw_surface_flag_shareable, &backup_handle, &res->backup, &user_srf->backup_base); if (unlikely(ret != 0)) { vmw_resource_unreference(&res); goto out_unlock; } tmp = vmw_resource_reference(res); ret = ttm_prime_object_init(tfile, res->backup_size, &user_srf->prime, req->drm_surface_flags & drm_vmw_surface_flag_shareable, VMW_RES_SURFACE, &vmw_user_surface_base_release, NULL); if (unlikely(ret != 0)) { vmw_resource_unreference(&tmp); vmw_resource_unreference(&res); goto out_unlock; } rep->handle = user_srf->prime.base.hash.key; rep->backup_size = res->backup_size; if (res->backup) { rep->buffer_map_handle = drm_vma_node_offset_addr(&res->backup->base.vma_node); rep->buffer_size = res->backup->base.num_pages * PAGE_SIZE; rep->buffer_handle = backup_handle; } else { rep->buffer_map_handle = 0; rep->buffer_size = 0; rep->buffer_handle = SVGA3D_INVALID_ID; } vmw_resource_unreference(&res); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; } /** * vmw_gb_surface_reference_ioctl - Ioctl function implementing * the user surface reference functionality. * * @dev: Pointer to a struct drm_device. * @data: Pointer to data copied from / to user-space. * @file_priv: Pointer to a drm file private structure. */ int vmw_gb_surface_reference_ioctl(struct drm_device *dev, void *data, struct drm_file *file_priv) { struct vmw_private *dev_priv = vmw_priv(dev); union drm_vmw_gb_surface_reference_arg *arg = (union drm_vmw_gb_surface_reference_arg *)data; struct drm_vmw_surface_arg *req = &arg->req; struct drm_vmw_gb_surface_ref_rep *rep = &arg->rep; struct ttm_object_file *tfile = vmw_fpriv(file_priv)->tfile; struct vmw_surface *srf; struct vmw_user_surface *user_srf; struct ttm_base_object *base; uint32_t backup_handle; int ret = -EINVAL; ret = vmw_surface_handle_reference(dev_priv, file_priv, req->sid, req->handle_type, &base); if (unlikely(ret != 0)) return ret; user_srf = container_of(base, struct vmw_user_surface, prime.base); srf = &user_srf->srf; if (!srf->res.backup) { DRM_ERROR("Shared GB surface is missing a backup buffer.\n"); goto out_bad_resource; } mutex_lock(&dev_priv->cmdbuf_mutex); /* Protect res->backup */ ret = vmw_user_dmabuf_reference(tfile, srf->res.backup, &backup_handle); mutex_unlock(&dev_priv->cmdbuf_mutex); if (unlikely(ret != 0)) { DRM_ERROR("Could not add a reference to a GB surface " "backup buffer.\n"); (void) ttm_ref_object_base_unref(tfile, base->hash.key, TTM_REF_USAGE); goto out_bad_resource; } rep->creq.svga3d_flags = srf->flags; rep->creq.format = srf->format; rep->creq.mip_levels = srf->mip_levels[0]; rep->creq.drm_surface_flags = 0; rep->creq.multisample_count = srf->multisample_count; rep->creq.autogen_filter = srf->autogen_filter; rep->creq.array_size = srf->array_size; rep->creq.buffer_handle = backup_handle; rep->creq.base_size = srf->base_size; rep->crep.handle = user_srf->prime.base.hash.key; rep->crep.backup_size = srf->res.backup_size; rep->crep.buffer_handle = backup_handle; rep->crep.buffer_map_handle = drm_vma_node_offset_addr(&srf->res.backup->base.vma_node); rep->crep.buffer_size = srf->res.backup->base.num_pages * PAGE_SIZE; out_bad_resource: ttm_base_object_unref(&base); return ret; } /** * vmw_surface_gb_priv_define - Define a private GB surface * * @dev: Pointer to a struct drm_device * @user_accounting_size: Used to track user-space memory usage, set * to 0 for kernel mode only memory * @svga3d_flags: SVGA3d surface flags for the device * @format: requested surface format * @for_scanout: true if inteded to be used for scanout buffer * @num_mip_levels: number of MIP levels * @multisample_count: * @array_size: Surface array size. * @size: width, heigh, depth of the surface requested * @user_srf_out: allocated user_srf. Set to NULL on failure. * * GB surfaces allocated by this function will not have a user mode handle, and * thus will only be visible to vmwgfx. For optimization reasons the * surface may later be given a user mode handle by another function to make * it available to user mode drivers. */ int vmw_surface_gb_priv_define(struct drm_device *dev, uint32_t user_accounting_size, uint32_t svga3d_flags, SVGA3dSurfaceFormat format, bool for_scanout, uint32_t num_mip_levels, uint32_t multisample_count, uint32_t array_size, struct drm_vmw_size size, struct vmw_surface **srf_out) { struct vmw_private *dev_priv = vmw_priv(dev); struct vmw_user_surface *user_srf; struct vmw_surface *srf; int ret; u32 num_layers; *srf_out = NULL; if (for_scanout) { uint32_t max_width, max_height; if (!svga3dsurface_is_screen_target_format(format)) { DRM_ERROR("Invalid Screen Target surface format."); return -EINVAL; } max_width = min(dev_priv->texture_max_width, dev_priv->stdu_max_width); max_height = min(dev_priv->texture_max_height, dev_priv->stdu_max_height); if (size.width > max_width || size.height > max_height) { DRM_ERROR("%ux%u\n, exeeds max surface size %ux%u", size.width, size.height, max_width, max_height); return -EINVAL; } } else { const struct svga3d_surface_desc *desc; desc = svga3dsurface_get_desc(format); if (unlikely(desc->block_desc == SVGA3DBLOCKDESC_NONE)) { DRM_ERROR("Invalid surface format.\n"); return -EINVAL; } } /* array_size must be null for non-GL3 host. */ if (array_size > 0 && !dev_priv->has_dx) { DRM_ERROR("Tried to create DX surface on non-DX host.\n"); return -EINVAL; } ret = ttm_read_lock(&dev_priv->reservation_sem, true); if (unlikely(ret != 0)) return ret; ret = ttm_mem_global_alloc(vmw_mem_glob(dev_priv), user_accounting_size, false, true); if (unlikely(ret != 0)) { if (ret != -ERESTARTSYS) DRM_ERROR("Out of graphics memory for surface" " creation.\n"); goto out_unlock; } user_srf = kzalloc(sizeof(*user_srf), GFP_KERNEL); if (unlikely(!user_srf)) { ret = -ENOMEM; goto out_no_user_srf; } *srf_out = &user_srf->srf; user_srf->size = user_accounting_size; user_srf->prime.base.shareable = false; user_srf->prime.base.tfile = NULL; srf = &user_srf->srf; srf->flags = svga3d_flags; srf->format = format; srf->scanout = for_scanout; srf->mip_levels[0] = num_mip_levels; srf->num_sizes = 1; srf->sizes = NULL; srf->offsets = NULL; srf->base_size = size; srf->autogen_filter = SVGA3D_TEX_FILTER_NONE; srf->array_size = array_size; srf->multisample_count = multisample_count; if (array_size) num_layers = array_size; else if (svga3d_flags & SVGA3D_SURFACE_CUBEMAP) num_layers = SVGA3D_MAX_SURFACE_FACES; else num_layers = 1; srf->res.backup_size = svga3dsurface_get_serialized_size(srf->format, srf->base_size, srf->mip_levels[0], num_layers); if (srf->flags & SVGA3D_SURFACE_BIND_STREAM_OUTPUT) srf->res.backup_size += sizeof(SVGA3dDXSOState); if (dev_priv->active_display_unit == vmw_du_screen_target && for_scanout) srf->flags |= SVGA3D_SURFACE_SCREENTARGET; /* * From this point, the generic resource management functions * destroy the object on failure. */ ret = vmw_surface_init(dev_priv, srf, vmw_user_surface_free); ttm_read_unlock(&dev_priv->reservation_sem); return ret; out_no_user_srf: ttm_mem_global_free(vmw_mem_glob(dev_priv), user_accounting_size); out_unlock: ttm_read_unlock(&dev_priv->reservation_sem); return ret; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3401_0
crossvul-cpp_data_bad_432_0
/* linux/drivers/cdrom/cdrom.c Copyright (c) 1996, 1997 David A. van Leeuwen. Copyright (c) 1997, 1998 Erik Andersen <andersee@debian.org> Copyright (c) 1998, 1999 Jens Axboe <axboe@image.dk> May be copied or modified under the terms of the GNU General Public License. See linux/COPYING for more information. Uniform CD-ROM driver for Linux. See Documentation/cdrom/cdrom-standard.tex for usage information. The routines in the file provide a uniform interface between the software that uses CD-ROMs and the various low-level drivers that actually talk to the hardware. Suggestions are welcome. Patches that work are more welcome though. ;-) To Do List: ---------------------------------- -- Modify sysctl/proc interface. I plan on having one directory per drive, with entries for outputing general drive information, and sysctl based tunable parameters such as whether the tray should auto-close for that drive. Suggestions (or patches) for this welcome! Revision History ---------------------------------- 1.00 Date Unknown -- David van Leeuwen <david@tm.tno.nl> -- Initial version by David A. van Leeuwen. I don't have a detailed changelog for the 1.x series, David? 2.00 Dec 2, 1997 -- Erik Andersen <andersee@debian.org> -- New maintainer! As David A. van Leeuwen has been too busy to actively maintain and improve this driver, I am now carrying on the torch. If you have a problem with this driver, please feel free to contact me. -- Added (rudimentary) sysctl interface. I realize this is really weak right now, and is _very_ badly implemented. It will be improved... -- Modified CDROM_DISC_STATUS so that it is now incorporated into the Uniform CD-ROM driver via the cdrom_count_tracks function. The cdrom_count_tracks function helps resolve some of the false assumptions of the CDROM_DISC_STATUS ioctl, and is also used to check for the correct media type when mounting or playing audio from a CD. -- Remove the calls to verify_area and only use the copy_from_user and copy_to_user stuff, since these calls now provide their own memory checking with the 2.1.x kernels. -- Major update to return codes so that errors from low-level drivers are passed on through (thanks to Gerd Knorr for pointing out this problem). -- Made it so if a function isn't implemented in a low-level driver, ENOSYS is now returned instead of EINVAL. -- Simplified some complex logic so that the source code is easier to read. -- Other stuff I probably forgot to mention (lots of changes). 2.01 to 2.11 Dec 1997-Jan 1998 -- TO-DO! Write changelogs for 2.01 to 2.12. 2.12 Jan 24, 1998 -- Erik Andersen <andersee@debian.org> -- Fixed a bug in the IOCTL_IN and IOCTL_OUT macros. It turns out that copy_*_user does not return EFAULT on error, but instead returns the number of bytes not copied. I was returning whatever non-zero stuff came back from the copy_*_user functions directly, which would result in strange errors. 2.13 July 17, 1998 -- Erik Andersen <andersee@debian.org> -- Fixed a bug in CDROM_SELECT_SPEED where you couldn't lower the speed of the drive. Thanks to Tobias Ringstr|m <tori@prosolvia.se> for pointing this out and providing a simple fix. -- Fixed the procfs-unload-module bug with the fill_inode procfs callback. thanks to Andrea Arcangeli -- Fixed it so that the /proc entry now also shows up when cdrom is compiled into the kernel. Before it only worked when loaded as a module. 2.14 August 17, 1998 -- Erik Andersen <andersee@debian.org> -- Fixed a bug in cdrom_media_changed and handling of reporting that the media had changed for devices that _don't_ implement media_changed. Thanks to Grant R. Guenther <grant@torque.net> for spotting this bug. -- Made a few things more pedanticly correct. 2.50 Oct 19, 1998 - Jens Axboe <axboe@image.dk> -- New maintainers! Erik was too busy to continue the work on the driver, so now Chris Zwilling <chris@cloudnet.com> and Jens Axboe <axboe@image.dk> will do their best to follow in his footsteps 2.51 Dec 20, 1998 - Jens Axboe <axboe@image.dk> -- Check if drive is capable of doing what we ask before blindly changing cdi->options in various ioctl. -- Added version to proc entry. 2.52 Jan 16, 1999 - Jens Axboe <axboe@image.dk> -- Fixed an error in open_for_data where we would sometimes not return the correct error value. Thanks Huba Gaspar <huba@softcell.hu>. -- Fixed module usage count - usage was based on /proc/sys/dev instead of /proc/sys/dev/cdrom. This could lead to an oops when other modules had entries in dev. Feb 02 - real bug was in sysctl.c where dev would be removed even though it was used. cdrom.c just illuminated that bug. 2.53 Feb 22, 1999 - Jens Axboe <axboe@image.dk> -- Fixup of several ioctl calls, in particular CDROM_SET_OPTIONS has been "rewritten" because capabilities and options aren't in sync. They should be... -- Added CDROM_LOCKDOOR ioctl. Locks the door and keeps it that way. -- Added CDROM_RESET ioctl. -- Added CDROM_DEBUG ioctl. Enable debug messages on-the-fly. -- Added CDROM_GET_CAPABILITY ioctl. This relieves userspace programs from parsing /proc/sys/dev/cdrom/info. 2.54 Mar 15, 1999 - Jens Axboe <axboe@image.dk> -- Check capability mask from low level driver when counting tracks as per suggestion from Corey J. Scotts <cstotts@blue.weeg.uiowa.edu>. 2.55 Apr 25, 1999 - Jens Axboe <axboe@image.dk> -- autoclose was mistakenly checked against CDC_OPEN_TRAY instead of CDC_CLOSE_TRAY. -- proc info didn't mask against capabilities mask. 3.00 Aug 5, 1999 - Jens Axboe <axboe@image.dk> -- Unified audio ioctl handling across CD-ROM drivers. A lot of the code was duplicated before. Drives that support the generic packet interface are now being fed packets from here instead. -- First attempt at adding support for MMC2 commands - for DVD and CD-R(W) drives. Only the DVD parts are in now - the interface used is the same as for the audio ioctls. -- ioctl cleanups. if a drive couldn't play audio, it didn't get a change to perform device specific ioctls as well. -- Defined CDROM_CAN(CDC_XXX) for checking the capabilities. -- Put in sysctl files for autoclose, autoeject, check_media, debug, and lock. -- /proc/sys/dev/cdrom/info has been updated to also contain info about CD-Rx and DVD capabilities. -- Now default to checking media type. -- CDROM_SEND_PACKET ioctl added. The infrastructure was in place for doing this anyway, with the generic_packet addition. 3.01 Aug 6, 1999 - Jens Axboe <axboe@image.dk> -- Fix up the sysctl handling so that the option flags get set correctly. -- Fix up ioctl handling so the device specific ones actually get called :). 3.02 Aug 8, 1999 - Jens Axboe <axboe@image.dk> -- Fixed volume control on SCSI drives (or others with longer audio page). -- Fixed a couple of DVD minors. Thanks to Andrew T. Veliath <andrewtv@usa.net> for telling me and for having defined the various DVD structures and ioctls in the first place! He designed the original DVD patches for ide-cd and while I rearranged and unified them, the interface is still the same. 3.03 Sep 1, 1999 - Jens Axboe <axboe@image.dk> -- Moved the rest of the audio ioctls from the CD-ROM drivers here. Only CDROMREADTOCENTRY and CDROMREADTOCHDR are left. -- Moved the CDROMREADxxx ioctls in here. -- Defined the cdrom_get_last_written and cdrom_get_next_block as ioctls and exported functions. -- Erik Andersen <andersen@xmission.com> modified all SCMD_ commands to now read GPCMD_ for the new generic packet interface. All low level drivers are updated as well. -- Various other cleanups. 3.04 Sep 12, 1999 - Jens Axboe <axboe@image.dk> -- Fixed a couple of possible memory leaks (if an operation failed and we didn't free the buffer before returning the error). -- Integrated Uniform CD Changer handling from Richard Sharman <rsharman@pobox.com>. -- Defined CD_DVD and CD_CHANGER log levels. -- Fixed the CDROMREADxxx ioctls. -- CDROMPLAYTRKIND uses the GPCMD_PLAY_AUDIO_MSF command - too few drives supported it. We lose the index part, however. -- Small modifications to accommodate opens of /dev/hdc1, required for ide-cd to handle multisession discs. -- Export cdrom_mode_sense and cdrom_mode_select. -- init_cdrom_command() for setting up a cgc command. 3.05 Oct 24, 1999 - Jens Axboe <axboe@image.dk> -- Changed the interface for CDROM_SEND_PACKET. Before it was virtually impossible to send the drive data in a sensible way. -- Lowered stack usage in mmc_ioctl(), dvd_read_disckey(), and dvd_read_manufact. -- Added setup of write mode for packet writing. -- Fixed CDDA ripping with cdda2wav - accept much larger requests of number of frames and split the reads in blocks of 8. 3.06 Dec 13, 1999 - Jens Axboe <axboe@image.dk> -- Added support for changing the region of DVD drives. -- Added sense data to generic command. 3.07 Feb 2, 2000 - Jens Axboe <axboe@suse.de> -- Do same "read header length" trick in cdrom_get_disc_info() as we do in cdrom_get_track_info() -- some drive don't obey specs and fail if they can't supply the full Mt Fuji size table. -- Deleted stuff related to setting up write modes. It has a different home now. -- Clear header length in mode_select unconditionally. -- Removed the register_disk() that was added, not needed here. 3.08 May 1, 2000 - Jens Axboe <axboe@suse.de> -- Fix direction flag in setup_send_key and setup_report_key. This gave some SCSI adapters problems. -- Always return -EROFS for write opens -- Convert to module_init/module_exit style init and remove some of the #ifdef MODULE stuff -- Fix several dvd errors - DVD_LU_SEND_ASF should pass agid, DVD_HOST_SEND_RPC_STATE did not set buffer size in cdb, and dvd_do_auth passed uninitialized data to drive because init_cdrom_command did not clear a 0 sized buffer. 3.09 May 12, 2000 - Jens Axboe <axboe@suse.de> -- Fix Video-CD on SCSI drives that don't support READ_CD command. In that case switch block size and issue plain READ_10 again, then switch back. 3.10 Jun 10, 2000 - Jens Axboe <axboe@suse.de> -- Fix volume control on CD's - old SCSI-II drives now use their own code, as doing MODE6 stuff in here is really not my intention. -- Use READ_DISC_INFO for more reliable end-of-disc. 3.11 Jun 12, 2000 - Jens Axboe <axboe@suse.de> -- Fix bug in getting rpc phase 2 region info. -- Reinstate "correct" CDROMPLAYTRKIND 3.12 Oct 18, 2000 - Jens Axboe <axboe@suse.de> -- Use quiet bit on packet commands not known to work 3.20 Dec 17, 2003 - Jens Axboe <axboe@suse.de> -- Various fixes and lots of cleanups not listed :-) -- Locking fixes -- Mt Rainier support -- DVD-RAM write open fixes Nov 5 2001, Aug 8 2002. Modified by Andy Polyakov <appro@fy.chalmers.se> to support MMC-3 compliant DVD+RW units. Modified by Nigel Kukard <nkukard@lbsd.net> - support DVD+RW 2.4.x patch by Andy Polyakov <appro@fy.chalmers.se> -------------------------------------------------------------------------*/ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define REVISION "Revision: 3.20" #define VERSION "Id: cdrom.c 3.20 2003/12/17" /* I use an error-log mask to give fine grain control over the type of messages dumped to the system logs. The available masks include: */ #define CD_NOTHING 0x0 #define CD_WARNING 0x1 #define CD_REG_UNREG 0x2 #define CD_DO_IOCTL 0x4 #define CD_OPEN 0x8 #define CD_CLOSE 0x10 #define CD_COUNT_TRACKS 0x20 #define CD_CHANGER 0x40 #define CD_DVD 0x80 /* Define this to remove _all_ the debugging messages */ /* #define ERRLOGMASK CD_NOTHING */ #define ERRLOGMASK CD_WARNING /* #define ERRLOGMASK (CD_WARNING|CD_OPEN|CD_COUNT_TRACKS|CD_CLOSE) */ /* #define ERRLOGMASK (CD_WARNING|CD_REG_UNREG|CD_DO_IOCTL|CD_OPEN|CD_CLOSE|CD_COUNT_TRACKS) */ #include <linux/module.h> #include <linux/fs.h> #include <linux/major.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/slab.h> #include <linux/cdrom.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include <linux/blkpg.h> #include <linux/init.h> #include <linux/fcntl.h> #include <linux/blkdev.h> #include <linux/times.h> #include <linux/uaccess.h> #include <scsi/scsi_common.h> #include <scsi/scsi_request.h> /* used to tell the module to turn on full debugging messages */ static bool debug; /* default compatibility mode */ static bool autoclose=1; static bool autoeject; static bool lockdoor = 1; /* will we ever get to use this... sigh. */ static bool check_media_type; /* automatically restart mrw format */ static bool mrw_format_restart = 1; module_param(debug, bool, 0); module_param(autoclose, bool, 0); module_param(autoeject, bool, 0); module_param(lockdoor, bool, 0); module_param(check_media_type, bool, 0); module_param(mrw_format_restart, bool, 0); static DEFINE_MUTEX(cdrom_mutex); static const char *mrw_format_status[] = { "not mrw", "bgformat inactive", "bgformat active", "mrw complete", }; static const char *mrw_address_space[] = { "DMA", "GAA" }; #if (ERRLOGMASK != CD_NOTHING) #define cd_dbg(type, fmt, ...) \ do { \ if ((ERRLOGMASK & type) || debug == 1) \ pr_debug(fmt, ##__VA_ARGS__); \ } while (0) #else #define cd_dbg(type, fmt, ...) \ do { \ if (0 && (ERRLOGMASK & type) || debug == 1) \ pr_debug(fmt, ##__VA_ARGS__); \ } while (0) #endif /* The (cdo->capability & ~cdi->mask & CDC_XXX) construct was used in a lot of places. This macro makes the code more clear. */ #define CDROM_CAN(type) (cdi->ops->capability & ~cdi->mask & (type)) /* * Another popular OS uses 7 seconds as the hard timeout for default * commands, so it is a good choice for us as well. */ #define CDROM_DEF_TIMEOUT (7 * HZ) /* Not-exported routines. */ static void cdrom_sysctl_register(void); static LIST_HEAD(cdrom_list); int cdrom_dummy_generic_packet(struct cdrom_device_info *cdi, struct packet_command *cgc) { if (cgc->sshdr) { cgc->sshdr->sense_key = 0x05; cgc->sshdr->asc = 0x20; cgc->sshdr->ascq = 0x00; } cgc->stat = -EIO; return -EIO; } EXPORT_SYMBOL(cdrom_dummy_generic_packet); static int cdrom_flush_cache(struct cdrom_device_info *cdi) { struct packet_command cgc; init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_FLUSH_CACHE; cgc.timeout = 5 * 60 * HZ; return cdi->ops->generic_packet(cdi, &cgc); } /* requires CD R/RW */ static int cdrom_get_disc_info(struct cdrom_device_info *cdi, disc_information *di) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; int ret, buflen; /* set up command and get the disc info */ init_cdrom_command(&cgc, di, sizeof(*di), CGC_DATA_READ); cgc.cmd[0] = GPCMD_READ_DISC_INFO; cgc.cmd[8] = cgc.buflen = 2; cgc.quiet = 1; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; /* not all drives have the same disc_info length, so requeue * packet with the length the drive tells us it can supply */ buflen = be16_to_cpu(di->disc_information_length) + sizeof(di->disc_information_length); if (buflen > sizeof(disc_information)) buflen = sizeof(disc_information); cgc.cmd[8] = cgc.buflen = buflen; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; /* return actual fill size */ return buflen; } /* This macro makes sure we don't have to check on cdrom_device_ops * existence in the run-time routines below. Change_capability is a * hack to have the capability flags defined const, while we can still * change it here without gcc complaining at every line. */ #define ENSURE(call, bits) \ do { \ if (cdo->call == NULL) \ *change_capability &= ~(bits); \ } while (0) /* * the first prototypes used 0x2c as the page code for the mrw mode page, * subsequently this was changed to 0x03. probe the one used by this drive */ static int cdrom_mrw_probe_pc(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[16]; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.timeout = HZ; cgc.quiet = 1; if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC, 0)) { cdi->mrw_mode_page = MRW_MODE_PC; return 0; } else if (!cdrom_mode_sense(cdi, &cgc, MRW_MODE_PC_PRE1, 0)) { cdi->mrw_mode_page = MRW_MODE_PC_PRE1; return 0; } return 1; } static int cdrom_is_mrw(struct cdrom_device_info *cdi, int *write) { struct packet_command cgc; struct mrw_feature_desc *mfd; unsigned char buffer[16]; int ret; *write = 0; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; cgc.cmd[3] = CDF_MRW; cgc.cmd[8] = sizeof(buffer); cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) return ret; mfd = (struct mrw_feature_desc *)&buffer[sizeof(struct feature_header)]; if (be16_to_cpu(mfd->feature_code) != CDF_MRW) return 1; *write = mfd->write; if ((ret = cdrom_mrw_probe_pc(cdi))) { *write = 0; return ret; } return 0; } static int cdrom_mrw_bgformat(struct cdrom_device_info *cdi, int cont) { struct packet_command cgc; unsigned char buffer[12]; int ret; pr_info("%sstarting format\n", cont ? "Re" : ""); /* * FmtData bit set (bit 4), format type is 1 */ init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_WRITE); cgc.cmd[0] = GPCMD_FORMAT_UNIT; cgc.cmd[1] = (1 << 4) | 1; cgc.timeout = 5 * 60 * HZ; /* * 4 byte format list header, 8 byte format list descriptor */ buffer[1] = 1 << 1; buffer[3] = 8; /* * nr_blocks field */ buffer[4] = 0xff; buffer[5] = 0xff; buffer[6] = 0xff; buffer[7] = 0xff; buffer[8] = 0x24 << 2; buffer[11] = cont; ret = cdi->ops->generic_packet(cdi, &cgc); if (ret) pr_info("bgformat failed\n"); return ret; } static int cdrom_mrw_bgformat_susp(struct cdrom_device_info *cdi, int immed) { struct packet_command cgc; init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_CLOSE_TRACK; /* * Session = 1, Track = 0 */ cgc.cmd[1] = !!immed; cgc.cmd[2] = 1 << 1; cgc.timeout = 5 * 60 * HZ; return cdi->ops->generic_packet(cdi, &cgc); } static int cdrom_mrw_exit(struct cdrom_device_info *cdi) { disc_information di; int ret; ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < (int)offsetof(typeof(di),disc_type)) return 1; ret = 0; if (di.mrw_status == CDM_MRW_BGFORMAT_ACTIVE) { pr_info("issuing MRW background format suspend\n"); ret = cdrom_mrw_bgformat_susp(cdi, 0); } if (!ret && cdi->media_written) ret = cdrom_flush_cache(cdi); return ret; } static int cdrom_mrw_set_lba_space(struct cdrom_device_info *cdi, int space) { struct packet_command cgc; struct mode_page_header *mph; char buffer[16]; int ret, offset, size; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.buffer = buffer; cgc.buflen = sizeof(buffer); ret = cdrom_mode_sense(cdi, &cgc, cdi->mrw_mode_page, 0); if (ret) return ret; mph = (struct mode_page_header *)buffer; offset = be16_to_cpu(mph->desc_length); size = be16_to_cpu(mph->mode_data_length) + 2; buffer[offset + 3] = space; cgc.buflen = size; ret = cdrom_mode_select(cdi, &cgc); if (ret) return ret; pr_info("%s: mrw address space %s selected\n", cdi->name, mrw_address_space[space]); return 0; } int register_cdrom(struct cdrom_device_info *cdi) { static char banner_printed; const struct cdrom_device_ops *cdo = cdi->ops; int *change_capability = (int *)&cdo->capability; /* hack */ cd_dbg(CD_OPEN, "entering register_cdrom\n"); if (cdo->open == NULL || cdo->release == NULL) return -EINVAL; if (!banner_printed) { pr_info("Uniform CD-ROM driver " REVISION "\n"); banner_printed = 1; cdrom_sysctl_register(); } ENSURE(drive_status, CDC_DRIVE_STATUS); if (cdo->check_events == NULL && cdo->media_changed == NULL) *change_capability = ~(CDC_MEDIA_CHANGED | CDC_SELECT_DISC); ENSURE(tray_move, CDC_CLOSE_TRAY | CDC_OPEN_TRAY); ENSURE(lock_door, CDC_LOCK); ENSURE(select_speed, CDC_SELECT_SPEED); ENSURE(get_last_session, CDC_MULTI_SESSION); ENSURE(get_mcn, CDC_MCN); ENSURE(reset, CDC_RESET); ENSURE(generic_packet, CDC_GENERIC_PACKET); cdi->mc_flags = 0; cdi->options = CDO_USE_FFLAGS; if (autoclose == 1 && CDROM_CAN(CDC_CLOSE_TRAY)) cdi->options |= (int) CDO_AUTO_CLOSE; if (autoeject == 1 && CDROM_CAN(CDC_OPEN_TRAY)) cdi->options |= (int) CDO_AUTO_EJECT; if (lockdoor == 1) cdi->options |= (int) CDO_LOCK; if (check_media_type == 1) cdi->options |= (int) CDO_CHECK_TYPE; if (CDROM_CAN(CDC_MRW_W)) cdi->exit = cdrom_mrw_exit; if (cdi->disk) cdi->cdda_method = CDDA_BPC_FULL; else cdi->cdda_method = CDDA_OLD; WARN_ON(!cdo->generic_packet); cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" registered\n", cdi->name); mutex_lock(&cdrom_mutex); list_add(&cdi->list, &cdrom_list); mutex_unlock(&cdrom_mutex); return 0; } #undef ENSURE void unregister_cdrom(struct cdrom_device_info *cdi) { cd_dbg(CD_OPEN, "entering unregister_cdrom\n"); mutex_lock(&cdrom_mutex); list_del(&cdi->list); mutex_unlock(&cdrom_mutex); if (cdi->exit) cdi->exit(cdi); cd_dbg(CD_REG_UNREG, "drive \"/dev/%s\" unregistered\n", cdi->name); } int cdrom_get_media_event(struct cdrom_device_info *cdi, struct media_event_desc *med) { struct packet_command cgc; unsigned char buffer[8]; struct event_header *eh = (struct event_header *)buffer; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_EVENT_STATUS_NOTIFICATION; cgc.cmd[1] = 1; /* IMMED */ cgc.cmd[4] = 1 << 4; /* media event */ cgc.cmd[8] = sizeof(buffer); cgc.quiet = 1; if (cdi->ops->generic_packet(cdi, &cgc)) return 1; if (be16_to_cpu(eh->data_len) < sizeof(*med)) return 1; if (eh->nea || eh->notification_class != 0x4) return 1; memcpy(med, &buffer[sizeof(*eh)], sizeof(*med)); return 0; } static int cdrom_get_random_writable(struct cdrom_device_info *cdi, struct rwrt_feature_desc *rfd) { struct packet_command cgc; char buffer[24]; int ret; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; /* often 0x46 */ cgc.cmd[3] = CDF_RWRT; /* often 0x0020 */ cgc.cmd[8] = sizeof(buffer); /* often 0x18 */ cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) return ret; memcpy(rfd, &buffer[sizeof(struct feature_header)], sizeof (*rfd)); return 0; } static int cdrom_has_defect_mgt(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[16]; __be16 *feature_code; int ret; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; cgc.cmd[3] = CDF_HWDM; cgc.cmd[8] = sizeof(buffer); cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) return ret; feature_code = (__be16 *) &buffer[sizeof(struct feature_header)]; if (be16_to_cpu(*feature_code) == CDF_HWDM) return 0; return 1; } static int cdrom_is_random_writable(struct cdrom_device_info *cdi, int *write) { struct rwrt_feature_desc rfd; int ret; *write = 0; if ((ret = cdrom_get_random_writable(cdi, &rfd))) return ret; if (CDF_RWRT == be16_to_cpu(rfd.feature_code)) *write = 1; return 0; } static int cdrom_media_erasable(struct cdrom_device_info *cdi) { disc_information di; int ret; ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < offsetof(typeof(di), n_first_track)) return -1; return di.erasable; } /* * FIXME: check RO bit */ static int cdrom_dvdram_open_write(struct cdrom_device_info *cdi) { int ret = cdrom_media_erasable(cdi); /* * allow writable open if media info read worked and media is * erasable, _or_ if it fails since not all drives support it */ if (!ret) return 1; return 0; } static int cdrom_mrw_open_write(struct cdrom_device_info *cdi) { disc_information di; int ret; /* * always reset to DMA lba space on open */ if (cdrom_mrw_set_lba_space(cdi, MRW_LBA_DMA)) { pr_err("failed setting lba address space\n"); return 1; } ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < offsetof(typeof(di),disc_type)) return 1; if (!di.erasable) return 1; /* * mrw_status * 0 - not MRW formatted * 1 - MRW bgformat started, but not running or complete * 2 - MRW bgformat in progress * 3 - MRW formatting complete */ ret = 0; pr_info("open: mrw_status '%s'\n", mrw_format_status[di.mrw_status]); if (!di.mrw_status) ret = 1; else if (di.mrw_status == CDM_MRW_BGFORMAT_INACTIVE && mrw_format_restart) ret = cdrom_mrw_bgformat(cdi, 1); return ret; } static int mo_open_write(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[255]; int ret; init_cdrom_command(&cgc, &buffer, 4, CGC_DATA_READ); cgc.quiet = 1; /* * obtain write protect information as per * drivers/scsi/sd.c:sd_read_write_protect_flag */ ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0); if (ret) ret = cdrom_mode_sense(cdi, &cgc, GPMODE_VENDOR_PAGE, 0); if (ret) { cgc.buflen = 255; ret = cdrom_mode_sense(cdi, &cgc, GPMODE_ALL_PAGES, 0); } /* drive gave us no info, let the user go ahead */ if (ret) return 0; return buffer[3] & 0x80; } static int cdrom_ram_open_write(struct cdrom_device_info *cdi) { struct rwrt_feature_desc rfd; int ret; if ((ret = cdrom_has_defect_mgt(cdi))) return ret; if ((ret = cdrom_get_random_writable(cdi, &rfd))) return ret; else if (CDF_RWRT == be16_to_cpu(rfd.feature_code)) ret = !rfd.curr; cd_dbg(CD_OPEN, "can open for random write\n"); return ret; } static void cdrom_mmc3_profile(struct cdrom_device_info *cdi) { struct packet_command cgc; char buffer[32]; int ret, mmc3_profile; init_cdrom_command(&cgc, buffer, sizeof(buffer), CGC_DATA_READ); cgc.cmd[0] = GPCMD_GET_CONFIGURATION; cgc.cmd[1] = 0; cgc.cmd[2] = cgc.cmd[3] = 0; /* Starting Feature Number */ cgc.cmd[8] = sizeof(buffer); /* Allocation Length */ cgc.quiet = 1; if ((ret = cdi->ops->generic_packet(cdi, &cgc))) mmc3_profile = 0xffff; else mmc3_profile = (buffer[6] << 8) | buffer[7]; cdi->mmc3_profile = mmc3_profile; } static int cdrom_is_dvd_rw(struct cdrom_device_info *cdi) { switch (cdi->mmc3_profile) { case 0x12: /* DVD-RAM */ case 0x1A: /* DVD+RW */ case 0x43: /* BD-RE */ return 0; default: return 1; } } /* * returns 0 for ok to open write, non-0 to disallow */ static int cdrom_open_write(struct cdrom_device_info *cdi) { int mrw, mrw_write, ram_write; int ret = 1; mrw = 0; if (!cdrom_is_mrw(cdi, &mrw_write)) mrw = 1; if (CDROM_CAN(CDC_MO_DRIVE)) ram_write = 1; else (void) cdrom_is_random_writable(cdi, &ram_write); if (mrw) cdi->mask &= ~CDC_MRW; else cdi->mask |= CDC_MRW; if (mrw_write) cdi->mask &= ~CDC_MRW_W; else cdi->mask |= CDC_MRW_W; if (ram_write) cdi->mask &= ~CDC_RAM; else cdi->mask |= CDC_RAM; if (CDROM_CAN(CDC_MRW_W)) ret = cdrom_mrw_open_write(cdi); else if (CDROM_CAN(CDC_DVD_RAM)) ret = cdrom_dvdram_open_write(cdi); else if (CDROM_CAN(CDC_RAM) && !CDROM_CAN(CDC_CD_R|CDC_CD_RW|CDC_DVD|CDC_DVD_R|CDC_MRW|CDC_MO_DRIVE)) ret = cdrom_ram_open_write(cdi); else if (CDROM_CAN(CDC_MO_DRIVE)) ret = mo_open_write(cdi); else if (!cdrom_is_dvd_rw(cdi)) ret = 0; return ret; } static void cdrom_dvd_rw_close_write(struct cdrom_device_info *cdi) { struct packet_command cgc; if (cdi->mmc3_profile != 0x1a) { cd_dbg(CD_CLOSE, "%s: No DVD+RW\n", cdi->name); return; } if (!cdi->media_written) { cd_dbg(CD_CLOSE, "%s: DVD+RW media clean\n", cdi->name); return; } pr_info("%s: dirty DVD+RW media, \"finalizing\"\n", cdi->name); init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_FLUSH_CACHE; cgc.timeout = 30*HZ; cdi->ops->generic_packet(cdi, &cgc); init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_CLOSE_TRACK; cgc.timeout = 3000*HZ; cgc.quiet = 1; cdi->ops->generic_packet(cdi, &cgc); init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_CLOSE_TRACK; cgc.cmd[2] = 2; /* Close session */ cgc.quiet = 1; cgc.timeout = 3000*HZ; cdi->ops->generic_packet(cdi, &cgc); cdi->media_written = 0; } static int cdrom_close_write(struct cdrom_device_info *cdi) { #if 0 return cdrom_flush_cache(cdi); #else return 0; #endif } /* badly broken, I know. Is due for a fixup anytime. */ static void cdrom_count_tracks(struct cdrom_device_info *cdi, tracktype *tracks) { struct cdrom_tochdr header; struct cdrom_tocentry entry; int ret, i; tracks->data = 0; tracks->audio = 0; tracks->cdi = 0; tracks->xa = 0; tracks->error = 0; cd_dbg(CD_COUNT_TRACKS, "entering cdrom_count_tracks\n"); /* Grab the TOC header so we can see how many tracks there are */ ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header); if (ret) { if (ret == -ENOMEDIUM) tracks->error = CDS_NO_DISC; else tracks->error = CDS_NO_INFO; return; } /* check what type of tracks are on this disc */ entry.cdte_format = CDROM_MSF; for (i = header.cdth_trk0; i <= header.cdth_trk1; i++) { entry.cdte_track = i; if (cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry)) { tracks->error = CDS_NO_INFO; return; } if (entry.cdte_ctrl & CDROM_DATA_TRACK) { if (entry.cdte_format == 0x10) tracks->cdi++; else if (entry.cdte_format == 0x20) tracks->xa++; else tracks->data++; } else { tracks->audio++; } cd_dbg(CD_COUNT_TRACKS, "track %d: format=%d, ctrl=%d\n", i, entry.cdte_format, entry.cdte_ctrl); } cd_dbg(CD_COUNT_TRACKS, "disc has %d tracks: %d=audio %d=data %d=Cd-I %d=XA\n", header.cdth_trk1, tracks->audio, tracks->data, tracks->cdi, tracks->xa); } static int open_for_data(struct cdrom_device_info *cdi) { int ret; const struct cdrom_device_ops *cdo = cdi->ops; tracktype tracks; cd_dbg(CD_OPEN, "entering open_for_data\n"); /* Check if the driver can report drive status. If it can, we can do clever things. If it can't, well, we at least tried! */ if (cdo->drive_status != NULL) { ret = cdo->drive_status(cdi, CDSL_CURRENT); cd_dbg(CD_OPEN, "drive_status=%d\n", ret); if (ret == CDS_TRAY_OPEN) { cd_dbg(CD_OPEN, "the tray is open...\n"); /* can/may i close it? */ if (CDROM_CAN(CDC_CLOSE_TRAY) && cdi->options & CDO_AUTO_CLOSE) { cd_dbg(CD_OPEN, "trying to close the tray\n"); ret=cdo->tray_move(cdi,0); if (ret) { cd_dbg(CD_OPEN, "bummer. tried to close the tray but failed.\n"); /* Ignore the error from the low level driver. We don't care why it couldn't close the tray. We only care that there is no disc in the drive, since that is the _REAL_ problem here.*/ ret=-ENOMEDIUM; goto clean_up_and_return; } } else { cd_dbg(CD_OPEN, "bummer. this drive can't close the tray.\n"); ret=-ENOMEDIUM; goto clean_up_and_return; } /* Ok, the door should be closed now.. Check again */ ret = cdo->drive_status(cdi, CDSL_CURRENT); if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) { cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n"); cd_dbg(CD_OPEN, "tray might not contain a medium\n"); ret=-ENOMEDIUM; goto clean_up_and_return; } cd_dbg(CD_OPEN, "the tray is now closed\n"); } /* the door should be closed now, check for the disc */ ret = cdo->drive_status(cdi, CDSL_CURRENT); if (ret!=CDS_DISC_OK) { ret = -ENOMEDIUM; goto clean_up_and_return; } } cdrom_count_tracks(cdi, &tracks); if (tracks.error == CDS_NO_DISC) { cd_dbg(CD_OPEN, "bummer. no disc.\n"); ret=-ENOMEDIUM; goto clean_up_and_return; } /* CD-Players which don't use O_NONBLOCK, workman * for example, need bit CDO_CHECK_TYPE cleared! */ if (tracks.data==0) { if (cdi->options & CDO_CHECK_TYPE) { /* give people a warning shot, now that CDO_CHECK_TYPE is the default case! */ cd_dbg(CD_OPEN, "bummer. wrong media type.\n"); cd_dbg(CD_WARNING, "pid %d must open device O_NONBLOCK!\n", (unsigned int)task_pid_nr(current)); ret=-EMEDIUMTYPE; goto clean_up_and_return; } else { cd_dbg(CD_OPEN, "wrong media type, but CDO_CHECK_TYPE not set\n"); } } cd_dbg(CD_OPEN, "all seems well, opening the devicen"); /* all seems well, we can open the device */ ret = cdo->open(cdi, 0); /* open for data */ cd_dbg(CD_OPEN, "opening the device gave me %d\n", ret); /* After all this careful checking, we shouldn't have problems opening the device, but we don't want the device locked if this somehow fails... */ if (ret) { cd_dbg(CD_OPEN, "open device failed\n"); goto clean_up_and_return; } if (CDROM_CAN(CDC_LOCK) && (cdi->options & CDO_LOCK)) { cdo->lock_door(cdi, 1); cd_dbg(CD_OPEN, "door locked\n"); } cd_dbg(CD_OPEN, "device opened successfully\n"); return ret; /* Something failed. Try to unlock the drive, because some drivers (notably ide-cd) lock the drive after every command. This produced a nasty bug where after mount failed, the drive would remain locked! This ensures that the drive gets unlocked after a mount fails. This is a goto to avoid bloating the driver with redundant code. */ clean_up_and_return: cd_dbg(CD_OPEN, "open failed\n"); if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) { cdo->lock_door(cdi, 0); cd_dbg(CD_OPEN, "door unlocked\n"); } return ret; } /* We use the open-option O_NONBLOCK to indicate that the * purpose of opening is only for subsequent ioctl() calls; no device * integrity checks are performed. * * We hope that all cd-player programs will adopt this convention. It * is in their own interest: device control becomes a lot easier * this way. */ int cdrom_open(struct cdrom_device_info *cdi, struct block_device *bdev, fmode_t mode) { int ret; cd_dbg(CD_OPEN, "entering cdrom_open\n"); /* if this was a O_NONBLOCK open and we should honor the flags, * do a quick open without drive/disc integrity checks. */ cdi->use_count++; if ((mode & FMODE_NDELAY) && (cdi->options & CDO_USE_FFLAGS)) { ret = cdi->ops->open(cdi, 1); } else { ret = open_for_data(cdi); if (ret) goto err; cdrom_mmc3_profile(cdi); if (mode & FMODE_WRITE) { ret = -EROFS; if (cdrom_open_write(cdi)) goto err_release; if (!CDROM_CAN(CDC_RAM)) goto err_release; ret = 0; cdi->media_written = 0; } } if (ret) goto err; cd_dbg(CD_OPEN, "Use count for \"/dev/%s\" now %d\n", cdi->name, cdi->use_count); return 0; err_release: if (CDROM_CAN(CDC_LOCK) && cdi->options & CDO_LOCK) { cdi->ops->lock_door(cdi, 0); cd_dbg(CD_OPEN, "door unlocked\n"); } cdi->ops->release(cdi); err: cdi->use_count--; return ret; } /* This code is similar to that in open_for_data. The routine is called whenever an audio play operation is requested. */ static int check_for_audio_disc(struct cdrom_device_info *cdi, const struct cdrom_device_ops *cdo) { int ret; tracktype tracks; cd_dbg(CD_OPEN, "entering check_for_audio_disc\n"); if (!(cdi->options & CDO_CHECK_TYPE)) return 0; if (cdo->drive_status != NULL) { ret = cdo->drive_status(cdi, CDSL_CURRENT); cd_dbg(CD_OPEN, "drive_status=%d\n", ret); if (ret == CDS_TRAY_OPEN) { cd_dbg(CD_OPEN, "the tray is open...\n"); /* can/may i close it? */ if (CDROM_CAN(CDC_CLOSE_TRAY) && cdi->options & CDO_AUTO_CLOSE) { cd_dbg(CD_OPEN, "trying to close the tray\n"); ret=cdo->tray_move(cdi,0); if (ret) { cd_dbg(CD_OPEN, "bummer. tried to close tray but failed.\n"); /* Ignore the error from the low level driver. We don't care why it couldn't close the tray. We only care that there is no disc in the drive, since that is the _REAL_ problem here.*/ return -ENOMEDIUM; } } else { cd_dbg(CD_OPEN, "bummer. this driver can't close the tray.\n"); return -ENOMEDIUM; } /* Ok, the door should be closed now.. Check again */ ret = cdo->drive_status(cdi, CDSL_CURRENT); if ((ret == CDS_NO_DISC) || (ret==CDS_TRAY_OPEN)) { cd_dbg(CD_OPEN, "bummer. the tray is still not closed.\n"); return -ENOMEDIUM; } if (ret!=CDS_DISC_OK) { cd_dbg(CD_OPEN, "bummer. disc isn't ready.\n"); return -EIO; } cd_dbg(CD_OPEN, "the tray is now closed\n"); } } cdrom_count_tracks(cdi, &tracks); if (tracks.error) return(tracks.error); if (tracks.audio==0) return -EMEDIUMTYPE; return 0; } void cdrom_release(struct cdrom_device_info *cdi, fmode_t mode) { const struct cdrom_device_ops *cdo = cdi->ops; int opened_for_data; cd_dbg(CD_CLOSE, "entering cdrom_release\n"); if (cdi->use_count > 0) cdi->use_count--; if (cdi->use_count == 0) { cd_dbg(CD_CLOSE, "Use count for \"/dev/%s\" now zero\n", cdi->name); cdrom_dvd_rw_close_write(cdi); if ((cdo->capability & CDC_LOCK) && !cdi->keeplocked) { cd_dbg(CD_CLOSE, "Unlocking door!\n"); cdo->lock_door(cdi, 0); } } opened_for_data = !(cdi->options & CDO_USE_FFLAGS) || !(mode & FMODE_NDELAY); /* * flush cache on last write release */ if (CDROM_CAN(CDC_RAM) && !cdi->use_count && cdi->for_data) cdrom_close_write(cdi); cdo->release(cdi); if (cdi->use_count == 0) { /* last process that closes dev*/ if (opened_for_data && cdi->options & CDO_AUTO_EJECT && CDROM_CAN(CDC_OPEN_TRAY)) cdo->tray_move(cdi, 1); } } static int cdrom_read_mech_status(struct cdrom_device_info *cdi, struct cdrom_changer_info *buf) { struct packet_command cgc; const struct cdrom_device_ops *cdo = cdi->ops; int length; /* * Sanyo changer isn't spec compliant (doesn't use regular change * LOAD_UNLOAD command, and it doesn't implement the mech status * command below */ if (cdi->sanyo_slot) { buf->hdr.nslots = 3; buf->hdr.curslot = cdi->sanyo_slot == 3 ? 0 : cdi->sanyo_slot; for (length = 0; length < 3; length++) { buf->slots[length].disc_present = 1; buf->slots[length].change = 0; } return 0; } length = sizeof(struct cdrom_mechstat_header) + cdi->capacity * sizeof(struct cdrom_slot); init_cdrom_command(&cgc, buf, length, CGC_DATA_READ); cgc.cmd[0] = GPCMD_MECHANISM_STATUS; cgc.cmd[8] = (length >> 8) & 0xff; cgc.cmd[9] = length & 0xff; return cdo->generic_packet(cdi, &cgc); } static int cdrom_slot_status(struct cdrom_device_info *cdi, int slot) { struct cdrom_changer_info *info; int ret; cd_dbg(CD_CHANGER, "entering cdrom_slot_status()\n"); if (cdi->sanyo_slot) return CDS_NO_INFO; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; if ((ret = cdrom_read_mech_status(cdi, info))) goto out_free; if (info->slots[slot].disc_present) ret = CDS_DISC_OK; else ret = CDS_NO_DISC; out_free: kfree(info); return ret; } /* Return the number of slots for an ATAPI/SCSI cdrom, * return 1 if not a changer. */ int cdrom_number_of_slots(struct cdrom_device_info *cdi) { int status; int nslots = 1; struct cdrom_changer_info *info; cd_dbg(CD_CHANGER, "entering cdrom_number_of_slots()\n"); /* cdrom_read_mech_status requires a valid value for capacity: */ cdi->capacity = 0; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; if ((status = cdrom_read_mech_status(cdi, info)) == 0) nslots = info->hdr.nslots; kfree(info); return nslots; } /* If SLOT < 0, unload the current slot. Otherwise, try to load SLOT. */ static int cdrom_load_unload(struct cdrom_device_info *cdi, int slot) { struct packet_command cgc; cd_dbg(CD_CHANGER, "entering cdrom_load_unload()\n"); if (cdi->sanyo_slot && slot < 0) return 0; init_cdrom_command(&cgc, NULL, 0, CGC_DATA_NONE); cgc.cmd[0] = GPCMD_LOAD_UNLOAD; cgc.cmd[4] = 2 + (slot >= 0); cgc.cmd[8] = slot; cgc.timeout = 60 * HZ; /* The Sanyo 3 CD changer uses byte 7 of the GPCMD_TEST_UNIT_READY to command to switch CDs instead of using the GPCMD_LOAD_UNLOAD opcode. */ if (cdi->sanyo_slot && -1 < slot) { cgc.cmd[0] = GPCMD_TEST_UNIT_READY; cgc.cmd[7] = slot; cgc.cmd[4] = cgc.cmd[8] = 0; cdi->sanyo_slot = slot ? slot : 3; } return cdi->ops->generic_packet(cdi, &cgc); } static int cdrom_select_disc(struct cdrom_device_info *cdi, int slot) { struct cdrom_changer_info *info; int curslot; int ret; cd_dbg(CD_CHANGER, "entering cdrom_select_disc()\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -EDRIVE_CANT_DO_THIS; if (cdi->ops->check_events) cdi->ops->check_events(cdi, 0, slot); else cdi->ops->media_changed(cdi, slot); if (slot == CDSL_NONE) { /* set media changed bits, on both queues */ cdi->mc_flags = 0x3; return cdrom_load_unload(cdi, -1); } info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; if ((ret = cdrom_read_mech_status(cdi, info))) { kfree(info); return ret; } curslot = info->hdr.curslot; kfree(info); if (cdi->use_count > 1 || cdi->keeplocked) { if (slot == CDSL_CURRENT) { return curslot; } else { return -EBUSY; } } /* Specifying CDSL_CURRENT will attempt to load the currnet slot, which is useful if it had been previously unloaded. Whether it can or not, it returns the current slot. Similarly, if slot happens to be the current one, we still try and load it. */ if (slot == CDSL_CURRENT) slot = curslot; /* set media changed bits on both queues */ cdi->mc_flags = 0x3; if ((ret = cdrom_load_unload(cdi, slot))) return ret; return slot; } /* * As cdrom implements an extra ioctl consumer for media changed * event, it needs to buffer ->check_events() output, such that event * is not lost for both the usual VFS and ioctl paths. * cdi->{vfs|ioctl}_events are used to buffer pending events for each * path. * * XXX: Locking is non-existent. cdi->ops->check_events() can be * called in parallel and buffering fields are accessed without any * exclusion. The original media_changed code had the same problem. * It might be better to simply deprecate CDROM_MEDIA_CHANGED ioctl * and remove this cruft altogether. It doesn't have much usefulness * at this point. */ static void cdrom_update_events(struct cdrom_device_info *cdi, unsigned int clearing) { unsigned int events; events = cdi->ops->check_events(cdi, clearing, CDSL_CURRENT); cdi->vfs_events |= events; cdi->ioctl_events |= events; } unsigned int cdrom_check_events(struct cdrom_device_info *cdi, unsigned int clearing) { unsigned int events; cdrom_update_events(cdi, clearing); events = cdi->vfs_events; cdi->vfs_events = 0; return events; } EXPORT_SYMBOL(cdrom_check_events); /* We want to make media_changed accessible to the user through an * ioctl. The main problem now is that we must double-buffer the * low-level implementation, to assure that the VFS and the user both * see a medium change once. */ static int media_changed(struct cdrom_device_info *cdi, int queue) { unsigned int mask = (1 << (queue & 1)); int ret = !!(cdi->mc_flags & mask); bool changed; if (!CDROM_CAN(CDC_MEDIA_CHANGED)) return ret; /* changed since last call? */ if (cdi->ops->check_events) { BUG_ON(!queue); /* shouldn't be called from VFS path */ cdrom_update_events(cdi, DISK_EVENT_MEDIA_CHANGE); changed = cdi->ioctl_events & DISK_EVENT_MEDIA_CHANGE; cdi->ioctl_events = 0; } else changed = cdi->ops->media_changed(cdi, CDSL_CURRENT); if (changed) { cdi->mc_flags = 0x3; /* set bit on both queues */ ret |= 1; cdi->media_written = 0; } cdi->mc_flags &= ~mask; /* clear bit */ return ret; } int cdrom_media_changed(struct cdrom_device_info *cdi) { /* This talks to the VFS, which doesn't like errors - just 1 or 0. * Returning "0" is always safe (media hasn't been changed). Do that * if the low-level cdrom driver dosn't support media changed. */ if (cdi == NULL || cdi->ops->media_changed == NULL) return 0; if (!CDROM_CAN(CDC_MEDIA_CHANGED)) return 0; return media_changed(cdi, 0); } /* Requests to the low-level drivers will /always/ be done in the following format convention: CDROM_LBA: all data-related requests. CDROM_MSF: all audio-related requests. However, a low-level implementation is allowed to refuse this request, and return information in its own favorite format. It doesn't make sense /at all/ to ask for a play_audio in LBA format, or ask for multi-session info in MSF format. However, for backward compatibility these format requests will be satisfied, but the requests to the low-level drivers will be sanitized in the more meaningful format indicated above. */ static void sanitize_format(union cdrom_addr *addr, u_char * curr, u_char requested) { if (*curr == requested) return; /* nothing to be done! */ if (requested == CDROM_LBA) { addr->lba = (int) addr->msf.frame + 75 * (addr->msf.second - 2 + 60 * addr->msf.minute); } else { /* CDROM_MSF */ int lba = addr->lba; addr->msf.frame = lba % 75; lba /= 75; lba += 2; addr->msf.second = lba % 60; addr->msf.minute = lba / 60; } *curr = requested; } void init_cdrom_command(struct packet_command *cgc, void *buf, int len, int type) { memset(cgc, 0, sizeof(struct packet_command)); if (buf) memset(buf, 0, len); cgc->buffer = (char *) buf; cgc->buflen = len; cgc->data_direction = type; cgc->timeout = CDROM_DEF_TIMEOUT; } /* DVD handling */ #define copy_key(dest,src) memcpy((dest), (src), sizeof(dvd_key)) #define copy_chal(dest,src) memcpy((dest), (src), sizeof(dvd_challenge)) static void setup_report_key(struct packet_command *cgc, unsigned agid, unsigned type) { cgc->cmd[0] = GPCMD_REPORT_KEY; cgc->cmd[10] = type | (agid << 6); switch (type) { case 0: case 8: case 5: { cgc->buflen = 8; break; } case 1: { cgc->buflen = 16; break; } case 2: case 4: { cgc->buflen = 12; break; } } cgc->cmd[9] = cgc->buflen; cgc->data_direction = CGC_DATA_READ; } static void setup_send_key(struct packet_command *cgc, unsigned agid, unsigned type) { cgc->cmd[0] = GPCMD_SEND_KEY; cgc->cmd[10] = type | (agid << 6); switch (type) { case 1: { cgc->buflen = 16; break; } case 3: { cgc->buflen = 12; break; } case 6: { cgc->buflen = 8; break; } } cgc->cmd[9] = cgc->buflen; cgc->data_direction = CGC_DATA_WRITE; } static int dvd_do_auth(struct cdrom_device_info *cdi, dvd_authinfo *ai) { int ret; u_char buf[20]; struct packet_command cgc; const struct cdrom_device_ops *cdo = cdi->ops; rpc_state_t rpc_state; memset(buf, 0, sizeof(buf)); init_cdrom_command(&cgc, buf, 0, CGC_DATA_READ); switch (ai->type) { /* LU data send */ case DVD_LU_SEND_AGID: cd_dbg(CD_DVD, "entering DVD_LU_SEND_AGID\n"); cgc.quiet = 1; setup_report_key(&cgc, ai->lsa.agid, 0); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lsa.agid = buf[7] >> 6; /* Returning data, let host change state */ break; case DVD_LU_SEND_KEY1: cd_dbg(CD_DVD, "entering DVD_LU_SEND_KEY1\n"); setup_report_key(&cgc, ai->lsk.agid, 2); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; copy_key(ai->lsk.key, &buf[4]); /* Returning data, let host change state */ break; case DVD_LU_SEND_CHALLENGE: cd_dbg(CD_DVD, "entering DVD_LU_SEND_CHALLENGE\n"); setup_report_key(&cgc, ai->lsc.agid, 1); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; copy_chal(ai->lsc.chal, &buf[4]); /* Returning data, let host change state */ break; /* Post-auth key */ case DVD_LU_SEND_TITLE_KEY: cd_dbg(CD_DVD, "entering DVD_LU_SEND_TITLE_KEY\n"); cgc.quiet = 1; setup_report_key(&cgc, ai->lstk.agid, 4); cgc.cmd[5] = ai->lstk.lba; cgc.cmd[4] = ai->lstk.lba >> 8; cgc.cmd[3] = ai->lstk.lba >> 16; cgc.cmd[2] = ai->lstk.lba >> 24; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lstk.cpm = (buf[4] >> 7) & 1; ai->lstk.cp_sec = (buf[4] >> 6) & 1; ai->lstk.cgms = (buf[4] >> 4) & 3; copy_key(ai->lstk.title_key, &buf[5]); /* Returning data, let host change state */ break; case DVD_LU_SEND_ASF: cd_dbg(CD_DVD, "entering DVD_LU_SEND_ASF\n"); setup_report_key(&cgc, ai->lsasf.agid, 5); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lsasf.asf = buf[7] & 1; break; /* LU data receive (LU changes state) */ case DVD_HOST_SEND_CHALLENGE: cd_dbg(CD_DVD, "entering DVD_HOST_SEND_CHALLENGE\n"); setup_send_key(&cgc, ai->hsc.agid, 1); buf[1] = 0xe; copy_chal(&buf[4], ai->hsc.chal); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->type = DVD_LU_SEND_KEY1; break; case DVD_HOST_SEND_KEY2: cd_dbg(CD_DVD, "entering DVD_HOST_SEND_KEY2\n"); setup_send_key(&cgc, ai->hsk.agid, 3); buf[1] = 0xa; copy_key(&buf[4], ai->hsk.key); if ((ret = cdo->generic_packet(cdi, &cgc))) { ai->type = DVD_AUTH_FAILURE; return ret; } ai->type = DVD_AUTH_ESTABLISHED; break; /* Misc */ case DVD_INVALIDATE_AGID: cgc.quiet = 1; cd_dbg(CD_DVD, "entering DVD_INVALIDATE_AGID\n"); setup_report_key(&cgc, ai->lsa.agid, 0x3f); if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; break; /* Get region settings */ case DVD_LU_SEND_RPC_STATE: cd_dbg(CD_DVD, "entering DVD_LU_SEND_RPC_STATE\n"); setup_report_key(&cgc, 0, 8); memset(&rpc_state, 0, sizeof(rpc_state_t)); cgc.buffer = (char *) &rpc_state; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; ai->lrpcs.type = rpc_state.type_code; ai->lrpcs.vra = rpc_state.vra; ai->lrpcs.ucca = rpc_state.ucca; ai->lrpcs.region_mask = rpc_state.region_mask; ai->lrpcs.rpc_scheme = rpc_state.rpc_scheme; break; /* Set region settings */ case DVD_HOST_SEND_RPC_STATE: cd_dbg(CD_DVD, "entering DVD_HOST_SEND_RPC_STATE\n"); setup_send_key(&cgc, 0, 6); buf[1] = 6; buf[4] = ai->hrpcs.pdrc; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; break; default: cd_dbg(CD_WARNING, "Invalid DVD key ioctl (%d)\n", ai->type); return -ENOTTY; } return 0; } static int dvd_read_physical(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { unsigned char buf[21], *base; struct dvd_layer *layer; const struct cdrom_device_ops *cdo = cdi->ops; int ret, layer_num = s->physical.layer_num; if (layer_num >= DVD_LAYERS) return -EINVAL; init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[6] = layer_num; cgc->cmd[7] = s->type; cgc->cmd[9] = cgc->buflen & 0xff; /* * refrain from reporting errors on non-existing layers (mainly) */ cgc->quiet = 1; ret = cdo->generic_packet(cdi, cgc); if (ret) return ret; base = &buf[4]; layer = &s->physical.layer[layer_num]; /* * place the data... really ugly, but at least we won't have to * worry about endianess in userspace. */ memset(layer, 0, sizeof(*layer)); layer->book_version = base[0] & 0xf; layer->book_type = base[0] >> 4; layer->min_rate = base[1] & 0xf; layer->disc_size = base[1] >> 4; layer->layer_type = base[2] & 0xf; layer->track_path = (base[2] >> 4) & 1; layer->nlayers = (base[2] >> 5) & 3; layer->track_density = base[3] & 0xf; layer->linear_density = base[3] >> 4; layer->start_sector = base[5] << 16 | base[6] << 8 | base[7]; layer->end_sector = base[9] << 16 | base[10] << 8 | base[11]; layer->end_sector_l0 = base[13] << 16 | base[14] << 8 | base[15]; layer->bca = base[16] >> 7; return 0; } static int dvd_read_copyright(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret; u_char buf[8]; const struct cdrom_device_ops *cdo = cdi->ops; init_cdrom_command(cgc, buf, sizeof(buf), CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[6] = s->copyright.layer_num; cgc->cmd[7] = s->type; cgc->cmd[8] = cgc->buflen >> 8; cgc->cmd[9] = cgc->buflen & 0xff; ret = cdo->generic_packet(cdi, cgc); if (ret) return ret; s->copyright.cpst = buf[4]; s->copyright.rmi = buf[5]; return 0; } static int dvd_read_disckey(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret, size; u_char *buf; const struct cdrom_device_ops *cdo = cdi->ops; size = sizeof(s->disckey.value) + 4; buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; init_cdrom_command(cgc, buf, size, CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[7] = s->type; cgc->cmd[8] = size >> 8; cgc->cmd[9] = size & 0xff; cgc->cmd[10] = s->disckey.agid << 6; ret = cdo->generic_packet(cdi, cgc); if (!ret) memcpy(s->disckey.value, &buf[4], sizeof(s->disckey.value)); kfree(buf); return ret; } static int dvd_read_bca(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret, size = 4 + 188; u_char *buf; const struct cdrom_device_ops *cdo = cdi->ops; buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; init_cdrom_command(cgc, buf, size, CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[7] = s->type; cgc->cmd[9] = cgc->buflen & 0xff; ret = cdo->generic_packet(cdi, cgc); if (ret) goto out; s->bca.len = buf[0] << 8 | buf[1]; if (s->bca.len < 12 || s->bca.len > 188) { cd_dbg(CD_WARNING, "Received invalid BCA length (%d)\n", s->bca.len); ret = -EIO; goto out; } memcpy(s->bca.value, &buf[4], s->bca.len); ret = 0; out: kfree(buf); return ret; } static int dvd_read_manufact(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { int ret = 0, size; u_char *buf; const struct cdrom_device_ops *cdo = cdi->ops; size = sizeof(s->manufact.value) + 4; buf = kmalloc(size, GFP_KERNEL); if (!buf) return -ENOMEM; init_cdrom_command(cgc, buf, size, CGC_DATA_READ); cgc->cmd[0] = GPCMD_READ_DVD_STRUCTURE; cgc->cmd[7] = s->type; cgc->cmd[8] = size >> 8; cgc->cmd[9] = size & 0xff; ret = cdo->generic_packet(cdi, cgc); if (ret) goto out; s->manufact.len = buf[0] << 8 | buf[1]; if (s->manufact.len < 0) { cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d)\n", s->manufact.len); ret = -EIO; } else { if (s->manufact.len > 2048) { cd_dbg(CD_WARNING, "Received invalid manufacture info length (%d): truncating to 2048\n", s->manufact.len); s->manufact.len = 2048; } memcpy(s->manufact.value, &buf[4], s->manufact.len); } out: kfree(buf); return ret; } static int dvd_read_struct(struct cdrom_device_info *cdi, dvd_struct *s, struct packet_command *cgc) { switch (s->type) { case DVD_STRUCT_PHYSICAL: return dvd_read_physical(cdi, s, cgc); case DVD_STRUCT_COPYRIGHT: return dvd_read_copyright(cdi, s, cgc); case DVD_STRUCT_DISCKEY: return dvd_read_disckey(cdi, s, cgc); case DVD_STRUCT_BCA: return dvd_read_bca(cdi, s, cgc); case DVD_STRUCT_MANUFACT: return dvd_read_manufact(cdi, s, cgc); default: cd_dbg(CD_WARNING, ": Invalid DVD structure read requested (%d)\n", s->type); return -EINVAL; } } int cdrom_mode_sense(struct cdrom_device_info *cdi, struct packet_command *cgc, int page_code, int page_control) { const struct cdrom_device_ops *cdo = cdi->ops; memset(cgc->cmd, 0, sizeof(cgc->cmd)); cgc->cmd[0] = GPCMD_MODE_SENSE_10; cgc->cmd[2] = page_code | (page_control << 6); cgc->cmd[7] = cgc->buflen >> 8; cgc->cmd[8] = cgc->buflen & 0xff; cgc->data_direction = CGC_DATA_READ; return cdo->generic_packet(cdi, cgc); } int cdrom_mode_select(struct cdrom_device_info *cdi, struct packet_command *cgc) { const struct cdrom_device_ops *cdo = cdi->ops; memset(cgc->cmd, 0, sizeof(cgc->cmd)); memset(cgc->buffer, 0, 2); cgc->cmd[0] = GPCMD_MODE_SELECT_10; cgc->cmd[1] = 0x10; /* PF */ cgc->cmd[7] = cgc->buflen >> 8; cgc->cmd[8] = cgc->buflen & 0xff; cgc->data_direction = CGC_DATA_WRITE; return cdo->generic_packet(cdi, cgc); } static int cdrom_read_subchannel(struct cdrom_device_info *cdi, struct cdrom_subchnl *subchnl, int mcn) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; char buffer[32]; int ret; init_cdrom_command(&cgc, buffer, 16, CGC_DATA_READ); cgc.cmd[0] = GPCMD_READ_SUBCHANNEL; cgc.cmd[1] = subchnl->cdsc_format;/* MSF or LBA addressing */ cgc.cmd[2] = 0x40; /* request subQ data */ cgc.cmd[3] = mcn ? 2 : 1; cgc.cmd[8] = 16; if ((ret = cdo->generic_packet(cdi, &cgc))) return ret; subchnl->cdsc_audiostatus = cgc.buffer[1]; subchnl->cdsc_ctrl = cgc.buffer[5] & 0xf; subchnl->cdsc_trk = cgc.buffer[6]; subchnl->cdsc_ind = cgc.buffer[7]; if (subchnl->cdsc_format == CDROM_LBA) { subchnl->cdsc_absaddr.lba = ((cgc.buffer[8] << 24) | (cgc.buffer[9] << 16) | (cgc.buffer[10] << 8) | (cgc.buffer[11])); subchnl->cdsc_reladdr.lba = ((cgc.buffer[12] << 24) | (cgc.buffer[13] << 16) | (cgc.buffer[14] << 8) | (cgc.buffer[15])); } else { subchnl->cdsc_reladdr.msf.minute = cgc.buffer[13]; subchnl->cdsc_reladdr.msf.second = cgc.buffer[14]; subchnl->cdsc_reladdr.msf.frame = cgc.buffer[15]; subchnl->cdsc_absaddr.msf.minute = cgc.buffer[9]; subchnl->cdsc_absaddr.msf.second = cgc.buffer[10]; subchnl->cdsc_absaddr.msf.frame = cgc.buffer[11]; } return 0; } /* * Specific READ_10 interface */ static int cdrom_read_cd(struct cdrom_device_info *cdi, struct packet_command *cgc, int lba, int blocksize, int nblocks) { const struct cdrom_device_ops *cdo = cdi->ops; memset(&cgc->cmd, 0, sizeof(cgc->cmd)); cgc->cmd[0] = GPCMD_READ_10; cgc->cmd[2] = (lba >> 24) & 0xff; cgc->cmd[3] = (lba >> 16) & 0xff; cgc->cmd[4] = (lba >> 8) & 0xff; cgc->cmd[5] = lba & 0xff; cgc->cmd[6] = (nblocks >> 16) & 0xff; cgc->cmd[7] = (nblocks >> 8) & 0xff; cgc->cmd[8] = nblocks & 0xff; cgc->buflen = blocksize * nblocks; return cdo->generic_packet(cdi, cgc); } /* very generic interface for reading the various types of blocks */ static int cdrom_read_block(struct cdrom_device_info *cdi, struct packet_command *cgc, int lba, int nblocks, int format, int blksize) { const struct cdrom_device_ops *cdo = cdi->ops; memset(&cgc->cmd, 0, sizeof(cgc->cmd)); cgc->cmd[0] = GPCMD_READ_CD; /* expected sector size - cdda,mode1,etc. */ cgc->cmd[1] = format << 2; /* starting address */ cgc->cmd[2] = (lba >> 24) & 0xff; cgc->cmd[3] = (lba >> 16) & 0xff; cgc->cmd[4] = (lba >> 8) & 0xff; cgc->cmd[5] = lba & 0xff; /* number of blocks */ cgc->cmd[6] = (nblocks >> 16) & 0xff; cgc->cmd[7] = (nblocks >> 8) & 0xff; cgc->cmd[8] = nblocks & 0xff; cgc->buflen = blksize * nblocks; /* set the header info returned */ switch (blksize) { case CD_FRAMESIZE_RAW0 : cgc->cmd[9] = 0x58; break; case CD_FRAMESIZE_RAW1 : cgc->cmd[9] = 0x78; break; case CD_FRAMESIZE_RAW : cgc->cmd[9] = 0xf8; break; default : cgc->cmd[9] = 0x10; } return cdo->generic_packet(cdi, cgc); } static int cdrom_read_cdda_old(struct cdrom_device_info *cdi, __u8 __user *ubuf, int lba, int nframes) { struct packet_command cgc; int ret = 0; int nr; cdi->last_sense = 0; memset(&cgc, 0, sizeof(cgc)); /* * start with will ra.nframes size, back down if alloc fails */ nr = nframes; do { cgc.buffer = kmalloc_array(nr, CD_FRAMESIZE_RAW, GFP_KERNEL); if (cgc.buffer) break; nr >>= 1; } while (nr); if (!nr) return -ENOMEM; cgc.data_direction = CGC_DATA_READ; while (nframes > 0) { if (nr > nframes) nr = nframes; ret = cdrom_read_block(cdi, &cgc, lba, nr, 1, CD_FRAMESIZE_RAW); if (ret) break; if (copy_to_user(ubuf, cgc.buffer, CD_FRAMESIZE_RAW * nr)) { ret = -EFAULT; break; } ubuf += CD_FRAMESIZE_RAW * nr; nframes -= nr; lba += nr; } kfree(cgc.buffer); return ret; } static int cdrom_read_cdda_bpc(struct cdrom_device_info *cdi, __u8 __user *ubuf, int lba, int nframes) { struct request_queue *q = cdi->disk->queue; struct request *rq; struct scsi_request *req; struct bio *bio; unsigned int len; int nr, ret = 0; if (!q) return -ENXIO; if (!blk_queue_scsi_passthrough(q)) { WARN_ONCE(true, "Attempt read CDDA info through a non-SCSI queue\n"); return -EINVAL; } cdi->last_sense = 0; while (nframes) { nr = nframes; if (cdi->cdda_method == CDDA_BPC_SINGLE) nr = 1; if (nr * CD_FRAMESIZE_RAW > (queue_max_sectors(q) << 9)) nr = (queue_max_sectors(q) << 9) / CD_FRAMESIZE_RAW; len = nr * CD_FRAMESIZE_RAW; rq = blk_get_request(q, REQ_OP_SCSI_IN, 0); if (IS_ERR(rq)) { ret = PTR_ERR(rq); break; } req = scsi_req(rq); ret = blk_rq_map_user(q, rq, NULL, ubuf, len, GFP_KERNEL); if (ret) { blk_put_request(rq); break; } req->cmd[0] = GPCMD_READ_CD; req->cmd[1] = 1 << 2; req->cmd[2] = (lba >> 24) & 0xff; req->cmd[3] = (lba >> 16) & 0xff; req->cmd[4] = (lba >> 8) & 0xff; req->cmd[5] = lba & 0xff; req->cmd[6] = (nr >> 16) & 0xff; req->cmd[7] = (nr >> 8) & 0xff; req->cmd[8] = nr & 0xff; req->cmd[9] = 0xf8; req->cmd_len = 12; rq->timeout = 60 * HZ; bio = rq->bio; blk_execute_rq(q, cdi->disk, rq, 0); if (scsi_req(rq)->result) { struct scsi_sense_hdr sshdr; ret = -EIO; scsi_normalize_sense(req->sense, req->sense_len, &sshdr); cdi->last_sense = sshdr.sense_key; } if (blk_rq_unmap_user(bio)) ret = -EFAULT; blk_put_request(rq); if (ret) break; nframes -= nr; lba += nr; ubuf += len; } return ret; } static int cdrom_read_cdda(struct cdrom_device_info *cdi, __u8 __user *ubuf, int lba, int nframes) { int ret; if (cdi->cdda_method == CDDA_OLD) return cdrom_read_cdda_old(cdi, ubuf, lba, nframes); retry: /* * for anything else than success and io error, we need to retry */ ret = cdrom_read_cdda_bpc(cdi, ubuf, lba, nframes); if (!ret || ret != -EIO) return ret; /* * I've seen drives get sense 4/8/3 udma crc errors on multi * frame dma, so drop to single frame dma if we need to */ if (cdi->cdda_method == CDDA_BPC_FULL && nframes > 1) { pr_info("dropping to single frame dma\n"); cdi->cdda_method = CDDA_BPC_SINGLE; goto retry; } /* * so we have an io error of some sort with multi frame dma. if the * condition wasn't a hardware error * problems, not for any error */ if (cdi->last_sense != 0x04 && cdi->last_sense != 0x0b) return ret; pr_info("dropping to old style cdda (sense=%x)\n", cdi->last_sense); cdi->cdda_method = CDDA_OLD; return cdrom_read_cdda_old(cdi, ubuf, lba, nframes); } static int cdrom_ioctl_multisession(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_multisession ms_info; u8 requested_format; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMMULTISESSION\n"); if (!(cdi->ops->capability & CDC_MULTI_SESSION)) return -ENOSYS; if (copy_from_user(&ms_info, argp, sizeof(ms_info))) return -EFAULT; requested_format = ms_info.addr_format; if (requested_format != CDROM_MSF && requested_format != CDROM_LBA) return -EINVAL; ms_info.addr_format = CDROM_LBA; ret = cdi->ops->get_last_session(cdi, &ms_info); if (ret) return ret; sanitize_format(&ms_info.addr, &ms_info.addr_format, requested_format); if (copy_to_user(argp, &ms_info, sizeof(ms_info))) return -EFAULT; cd_dbg(CD_DO_IOCTL, "CDROMMULTISESSION successful\n"); return 0; } static int cdrom_ioctl_eject(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT\n"); if (!CDROM_CAN(CDC_OPEN_TRAY)) return -ENOSYS; if (cdi->use_count != 1 || cdi->keeplocked) return -EBUSY; if (CDROM_CAN(CDC_LOCK)) { int ret = cdi->ops->lock_door(cdi, 0); if (ret) return ret; } return cdi->ops->tray_move(cdi, 1); } static int cdrom_ioctl_closetray(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROMCLOSETRAY\n"); if (!CDROM_CAN(CDC_CLOSE_TRAY)) return -ENOSYS; return cdi->ops->tray_move(cdi, 0); } static int cdrom_ioctl_eject_sw(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROMEJECT_SW\n"); if (!CDROM_CAN(CDC_OPEN_TRAY)) return -ENOSYS; if (cdi->keeplocked) return -EBUSY; cdi->options &= ~(CDO_AUTO_CLOSE | CDO_AUTO_EJECT); if (arg) cdi->options |= CDO_AUTO_CLOSE | CDO_AUTO_EJECT; return 0; } static int cdrom_ioctl_media_changed(struct cdrom_device_info *cdi, unsigned long arg) { struct cdrom_changer_info *info; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROM_MEDIA_CHANGED\n"); if (!CDROM_CAN(CDC_MEDIA_CHANGED)) return -ENOSYS; /* cannot select disc or select current disc */ if (!CDROM_CAN(CDC_SELECT_DISC) || arg == CDSL_CURRENT) return media_changed(cdi, 1); if (arg >= cdi->capacity) return -EINVAL; info = kmalloc(sizeof(*info), GFP_KERNEL); if (!info) return -ENOMEM; ret = cdrom_read_mech_status(cdi, info); if (!ret) ret = info->slots[arg].change; kfree(info); return ret; } static int cdrom_ioctl_set_options(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SET_OPTIONS\n"); /* * Options need to be in sync with capability. * Too late for that, so we have to check each one separately. */ switch (arg) { case CDO_USE_FFLAGS: case CDO_CHECK_TYPE: break; case CDO_LOCK: if (!CDROM_CAN(CDC_LOCK)) return -ENOSYS; break; case 0: return cdi->options; /* default is basically CDO_[AUTO_CLOSE|AUTO_EJECT] */ default: if (!CDROM_CAN(arg)) return -ENOSYS; } cdi->options |= (int) arg; return cdi->options; } static int cdrom_ioctl_clear_options(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_CLEAR_OPTIONS\n"); cdi->options &= ~(int) arg; return cdi->options; } static int cdrom_ioctl_select_speed(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_SPEED\n"); if (!CDROM_CAN(CDC_SELECT_SPEED)) return -ENOSYS; return cdi->ops->select_speed(cdi, arg); } static int cdrom_ioctl_select_disc(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_SELECT_DISC\n"); if (!CDROM_CAN(CDC_SELECT_DISC)) return -ENOSYS; if (arg != CDSL_CURRENT && arg != CDSL_NONE) { if ((int)arg >= cdi->capacity) return -EINVAL; } /* * ->select_disc is a hook to allow a driver-specific way of * seleting disc. However, since there is no equivalent hook for * cdrom_slot_status this may not actually be useful... */ if (cdi->ops->select_disc) return cdi->ops->select_disc(cdi, arg); cd_dbg(CD_CHANGER, "Using generic cdrom_select_disc()\n"); return cdrom_select_disc(cdi, arg); } static int cdrom_ioctl_reset(struct cdrom_device_info *cdi, struct block_device *bdev) { cd_dbg(CD_DO_IOCTL, "entering CDROM_RESET\n"); if (!capable(CAP_SYS_ADMIN)) return -EACCES; if (!CDROM_CAN(CDC_RESET)) return -ENOSYS; invalidate_bdev(bdev); return cdi->ops->reset(cdi); } static int cdrom_ioctl_lock_door(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "%socking door\n", arg ? "L" : "Unl"); if (!CDROM_CAN(CDC_LOCK)) return -EDRIVE_CANT_DO_THIS; cdi->keeplocked = arg ? 1 : 0; /* * Don't unlock the door on multiple opens by default, but allow * root to do so. */ if (cdi->use_count != 1 && !arg && !capable(CAP_SYS_ADMIN)) return -EBUSY; return cdi->ops->lock_door(cdi, arg); } static int cdrom_ioctl_debug(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "%sabling debug\n", arg ? "En" : "Dis"); if (!capable(CAP_SYS_ADMIN)) return -EACCES; debug = arg ? 1 : 0; return debug; } static int cdrom_ioctl_get_capability(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_CAPABILITY\n"); return (cdi->ops->capability & ~cdi->mask); } /* * The following function is implemented, although very few audio * discs give Universal Product Code information, which should just be * the Medium Catalog Number on the box. Note, that the way the code * is written on the CD is /not/ uniform across all discs! */ static int cdrom_ioctl_get_mcn(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_mcn mcn; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROM_GET_MCN\n"); if (!(cdi->ops->capability & CDC_MCN)) return -ENOSYS; ret = cdi->ops->get_mcn(cdi, &mcn); if (ret) return ret; if (copy_to_user(argp, &mcn, sizeof(mcn))) return -EFAULT; cd_dbg(CD_DO_IOCTL, "CDROM_GET_MCN successful\n"); return 0; } static int cdrom_ioctl_drive_status(struct cdrom_device_info *cdi, unsigned long arg) { cd_dbg(CD_DO_IOCTL, "entering CDROM_DRIVE_STATUS\n"); if (!(cdi->ops->capability & CDC_DRIVE_STATUS)) return -ENOSYS; if (!CDROM_CAN(CDC_SELECT_DISC) || (arg == CDSL_CURRENT || arg == CDSL_NONE)) return cdi->ops->drive_status(cdi, CDSL_CURRENT); if (arg >= cdi->capacity) return -EINVAL; return cdrom_slot_status(cdi, arg); } /* * Ok, this is where problems start. The current interface for the * CDROM_DISC_STATUS ioctl is flawed. It makes the false assumption that * CDs are all CDS_DATA_1 or all CDS_AUDIO, etc. Unfortunately, while this * is often the case, it is also very common for CDs to have some tracks * with data, and some tracks with audio. Just because I feel like it, * I declare the following to be the best way to cope. If the CD has ANY * data tracks on it, it will be returned as a data CD. If it has any XA * tracks, I will return it as that. Now I could simplify this interface * by combining these returns with the above, but this more clearly * demonstrates the problem with the current interface. Too bad this * wasn't designed to use bitmasks... -Erik * * Well, now we have the option CDS_MIXED: a mixed-type CD. * User level programmers might feel the ioctl is not very useful. * ---david */ static int cdrom_ioctl_disc_status(struct cdrom_device_info *cdi) { tracktype tracks; cd_dbg(CD_DO_IOCTL, "entering CDROM_DISC_STATUS\n"); cdrom_count_tracks(cdi, &tracks); if (tracks.error) return tracks.error; /* Policy mode on */ if (tracks.audio > 0) { if (!tracks.data && !tracks.cdi && !tracks.xa) return CDS_AUDIO; else return CDS_MIXED; } if (tracks.cdi > 0) return CDS_XA_2_2; if (tracks.xa > 0) return CDS_XA_2_1; if (tracks.data > 0) return CDS_DATA_1; /* Policy mode off */ cd_dbg(CD_WARNING, "This disc doesn't have any tracks I recognize!\n"); return CDS_NO_INFO; } static int cdrom_ioctl_changer_nslots(struct cdrom_device_info *cdi) { cd_dbg(CD_DO_IOCTL, "entering CDROM_CHANGER_NSLOTS\n"); return cdi->capacity; } static int cdrom_ioctl_get_subchnl(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_subchnl q; u8 requested, back; int ret; /* cd_dbg(CD_DO_IOCTL,"entering CDROMSUBCHNL\n");*/ if (copy_from_user(&q, argp, sizeof(q))) return -EFAULT; requested = q.cdsc_format; if (requested != CDROM_MSF && requested != CDROM_LBA) return -EINVAL; q.cdsc_format = CDROM_MSF; ret = cdi->ops->audio_ioctl(cdi, CDROMSUBCHNL, &q); if (ret) return ret; back = q.cdsc_format; /* local copy */ sanitize_format(&q.cdsc_absaddr, &back, requested); sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested); if (copy_to_user(argp, &q, sizeof(q))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */ return 0; } static int cdrom_ioctl_read_tochdr(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_tochdr header; int ret; /* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCHDR\n"); */ if (copy_from_user(&header, argp, sizeof(header))) return -EFAULT; ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCHDR, &header); if (ret) return ret; if (copy_to_user(argp, &header, sizeof(header))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCHDR successful\n"); */ return 0; } static int cdrom_ioctl_read_tocentry(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_tocentry entry; u8 requested_format; int ret; /* cd_dbg(CD_DO_IOCTL, "entering CDROMREADTOCENTRY\n"); */ if (copy_from_user(&entry, argp, sizeof(entry))) return -EFAULT; requested_format = entry.cdte_format; if (requested_format != CDROM_MSF && requested_format != CDROM_LBA) return -EINVAL; /* make interface to low-level uniform */ entry.cdte_format = CDROM_MSF; ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &entry); if (ret) return ret; sanitize_format(&entry.cdte_addr, &entry.cdte_format, requested_format); if (copy_to_user(argp, &entry, sizeof(entry))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMREADTOCENTRY successful\n"); */ return 0; } static int cdrom_ioctl_play_msf(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_msf msf; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; if (copy_from_user(&msf, argp, sizeof(msf))) return -EFAULT; return cdi->ops->audio_ioctl(cdi, CDROMPLAYMSF, &msf); } static int cdrom_ioctl_play_trkind(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_ti ti; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYTRKIND\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; if (copy_from_user(&ti, argp, sizeof(ti))) return -EFAULT; ret = check_for_audio_disc(cdi, cdi->ops); if (ret) return ret; return cdi->ops->audio_ioctl(cdi, CDROMPLAYTRKIND, &ti); } static int cdrom_ioctl_volctrl(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_volctrl volume; cd_dbg(CD_DO_IOCTL, "entering CDROMVOLCTRL\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; if (copy_from_user(&volume, argp, sizeof(volume))) return -EFAULT; return cdi->ops->audio_ioctl(cdi, CDROMVOLCTRL, &volume); } static int cdrom_ioctl_volread(struct cdrom_device_info *cdi, void __user *argp) { struct cdrom_volctrl volume; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMVOLREAD\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; ret = cdi->ops->audio_ioctl(cdi, CDROMVOLREAD, &volume); if (ret) return ret; if (copy_to_user(argp, &volume, sizeof(volume))) return -EFAULT; return 0; } static int cdrom_ioctl_audioctl(struct cdrom_device_info *cdi, unsigned int cmd) { int ret; cd_dbg(CD_DO_IOCTL, "doing audio ioctl (start/stop/pause/resume)\n"); if (!CDROM_CAN(CDC_PLAY_AUDIO)) return -ENOSYS; ret = check_for_audio_disc(cdi, cdi->ops); if (ret) return ret; return cdi->ops->audio_ioctl(cdi, cmd, NULL); } /* * Required when we need to use READ_10 to issue other than 2048 block * reads */ static int cdrom_switch_blocksize(struct cdrom_device_info *cdi, int size) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; struct modesel_head mh; memset(&mh, 0, sizeof(mh)); mh.block_desc_length = 0x08; mh.block_length_med = (size >> 8) & 0xff; mh.block_length_lo = size & 0xff; memset(&cgc, 0, sizeof(cgc)); cgc.cmd[0] = 0x15; cgc.cmd[1] = 1 << 4; cgc.cmd[4] = 12; cgc.buflen = sizeof(mh); cgc.buffer = (char *) &mh; cgc.data_direction = CGC_DATA_WRITE; mh.block_desc_length = 0x08; mh.block_length_med = (size >> 8) & 0xff; mh.block_length_lo = size & 0xff; return cdo->generic_packet(cdi, &cgc); } static int cdrom_get_track_info(struct cdrom_device_info *cdi, __u16 track, __u8 type, track_information *ti) { const struct cdrom_device_ops *cdo = cdi->ops; struct packet_command cgc; int ret, buflen; init_cdrom_command(&cgc, ti, 8, CGC_DATA_READ); cgc.cmd[0] = GPCMD_READ_TRACK_RZONE_INFO; cgc.cmd[1] = type & 3; cgc.cmd[4] = (track & 0xff00) >> 8; cgc.cmd[5] = track & 0xff; cgc.cmd[8] = 8; cgc.quiet = 1; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; buflen = be16_to_cpu(ti->track_information_length) + sizeof(ti->track_information_length); if (buflen > sizeof(track_information)) buflen = sizeof(track_information); cgc.cmd[8] = cgc.buflen = buflen; ret = cdo->generic_packet(cdi, &cgc); if (ret) return ret; /* return actual fill size */ return buflen; } /* return the last written block on the CD-R media. this is for the udf file system. */ int cdrom_get_last_written(struct cdrom_device_info *cdi, long *last_written) { struct cdrom_tocentry toc; disc_information di; track_information ti; __u32 last_track; int ret = -1, ti_size; if (!CDROM_CAN(CDC_GENERIC_PACKET)) goto use_toc; ret = cdrom_get_disc_info(cdi, &di); if (ret < (int)(offsetof(typeof(di), last_track_lsb) + sizeof(di.last_track_lsb))) goto use_toc; /* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */ last_track = (di.last_track_msb << 8) | di.last_track_lsb; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); if (ti_size < (int)offsetof(typeof(ti), track_start)) goto use_toc; /* if this track is blank, try the previous. */ if (ti.blank) { if (last_track == 1) goto use_toc; last_track--; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); } if (ti_size < (int)(offsetof(typeof(ti), track_size) + sizeof(ti.track_size))) goto use_toc; /* if last recorded field is valid, return it. */ if (ti.lra_v && ti_size >= (int)(offsetof(typeof(ti), last_rec_address) + sizeof(ti.last_rec_address))) { *last_written = be32_to_cpu(ti.last_rec_address); } else { /* make it up instead */ *last_written = be32_to_cpu(ti.track_start) + be32_to_cpu(ti.track_size); if (ti.free_blocks) *last_written -= (be32_to_cpu(ti.free_blocks) + 7); } return 0; /* this is where we end up if the drive either can't do a GPCMD_READ_DISC_INFO or GPCMD_READ_TRACK_RZONE_INFO or if it doesn't give enough information or fails. then we return the toc contents. */ use_toc: toc.cdte_format = CDROM_MSF; toc.cdte_track = CDROM_LEADOUT; if ((ret = cdi->ops->audio_ioctl(cdi, CDROMREADTOCENTRY, &toc))) return ret; sanitize_format(&toc.cdte_addr, &toc.cdte_format, CDROM_LBA); *last_written = toc.cdte_addr.lba; return 0; } /* return the next writable block. also for udf file system. */ static int cdrom_get_next_writable(struct cdrom_device_info *cdi, long *next_writable) { disc_information di; track_information ti; __u16 last_track; int ret, ti_size; if (!CDROM_CAN(CDC_GENERIC_PACKET)) goto use_last_written; ret = cdrom_get_disc_info(cdi, &di); if (ret < 0 || ret < offsetof(typeof(di), last_track_lsb) + sizeof(di.last_track_lsb)) goto use_last_written; /* if unit didn't return msb, it's zeroed by cdrom_get_disc_info */ last_track = (di.last_track_msb << 8) | di.last_track_lsb; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); if (ti_size < 0 || ti_size < offsetof(typeof(ti), track_start)) goto use_last_written; /* if this track is blank, try the previous. */ if (ti.blank) { if (last_track == 1) goto use_last_written; last_track--; ti_size = cdrom_get_track_info(cdi, last_track, 1, &ti); if (ti_size < 0) goto use_last_written; } /* if next recordable address field is valid, use it. */ if (ti.nwa_v && ti_size >= offsetof(typeof(ti), next_writable) + sizeof(ti.next_writable)) { *next_writable = be32_to_cpu(ti.next_writable); return 0; } use_last_written: ret = cdrom_get_last_written(cdi, next_writable); if (ret) { *next_writable = 0; return ret; } else { *next_writable += 7; return 0; } } static noinline int mmc_ioctl_cdrom_read_data(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc, int cmd) { struct scsi_sense_hdr sshdr; struct cdrom_msf msf; int blocksize = 0, format = 0, lba; int ret; switch (cmd) { case CDROMREADRAW: blocksize = CD_FRAMESIZE_RAW; break; case CDROMREADMODE1: blocksize = CD_FRAMESIZE; format = 2; break; case CDROMREADMODE2: blocksize = CD_FRAMESIZE_RAW0; break; } if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf))) return -EFAULT; lba = msf_to_lba(msf.cdmsf_min0, msf.cdmsf_sec0, msf.cdmsf_frame0); /* FIXME: we need upper bound checking, too!! */ if (lba < 0) return -EINVAL; cgc->buffer = kzalloc(blocksize, GFP_KERNEL); if (cgc->buffer == NULL) return -ENOMEM; memset(&sshdr, 0, sizeof(sshdr)); cgc->sshdr = &sshdr; cgc->data_direction = CGC_DATA_READ; ret = cdrom_read_block(cdi, cgc, lba, 1, format, blocksize); if (ret && sshdr.sense_key == 0x05 && sshdr.asc == 0x20 && sshdr.ascq == 0x00) { /* * SCSI-II devices are not required to support * READ_CD, so let's try switching block size */ /* FIXME: switch back again... */ ret = cdrom_switch_blocksize(cdi, blocksize); if (ret) goto out; cgc->sshdr = NULL; ret = cdrom_read_cd(cdi, cgc, lba, blocksize, 1); ret |= cdrom_switch_blocksize(cdi, blocksize); } if (!ret && copy_to_user(arg, cgc->buffer, blocksize)) ret = -EFAULT; out: kfree(cgc->buffer); return ret; } static noinline int mmc_ioctl_cdrom_read_audio(struct cdrom_device_info *cdi, void __user *arg) { struct cdrom_read_audio ra; int lba; if (copy_from_user(&ra, (struct cdrom_read_audio __user *)arg, sizeof(ra))) return -EFAULT; if (ra.addr_format == CDROM_MSF) lba = msf_to_lba(ra.addr.msf.minute, ra.addr.msf.second, ra.addr.msf.frame); else if (ra.addr_format == CDROM_LBA) lba = ra.addr.lba; else return -EINVAL; /* FIXME: we need upper bound checking, too!! */ if (lba < 0 || ra.nframes <= 0 || ra.nframes > CD_FRAMES) return -EINVAL; return cdrom_read_cdda(cdi, ra.buf, lba, ra.nframes); } static noinline int mmc_ioctl_cdrom_subchannel(struct cdrom_device_info *cdi, void __user *arg) { int ret; struct cdrom_subchnl q; u_char requested, back; if (copy_from_user(&q, (struct cdrom_subchnl __user *)arg, sizeof(q))) return -EFAULT; requested = q.cdsc_format; if (!((requested == CDROM_MSF) || (requested == CDROM_LBA))) return -EINVAL; ret = cdrom_read_subchannel(cdi, &q, 0); if (ret) return ret; back = q.cdsc_format; /* local copy */ sanitize_format(&q.cdsc_absaddr, &back, requested); sanitize_format(&q.cdsc_reladdr, &q.cdsc_format, requested); if (copy_to_user((struct cdrom_subchnl __user *)arg, &q, sizeof(q))) return -EFAULT; /* cd_dbg(CD_DO_IOCTL, "CDROMSUBCHNL successful\n"); */ return 0; } static noinline int mmc_ioctl_cdrom_play_msf(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc) { const struct cdrom_device_ops *cdo = cdi->ops; struct cdrom_msf msf; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYMSF\n"); if (copy_from_user(&msf, (struct cdrom_msf __user *)arg, sizeof(msf))) return -EFAULT; cgc->cmd[0] = GPCMD_PLAY_AUDIO_MSF; cgc->cmd[3] = msf.cdmsf_min0; cgc->cmd[4] = msf.cdmsf_sec0; cgc->cmd[5] = msf.cdmsf_frame0; cgc->cmd[6] = msf.cdmsf_min1; cgc->cmd[7] = msf.cdmsf_sec1; cgc->cmd[8] = msf.cdmsf_frame1; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_cdrom_play_blk(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc) { const struct cdrom_device_ops *cdo = cdi->ops; struct cdrom_blk blk; cd_dbg(CD_DO_IOCTL, "entering CDROMPLAYBLK\n"); if (copy_from_user(&blk, (struct cdrom_blk __user *)arg, sizeof(blk))) return -EFAULT; cgc->cmd[0] = GPCMD_PLAY_AUDIO_10; cgc->cmd[2] = (blk.from >> 24) & 0xff; cgc->cmd[3] = (blk.from >> 16) & 0xff; cgc->cmd[4] = (blk.from >> 8) & 0xff; cgc->cmd[5] = blk.from & 0xff; cgc->cmd[7] = (blk.len >> 8) & 0xff; cgc->cmd[8] = blk.len & 0xff; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_cdrom_volume(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc, unsigned int cmd) { struct cdrom_volctrl volctrl; unsigned char buffer[32]; char mask[sizeof(buffer)]; unsigned short offset; int ret; cd_dbg(CD_DO_IOCTL, "entering CDROMVOLUME\n"); if (copy_from_user(&volctrl, (struct cdrom_volctrl __user *)arg, sizeof(volctrl))) return -EFAULT; cgc->buffer = buffer; cgc->buflen = 24; ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0); if (ret) return ret; /* originally the code depended on buffer[1] to determine how much data is available for transfer. buffer[1] is unfortunately ambigious and the only reliable way seem to be to simply skip over the block descriptor... */ offset = 8 + be16_to_cpu(*(__be16 *)(buffer + 6)); if (offset + 16 > sizeof(buffer)) return -E2BIG; if (offset + 16 > cgc->buflen) { cgc->buflen = offset + 16; ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 0); if (ret) return ret; } /* sanity check */ if ((buffer[offset] & 0x3f) != GPMODE_AUDIO_CTL_PAGE || buffer[offset + 1] < 14) return -EINVAL; /* now we have the current volume settings. if it was only a CDROMVOLREAD, return these values */ if (cmd == CDROMVOLREAD) { volctrl.channel0 = buffer[offset+9]; volctrl.channel1 = buffer[offset+11]; volctrl.channel2 = buffer[offset+13]; volctrl.channel3 = buffer[offset+15]; if (copy_to_user((struct cdrom_volctrl __user *)arg, &volctrl, sizeof(volctrl))) return -EFAULT; return 0; } /* get the volume mask */ cgc->buffer = mask; ret = cdrom_mode_sense(cdi, cgc, GPMODE_AUDIO_CTL_PAGE, 1); if (ret) return ret; buffer[offset + 9] = volctrl.channel0 & mask[offset + 9]; buffer[offset + 11] = volctrl.channel1 & mask[offset + 11]; buffer[offset + 13] = volctrl.channel2 & mask[offset + 13]; buffer[offset + 15] = volctrl.channel3 & mask[offset + 15]; /* set volume */ cgc->buffer = buffer + offset - 8; memset(cgc->buffer, 0, 8); return cdrom_mode_select(cdi, cgc); } static noinline int mmc_ioctl_cdrom_start_stop(struct cdrom_device_info *cdi, struct packet_command *cgc, int cmd) { const struct cdrom_device_ops *cdo = cdi->ops; cd_dbg(CD_DO_IOCTL, "entering CDROMSTART/CDROMSTOP\n"); cgc->cmd[0] = GPCMD_START_STOP_UNIT; cgc->cmd[1] = 1; cgc->cmd[4] = (cmd == CDROMSTART) ? 1 : 0; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_cdrom_pause_resume(struct cdrom_device_info *cdi, struct packet_command *cgc, int cmd) { const struct cdrom_device_ops *cdo = cdi->ops; cd_dbg(CD_DO_IOCTL, "entering CDROMPAUSE/CDROMRESUME\n"); cgc->cmd[0] = GPCMD_PAUSE_RESUME; cgc->cmd[8] = (cmd == CDROMRESUME) ? 1 : 0; cgc->data_direction = CGC_DATA_NONE; return cdo->generic_packet(cdi, cgc); } static noinline int mmc_ioctl_dvd_read_struct(struct cdrom_device_info *cdi, void __user *arg, struct packet_command *cgc) { int ret; dvd_struct *s; int size = sizeof(dvd_struct); if (!CDROM_CAN(CDC_DVD)) return -ENOSYS; s = memdup_user(arg, size); if (IS_ERR(s)) return PTR_ERR(s); cd_dbg(CD_DO_IOCTL, "entering DVD_READ_STRUCT\n"); ret = dvd_read_struct(cdi, s, cgc); if (ret) goto out; if (copy_to_user(arg, s, size)) ret = -EFAULT; out: kfree(s); return ret; } static noinline int mmc_ioctl_dvd_auth(struct cdrom_device_info *cdi, void __user *arg) { int ret; dvd_authinfo ai; if (!CDROM_CAN(CDC_DVD)) return -ENOSYS; cd_dbg(CD_DO_IOCTL, "entering DVD_AUTH\n"); if (copy_from_user(&ai, (dvd_authinfo __user *)arg, sizeof(ai))) return -EFAULT; ret = dvd_do_auth(cdi, &ai); if (ret) return ret; if (copy_to_user((dvd_authinfo __user *)arg, &ai, sizeof(ai))) return -EFAULT; return 0; } static noinline int mmc_ioctl_cdrom_next_writable(struct cdrom_device_info *cdi, void __user *arg) { int ret; long next = 0; cd_dbg(CD_DO_IOCTL, "entering CDROM_NEXT_WRITABLE\n"); ret = cdrom_get_next_writable(cdi, &next); if (ret) return ret; if (copy_to_user((long __user *)arg, &next, sizeof(next))) return -EFAULT; return 0; } static noinline int mmc_ioctl_cdrom_last_written(struct cdrom_device_info *cdi, void __user *arg) { int ret; long last = 0; cd_dbg(CD_DO_IOCTL, "entering CDROM_LAST_WRITTEN\n"); ret = cdrom_get_last_written(cdi, &last); if (ret) return ret; if (copy_to_user((long __user *)arg, &last, sizeof(last))) return -EFAULT; return 0; } static int mmc_ioctl(struct cdrom_device_info *cdi, unsigned int cmd, unsigned long arg) { struct packet_command cgc; void __user *userptr = (void __user *)arg; memset(&cgc, 0, sizeof(cgc)); /* build a unified command and queue it through cdo->generic_packet() */ switch (cmd) { case CDROMREADRAW: case CDROMREADMODE1: case CDROMREADMODE2: return mmc_ioctl_cdrom_read_data(cdi, userptr, &cgc, cmd); case CDROMREADAUDIO: return mmc_ioctl_cdrom_read_audio(cdi, userptr); case CDROMSUBCHNL: return mmc_ioctl_cdrom_subchannel(cdi, userptr); case CDROMPLAYMSF: return mmc_ioctl_cdrom_play_msf(cdi, userptr, &cgc); case CDROMPLAYBLK: return mmc_ioctl_cdrom_play_blk(cdi, userptr, &cgc); case CDROMVOLCTRL: case CDROMVOLREAD: return mmc_ioctl_cdrom_volume(cdi, userptr, &cgc, cmd); case CDROMSTART: case CDROMSTOP: return mmc_ioctl_cdrom_start_stop(cdi, &cgc, cmd); case CDROMPAUSE: case CDROMRESUME: return mmc_ioctl_cdrom_pause_resume(cdi, &cgc, cmd); case DVD_READ_STRUCT: return mmc_ioctl_dvd_read_struct(cdi, userptr, &cgc); case DVD_AUTH: return mmc_ioctl_dvd_auth(cdi, userptr); case CDROM_NEXT_WRITABLE: return mmc_ioctl_cdrom_next_writable(cdi, userptr); case CDROM_LAST_WRITTEN: return mmc_ioctl_cdrom_last_written(cdi, userptr); } return -ENOTTY; } /* * Just about every imaginable ioctl is supported in the Uniform layer * these days. * ATAPI / SCSI specific code now mainly resides in mmc_ioctl(). */ int cdrom_ioctl(struct cdrom_device_info *cdi, struct block_device *bdev, fmode_t mode, unsigned int cmd, unsigned long arg) { void __user *argp = (void __user *)arg; int ret; /* * Try the generic SCSI command ioctl's first. */ ret = scsi_cmd_blk_ioctl(bdev, mode, cmd, argp); if (ret != -ENOTTY) return ret; switch (cmd) { case CDROMMULTISESSION: return cdrom_ioctl_multisession(cdi, argp); case CDROMEJECT: return cdrom_ioctl_eject(cdi); case CDROMCLOSETRAY: return cdrom_ioctl_closetray(cdi); case CDROMEJECT_SW: return cdrom_ioctl_eject_sw(cdi, arg); case CDROM_MEDIA_CHANGED: return cdrom_ioctl_media_changed(cdi, arg); case CDROM_SET_OPTIONS: return cdrom_ioctl_set_options(cdi, arg); case CDROM_CLEAR_OPTIONS: return cdrom_ioctl_clear_options(cdi, arg); case CDROM_SELECT_SPEED: return cdrom_ioctl_select_speed(cdi, arg); case CDROM_SELECT_DISC: return cdrom_ioctl_select_disc(cdi, arg); case CDROMRESET: return cdrom_ioctl_reset(cdi, bdev); case CDROM_LOCKDOOR: return cdrom_ioctl_lock_door(cdi, arg); case CDROM_DEBUG: return cdrom_ioctl_debug(cdi, arg); case CDROM_GET_CAPABILITY: return cdrom_ioctl_get_capability(cdi); case CDROM_GET_MCN: return cdrom_ioctl_get_mcn(cdi, argp); case CDROM_DRIVE_STATUS: return cdrom_ioctl_drive_status(cdi, arg); case CDROM_DISC_STATUS: return cdrom_ioctl_disc_status(cdi); case CDROM_CHANGER_NSLOTS: return cdrom_ioctl_changer_nslots(cdi); } /* * Use the ioctls that are implemented through the generic_packet() * interface. this may look at bit funny, but if -ENOTTY is * returned that particular ioctl is not implemented and we * let it go through the device specific ones. */ if (CDROM_CAN(CDC_GENERIC_PACKET)) { ret = mmc_ioctl(cdi, cmd, arg); if (ret != -ENOTTY) return ret; } /* * Note: most of the cd_dbg() calls are commented out here, * because they fill up the sys log when CD players poll * the drive. */ switch (cmd) { case CDROMSUBCHNL: return cdrom_ioctl_get_subchnl(cdi, argp); case CDROMREADTOCHDR: return cdrom_ioctl_read_tochdr(cdi, argp); case CDROMREADTOCENTRY: return cdrom_ioctl_read_tocentry(cdi, argp); case CDROMPLAYMSF: return cdrom_ioctl_play_msf(cdi, argp); case CDROMPLAYTRKIND: return cdrom_ioctl_play_trkind(cdi, argp); case CDROMVOLCTRL: return cdrom_ioctl_volctrl(cdi, argp); case CDROMVOLREAD: return cdrom_ioctl_volread(cdi, argp); case CDROMSTART: case CDROMSTOP: case CDROMPAUSE: case CDROMRESUME: return cdrom_ioctl_audioctl(cdi, cmd); } return -ENOSYS; } EXPORT_SYMBOL(cdrom_get_last_written); EXPORT_SYMBOL(register_cdrom); EXPORT_SYMBOL(unregister_cdrom); EXPORT_SYMBOL(cdrom_open); EXPORT_SYMBOL(cdrom_release); EXPORT_SYMBOL(cdrom_ioctl); EXPORT_SYMBOL(cdrom_media_changed); EXPORT_SYMBOL(cdrom_number_of_slots); EXPORT_SYMBOL(cdrom_mode_select); EXPORT_SYMBOL(cdrom_mode_sense); EXPORT_SYMBOL(init_cdrom_command); EXPORT_SYMBOL(cdrom_get_media_event); #ifdef CONFIG_SYSCTL #define CDROM_STR_SIZE 1000 static struct cdrom_sysctl_settings { char info[CDROM_STR_SIZE]; /* general info */ int autoclose; /* close tray upon mount, etc */ int autoeject; /* eject on umount */ int debug; /* turn on debugging messages */ int lock; /* lock the door on device open */ int check; /* check media type */ } cdrom_sysctl_settings; enum cdrom_print_option { CTL_NAME, CTL_SPEED, CTL_SLOTS, CTL_CAPABILITY }; static int cdrom_print_info(const char *header, int val, char *info, int *pos, enum cdrom_print_option option) { const int max_size = sizeof(cdrom_sysctl_settings.info); struct cdrom_device_info *cdi; int ret; ret = scnprintf(info + *pos, max_size - *pos, header); if (!ret) return 1; *pos += ret; list_for_each_entry(cdi, &cdrom_list, list) { switch (option) { case CTL_NAME: ret = scnprintf(info + *pos, max_size - *pos, "\t%s", cdi->name); break; case CTL_SPEED: ret = scnprintf(info + *pos, max_size - *pos, "\t%d", cdi->speed); break; case CTL_SLOTS: ret = scnprintf(info + *pos, max_size - *pos, "\t%d", cdi->capacity); break; case CTL_CAPABILITY: ret = scnprintf(info + *pos, max_size - *pos, "\t%d", CDROM_CAN(val) != 0); break; default: pr_info("invalid option%d\n", option); return 1; } if (!ret) return 1; *pos += ret; } return 0; } static int cdrom_sysctl_info(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int pos; char *info = cdrom_sysctl_settings.info; const int max_size = sizeof(cdrom_sysctl_settings.info); if (!*lenp || (*ppos && !write)) { *lenp = 0; return 0; } mutex_lock(&cdrom_mutex); pos = sprintf(info, "CD-ROM information, " VERSION "\n"); if (cdrom_print_info("\ndrive name:\t", 0, info, &pos, CTL_NAME)) goto done; if (cdrom_print_info("\ndrive speed:\t", 0, info, &pos, CTL_SPEED)) goto done; if (cdrom_print_info("\ndrive # of slots:", 0, info, &pos, CTL_SLOTS)) goto done; if (cdrom_print_info("\nCan close tray:\t", CDC_CLOSE_TRAY, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan open tray:\t", CDC_OPEN_TRAY, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan lock tray:\t", CDC_LOCK, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan change speed:", CDC_SELECT_SPEED, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan select disk:", CDC_SELECT_DISC, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read multisession:", CDC_MULTI_SESSION, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read MCN:\t", CDC_MCN, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nReports media changed:", CDC_MEDIA_CHANGED, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan play audio:\t", CDC_PLAY_AUDIO, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write CD-R:\t", CDC_CD_R, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write CD-RW:", CDC_CD_RW, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read DVD:\t", CDC_DVD, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write DVD-R:", CDC_DVD_R, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write DVD-RAM:", CDC_DVD_RAM, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan read MRW:\t", CDC_MRW, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write MRW:\t", CDC_MRW_W, info, &pos, CTL_CAPABILITY)) goto done; if (cdrom_print_info("\nCan write RAM:\t", CDC_RAM, info, &pos, CTL_CAPABILITY)) goto done; if (!scnprintf(info + pos, max_size - pos, "\n\n")) goto done; doit: mutex_unlock(&cdrom_mutex); return proc_dostring(ctl, write, buffer, lenp, ppos); done: pr_info("info buffer too small\n"); goto doit; } /* Unfortunately, per device settings are not implemented through procfs/sysctl yet. When they are, this will naturally disappear. For now just update all drives. Later this will become the template on which new registered drives will be based. */ static void cdrom_update_settings(void) { struct cdrom_device_info *cdi; mutex_lock(&cdrom_mutex); list_for_each_entry(cdi, &cdrom_list, list) { if (autoclose && CDROM_CAN(CDC_CLOSE_TRAY)) cdi->options |= CDO_AUTO_CLOSE; else if (!autoclose) cdi->options &= ~CDO_AUTO_CLOSE; if (autoeject && CDROM_CAN(CDC_OPEN_TRAY)) cdi->options |= CDO_AUTO_EJECT; else if (!autoeject) cdi->options &= ~CDO_AUTO_EJECT; if (lockdoor && CDROM_CAN(CDC_LOCK)) cdi->options |= CDO_LOCK; else if (!lockdoor) cdi->options &= ~CDO_LOCK; if (check_media_type) cdi->options |= CDO_CHECK_TYPE; else cdi->options &= ~CDO_CHECK_TYPE; } mutex_unlock(&cdrom_mutex); } static int cdrom_sysctl_handler(struct ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; ret = proc_dointvec(ctl, write, buffer, lenp, ppos); if (write) { /* we only care for 1 or 0. */ autoclose = !!cdrom_sysctl_settings.autoclose; autoeject = !!cdrom_sysctl_settings.autoeject; debug = !!cdrom_sysctl_settings.debug; lockdoor = !!cdrom_sysctl_settings.lock; check_media_type = !!cdrom_sysctl_settings.check; /* update the option flags according to the changes. we don't have per device options through sysctl yet, but we will have and then this will disappear. */ cdrom_update_settings(); } return ret; } /* Place files in /proc/sys/dev/cdrom */ static struct ctl_table cdrom_table[] = { { .procname = "info", .data = &cdrom_sysctl_settings.info, .maxlen = CDROM_STR_SIZE, .mode = 0444, .proc_handler = cdrom_sysctl_info, }, { .procname = "autoclose", .data = &cdrom_sysctl_settings.autoclose, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "autoeject", .data = &cdrom_sysctl_settings.autoeject, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "debug", .data = &cdrom_sysctl_settings.debug, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "lock", .data = &cdrom_sysctl_settings.lock, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler, }, { .procname = "check_media", .data = &cdrom_sysctl_settings.check, .maxlen = sizeof(int), .mode = 0644, .proc_handler = cdrom_sysctl_handler }, { } }; static struct ctl_table cdrom_cdrom_table[] = { { .procname = "cdrom", .maxlen = 0, .mode = 0555, .child = cdrom_table, }, { } }; /* Make sure that /proc/sys/dev is there */ static struct ctl_table cdrom_root_table[] = { { .procname = "dev", .maxlen = 0, .mode = 0555, .child = cdrom_cdrom_table, }, { } }; static struct ctl_table_header *cdrom_sysctl_header; static void cdrom_sysctl_register(void) { static int initialized; if (initialized == 1) return; cdrom_sysctl_header = register_sysctl_table(cdrom_root_table); /* set the defaults */ cdrom_sysctl_settings.autoclose = autoclose; cdrom_sysctl_settings.autoeject = autoeject; cdrom_sysctl_settings.debug = debug; cdrom_sysctl_settings.lock = lockdoor; cdrom_sysctl_settings.check = check_media_type; initialized = 1; } static void cdrom_sysctl_unregister(void) { if (cdrom_sysctl_header) unregister_sysctl_table(cdrom_sysctl_header); } #else /* CONFIG_SYSCTL */ static void cdrom_sysctl_register(void) { } static void cdrom_sysctl_unregister(void) { } #endif /* CONFIG_SYSCTL */ static int __init cdrom_init(void) { cdrom_sysctl_register(); return 0; } static void __exit cdrom_exit(void) { pr_info("Uniform CD-ROM driver unloaded\n"); cdrom_sysctl_unregister(); } module_init(cdrom_init); module_exit(cdrom_exit); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/bad_432_0
crossvul-cpp_data_good_2371_0
/* * Copyright (C) 1995 Linus Torvalds * * Pentium III FXSR, SSE support * Gareth Hughes <gareth@valinux.com>, May 2000 * * X86-64 port * Andi Kleen. * * CPU hotplug support - ashok.raj@intel.com */ /* * This file handles the architecture-dependent parts of process handling.. */ #include <linux/cpu.h> #include <linux/errno.h> #include <linux/sched.h> #include <linux/fs.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/elfcore.h> #include <linux/smp.h> #include <linux/slab.h> #include <linux/user.h> #include <linux/interrupt.h> #include <linux/delay.h> #include <linux/module.h> #include <linux/ptrace.h> #include <linux/notifier.h> #include <linux/kprobes.h> #include <linux/kdebug.h> #include <linux/prctl.h> #include <linux/uaccess.h> #include <linux/io.h> #include <linux/ftrace.h> #include <asm/pgtable.h> #include <asm/processor.h> #include <asm/i387.h> #include <asm/fpu-internal.h> #include <asm/mmu_context.h> #include <asm/prctl.h> #include <asm/desc.h> #include <asm/proto.h> #include <asm/ia32.h> #include <asm/idle.h> #include <asm/syscalls.h> #include <asm/debugreg.h> #include <asm/switch_to.h> asmlinkage extern void ret_from_fork(void); __visible DEFINE_PER_CPU(unsigned long, old_rsp); /* Prints also some state that isn't saved in the pt_regs */ void __show_regs(struct pt_regs *regs, int all) { unsigned long cr0 = 0L, cr2 = 0L, cr3 = 0L, cr4 = 0L, fs, gs, shadowgs; unsigned long d0, d1, d2, d3, d6, d7; unsigned int fsindex, gsindex; unsigned int ds, cs, es; printk(KERN_DEFAULT "RIP: %04lx:[<%016lx>] ", regs->cs & 0xffff, regs->ip); printk_address(regs->ip); printk(KERN_DEFAULT "RSP: %04lx:%016lx EFLAGS: %08lx\n", regs->ss, regs->sp, regs->flags); printk(KERN_DEFAULT "RAX: %016lx RBX: %016lx RCX: %016lx\n", regs->ax, regs->bx, regs->cx); printk(KERN_DEFAULT "RDX: %016lx RSI: %016lx RDI: %016lx\n", regs->dx, regs->si, regs->di); printk(KERN_DEFAULT "RBP: %016lx R08: %016lx R09: %016lx\n", regs->bp, regs->r8, regs->r9); printk(KERN_DEFAULT "R10: %016lx R11: %016lx R12: %016lx\n", regs->r10, regs->r11, regs->r12); printk(KERN_DEFAULT "R13: %016lx R14: %016lx R15: %016lx\n", regs->r13, regs->r14, regs->r15); asm("movl %%ds,%0" : "=r" (ds)); asm("movl %%cs,%0" : "=r" (cs)); asm("movl %%es,%0" : "=r" (es)); asm("movl %%fs,%0" : "=r" (fsindex)); asm("movl %%gs,%0" : "=r" (gsindex)); rdmsrl(MSR_FS_BASE, fs); rdmsrl(MSR_GS_BASE, gs); rdmsrl(MSR_KERNEL_GS_BASE, shadowgs); if (!all) return; cr0 = read_cr0(); cr2 = read_cr2(); cr3 = read_cr3(); cr4 = read_cr4(); printk(KERN_DEFAULT "FS: %016lx(%04x) GS:%016lx(%04x) knlGS:%016lx\n", fs, fsindex, gs, gsindex, shadowgs); printk(KERN_DEFAULT "CS: %04x DS: %04x ES: %04x CR0: %016lx\n", cs, ds, es, cr0); printk(KERN_DEFAULT "CR2: %016lx CR3: %016lx CR4: %016lx\n", cr2, cr3, cr4); get_debugreg(d0, 0); get_debugreg(d1, 1); get_debugreg(d2, 2); get_debugreg(d3, 3); get_debugreg(d6, 6); get_debugreg(d7, 7); /* Only print out debug registers if they are in their non-default state. */ if ((d0 == 0) && (d1 == 0) && (d2 == 0) && (d3 == 0) && (d6 == DR6_RESERVED) && (d7 == 0x400)) return; printk(KERN_DEFAULT "DR0: %016lx DR1: %016lx DR2: %016lx\n", d0, d1, d2); printk(KERN_DEFAULT "DR3: %016lx DR6: %016lx DR7: %016lx\n", d3, d6, d7); } void release_thread(struct task_struct *dead_task) { if (dead_task->mm) { if (dead_task->mm->context.size) { pr_warn("WARNING: dead process %s still has LDT? <%p/%d>\n", dead_task->comm, dead_task->mm->context.ldt, dead_task->mm->context.size); BUG(); } } } static inline void set_32bit_tls(struct task_struct *t, int tls, u32 addr) { struct user_desc ud = { .base_addr = addr, .limit = 0xfffff, .seg_32bit = 1, .limit_in_pages = 1, .useable = 1, }; struct desc_struct *desc = t->thread.tls_array; desc += tls; fill_ldt(desc, &ud); } static inline u32 read_32bit_tls(struct task_struct *t, int tls) { return get_desc_base(&t->thread.tls_array[tls]); } int copy_thread(unsigned long clone_flags, unsigned long sp, unsigned long arg, struct task_struct *p) { int err; struct pt_regs *childregs; struct task_struct *me = current; p->thread.sp0 = (unsigned long)task_stack_page(p) + THREAD_SIZE; childregs = task_pt_regs(p); p->thread.sp = (unsigned long) childregs; p->thread.usersp = me->thread.usersp; set_tsk_thread_flag(p, TIF_FORK); p->thread.io_bitmap_ptr = NULL; savesegment(gs, p->thread.gsindex); p->thread.gs = p->thread.gsindex ? 0 : me->thread.gs; savesegment(fs, p->thread.fsindex); p->thread.fs = p->thread.fsindex ? 0 : me->thread.fs; savesegment(es, p->thread.es); savesegment(ds, p->thread.ds); memset(p->thread.ptrace_bps, 0, sizeof(p->thread.ptrace_bps)); if (unlikely(p->flags & PF_KTHREAD)) { /* kernel thread */ memset(childregs, 0, sizeof(struct pt_regs)); childregs->sp = (unsigned long)childregs; childregs->ss = __KERNEL_DS; childregs->bx = sp; /* function */ childregs->bp = arg; childregs->orig_ax = -1; childregs->cs = __KERNEL_CS | get_kernel_rpl(); childregs->flags = X86_EFLAGS_IF | X86_EFLAGS_FIXED; return 0; } *childregs = *current_pt_regs(); childregs->ax = 0; if (sp) childregs->sp = sp; err = -ENOMEM; if (unlikely(test_tsk_thread_flag(me, TIF_IO_BITMAP))) { p->thread.io_bitmap_ptr = kmemdup(me->thread.io_bitmap_ptr, IO_BITMAP_BYTES, GFP_KERNEL); if (!p->thread.io_bitmap_ptr) { p->thread.io_bitmap_max = 0; return -ENOMEM; } set_tsk_thread_flag(p, TIF_IO_BITMAP); } /* * Set a new TLS for the child thread? */ if (clone_flags & CLONE_SETTLS) { #ifdef CONFIG_IA32_EMULATION if (test_thread_flag(TIF_IA32)) err = do_set_thread_area(p, -1, (struct user_desc __user *)childregs->si, 0); else #endif err = do_arch_prctl(p, ARCH_SET_FS, childregs->r8); if (err) goto out; } err = 0; out: if (err && p->thread.io_bitmap_ptr) { kfree(p->thread.io_bitmap_ptr); p->thread.io_bitmap_max = 0; } return err; } static void start_thread_common(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp, unsigned int _cs, unsigned int _ss, unsigned int _ds) { loadsegment(fs, 0); loadsegment(es, _ds); loadsegment(ds, _ds); load_gs_index(0); current->thread.usersp = new_sp; regs->ip = new_ip; regs->sp = new_sp; this_cpu_write(old_rsp, new_sp); regs->cs = _cs; regs->ss = _ss; regs->flags = X86_EFLAGS_IF; } void start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp) { start_thread_common(regs, new_ip, new_sp, __USER_CS, __USER_DS, 0); } #ifdef CONFIG_IA32_EMULATION void start_thread_ia32(struct pt_regs *regs, u32 new_ip, u32 new_sp) { start_thread_common(regs, new_ip, new_sp, test_thread_flag(TIF_X32) ? __USER_CS : __USER32_CS, __USER_DS, __USER_DS); } #endif /* * switch_to(x,y) should switch tasks from x to y. * * This could still be optimized: * - fold all the options into a flag word and test it with a single test. * - could test fs/gs bitsliced * * Kprobes not supported here. Set the probe on schedule instead. * Function graph tracer not supported too. */ __visible __notrace_funcgraph struct task_struct * __switch_to(struct task_struct *prev_p, struct task_struct *next_p) { struct thread_struct *prev = &prev_p->thread; struct thread_struct *next = &next_p->thread; int cpu = smp_processor_id(); struct tss_struct *tss = &per_cpu(init_tss, cpu); unsigned fsindex, gsindex; fpu_switch_t fpu; fpu = switch_fpu_prepare(prev_p, next_p, cpu); /* Reload esp0 and ss1. */ load_sp0(tss, next); /* We must save %fs and %gs before load_TLS() because * %fs and %gs may be cleared by load_TLS(). * * (e.g. xen_load_tls()) */ savesegment(fs, fsindex); savesegment(gs, gsindex); /* * Load TLS before restoring any segments so that segment loads * reference the correct GDT entries. */ load_TLS(next, cpu); /* * Leave lazy mode, flushing any hypercalls made here. This * must be done after loading TLS entries in the GDT but before * loading segments that might reference them, and and it must * be done before math_state_restore, so the TS bit is up to * date. */ arch_end_context_switch(next_p); /* Switch DS and ES. * * Reading them only returns the selectors, but writing them (if * nonzero) loads the full descriptor from the GDT or LDT. The * LDT for next is loaded in switch_mm, and the GDT is loaded * above. * * We therefore need to write new values to the segment * registers on every context switch unless both the new and old * values are zero. * * Note that we don't need to do anything for CS and SS, as * those are saved and restored as part of pt_regs. */ savesegment(es, prev->es); if (unlikely(next->es | prev->es)) loadsegment(es, next->es); savesegment(ds, prev->ds); if (unlikely(next->ds | prev->ds)) loadsegment(ds, next->ds); /* * Switch FS and GS. * * These are even more complicated than FS and GS: they have * 64-bit bases are that controlled by arch_prctl. Those bases * only differ from the values in the GDT or LDT if the selector * is 0. * * Loading the segment register resets the hidden base part of * the register to 0 or the value from the GDT / LDT. If the * next base address zero, writing 0 to the segment register is * much faster than using wrmsr to explicitly zero the base. * * The thread_struct.fs and thread_struct.gs values are 0 * if the fs and gs bases respectively are not overridden * from the values implied by fsindex and gsindex. They * are nonzero, and store the nonzero base addresses, if * the bases are overridden. * * (fs != 0 && fsindex != 0) || (gs != 0 && gsindex != 0) should * be impossible. * * Therefore we need to reload the segment registers if either * the old or new selector is nonzero, and we need to override * the base address if next thread expects it to be overridden. * * This code is unnecessarily slow in the case where the old and * new indexes are zero and the new base is nonzero -- it will * unnecessarily write 0 to the selector before writing the new * base address. * * Note: This all depends on arch_prctl being the only way that * user code can override the segment base. Once wrfsbase and * wrgsbase are enabled, most of this code will need to change. */ if (unlikely(fsindex | next->fsindex | prev->fs)) { loadsegment(fs, next->fsindex); /* * If user code wrote a nonzero value to FS, then it also * cleared the overridden base address. * * XXX: if user code wrote 0 to FS and cleared the base * address itself, we won't notice and we'll incorrectly * restore the prior base address next time we reschdule * the process. */ if (fsindex) prev->fs = 0; } if (next->fs) wrmsrl(MSR_FS_BASE, next->fs); prev->fsindex = fsindex; if (unlikely(gsindex | next->gsindex | prev->gs)) { load_gs_index(next->gsindex); /* This works (and fails) the same way as fsindex above. */ if (gsindex) prev->gs = 0; } if (next->gs) wrmsrl(MSR_KERNEL_GS_BASE, next->gs); prev->gsindex = gsindex; switch_fpu_finish(next_p, fpu); /* * Switch the PDA and FPU contexts. */ prev->usersp = this_cpu_read(old_rsp); this_cpu_write(old_rsp, next->usersp); this_cpu_write(current_task, next_p); /* * If it were not for PREEMPT_ACTIVE we could guarantee that the * preempt_count of all tasks was equal here and this would not be * needed. */ task_thread_info(prev_p)->saved_preempt_count = this_cpu_read(__preempt_count); this_cpu_write(__preempt_count, task_thread_info(next_p)->saved_preempt_count); this_cpu_write(kernel_stack, (unsigned long)task_stack_page(next_p) + THREAD_SIZE - KERNEL_STACK_OFFSET); /* * Now maybe reload the debug registers and handle I/O bitmaps */ if (unlikely(task_thread_info(next_p)->flags & _TIF_WORK_CTXSW_NEXT || task_thread_info(prev_p)->flags & _TIF_WORK_CTXSW_PREV)) __switch_to_xtra(prev_p, next_p, tss); return prev_p; } void set_personality_64bit(void) { /* inherit personality from parent */ /* Make sure to be in 64bit mode */ clear_thread_flag(TIF_IA32); clear_thread_flag(TIF_ADDR32); clear_thread_flag(TIF_X32); /* Ensure the corresponding mm is not marked. */ if (current->mm) current->mm->context.ia32_compat = 0; /* TBD: overwrites user setup. Should have two bits. But 64bit processes have always behaved this way, so it's not too bad. The main problem is just that 32bit childs are affected again. */ current->personality &= ~READ_IMPLIES_EXEC; } void set_personality_ia32(bool x32) { /* inherit personality from parent */ /* Make sure to be in 32bit mode */ set_thread_flag(TIF_ADDR32); /* Mark the associated mm as containing 32-bit tasks. */ if (x32) { clear_thread_flag(TIF_IA32); set_thread_flag(TIF_X32); if (current->mm) current->mm->context.ia32_compat = TIF_X32; current->personality &= ~READ_IMPLIES_EXEC; /* is_compat_task() uses the presence of the x32 syscall bit flag to determine compat status */ current_thread_info()->status &= ~TS_COMPAT; } else { set_thread_flag(TIF_IA32); clear_thread_flag(TIF_X32); if (current->mm) current->mm->context.ia32_compat = TIF_IA32; current->personality |= force_personality32; /* Prepare the first "return" to user space */ current_thread_info()->status |= TS_COMPAT; } } EXPORT_SYMBOL_GPL(set_personality_ia32); unsigned long get_wchan(struct task_struct *p) { unsigned long stack; u64 fp, ip; int count = 0; if (!p || p == current || p->state == TASK_RUNNING) return 0; stack = (unsigned long)task_stack_page(p); if (p->thread.sp < stack || p->thread.sp >= stack+THREAD_SIZE) return 0; fp = *(u64 *)(p->thread.sp); do { if (fp < (unsigned long)stack || fp >= (unsigned long)stack+THREAD_SIZE) return 0; ip = *(u64 *)(fp+8); if (!in_sched_functions(ip)) return ip; fp = *(u64 *)fp; } while (count++ < 16); return 0; } long do_arch_prctl(struct task_struct *task, int code, unsigned long addr) { int ret = 0; int doit = task == current; int cpu; switch (code) { case ARCH_SET_GS: if (addr >= TASK_SIZE_OF(task)) return -EPERM; cpu = get_cpu(); /* handle small bases via the GDT because that's faster to switch. */ if (addr <= 0xffffffff) { set_32bit_tls(task, GS_TLS, addr); if (doit) { load_TLS(&task->thread, cpu); load_gs_index(GS_TLS_SEL); } task->thread.gsindex = GS_TLS_SEL; task->thread.gs = 0; } else { task->thread.gsindex = 0; task->thread.gs = addr; if (doit) { load_gs_index(0); ret = wrmsrl_safe(MSR_KERNEL_GS_BASE, addr); } } put_cpu(); break; case ARCH_SET_FS: /* Not strictly needed for fs, but do it for symmetry with gs */ if (addr >= TASK_SIZE_OF(task)) return -EPERM; cpu = get_cpu(); /* handle small bases via the GDT because that's faster to switch. */ if (addr <= 0xffffffff) { set_32bit_tls(task, FS_TLS, addr); if (doit) { load_TLS(&task->thread, cpu); loadsegment(fs, FS_TLS_SEL); } task->thread.fsindex = FS_TLS_SEL; task->thread.fs = 0; } else { task->thread.fsindex = 0; task->thread.fs = addr; if (doit) { /* set the selector to 0 to not confuse __switch_to */ loadsegment(fs, 0); ret = wrmsrl_safe(MSR_FS_BASE, addr); } } put_cpu(); break; case ARCH_GET_FS: { unsigned long base; if (task->thread.fsindex == FS_TLS_SEL) base = read_32bit_tls(task, FS_TLS); else if (doit) rdmsrl(MSR_FS_BASE, base); else base = task->thread.fs; ret = put_user(base, (unsigned long __user *)addr); break; } case ARCH_GET_GS: { unsigned long base; unsigned gsindex; if (task->thread.gsindex == GS_TLS_SEL) base = read_32bit_tls(task, GS_TLS); else if (doit) { savesegment(gs, gsindex); if (gsindex) rdmsrl(MSR_KERNEL_GS_BASE, base); else base = task->thread.gs; } else base = task->thread.gs; ret = put_user(base, (unsigned long __user *)addr); break; } default: ret = -EINVAL; break; } return ret; } long sys_arch_prctl(int code, unsigned long addr) { return do_arch_prctl(current, code, addr); } unsigned long KSTK_ESP(struct task_struct *task) { return (test_tsk_thread_flag(task, TIF_IA32)) ? (task_pt_regs(task)->sp) : ((task)->thread.usersp); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2371_0
crossvul-cpp_data_bad_1674_0
/* Copyright (C) 2011 ABRT Team Copyright (C) 2011 RedHat inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <gtk/gtk.h> #include <gdk/gdkkeysyms.h> #include "client.h" #include "internal_libreport_gtk.h" #include "wizard.h" #include "search_item.h" #include "libreport_types.h" #include "global_configuration.h" #define DEFAULT_WIDTH 800 #define DEFAULT_HEIGHT 500 #define EMERGENCY_ANALYSIS_EVENT_NAME "report_EmergencyAnalysis" #define FORBIDDEN_WORDS_BLACKLLIST "forbidden_words.conf" #define FORBIDDEN_WORDS_WHITELIST "ignored_words.conf" #if GTK_MAJOR_VERSION == 2 && GTK_MINOR_VERSION < 22 # define gtk_assistant_commit(...) ((void)0) # define GDK_KEY_Delete GDK_Delete # define GDK_KEY_KP_Delete GDK_KP_Delete #endif /* For Fedora 16 and gtk3 < 3.4.4*/ #ifndef GDK_BUTTON_PRIMARY # define GDK_BUTTON_PRIMARY 1 #endif typedef struct event_gui_data_t { char *event_name; GtkToggleButton *toggle_button; } event_gui_data_t; /* Using GHashTable as a set of file names */ /* Each table key has associated an nonzero integer and it allows us */ /* to write the following statements: */ /* if(g_hash_table_lookup(g_loaded_texts, FILENAME_COMMENT)) ... */ static GHashTable *g_loaded_texts; static char *g_event_selected; static unsigned g_black_event_count = 0; static pid_t g_event_child_pid = 0; static guint g_event_source_id = 0; static bool g_expert_mode; static GtkNotebook *g_assistant; static GtkWindow *g_wnd_assistant; static GtkBox *g_box_assistant; static GtkWidget *g_btn_stop; static GtkWidget *g_btn_close; static GtkWidget *g_btn_next; static GtkWidget *g_btn_onfail; static GtkWidget *g_btn_repeat; static GtkWidget *g_btn_detail; static GtkBox *g_box_events; static GtkBox *g_box_workflows; /* List of event_gui_data's */ static GList *g_list_events; static GtkLabel *g_lbl_event_log; static GtkTextView *g_tv_event_log; /* List of event_gui_data's */ /* List of event_gui_data's */ static GtkContainer *g_container_details1; static GtkContainer *g_container_details2; static GtkLabel *g_lbl_cd_reason; static GtkTextView *g_tv_comment; static GtkEventBox *g_eb_comment; static GtkCheckButton *g_cb_no_comment; static GtkWidget *g_widget_warnings_area; static GtkBox *g_box_warning_labels; static GtkToggleButton *g_tb_approve_bt; static GtkButton *g_btn_add_file; static GtkLabel *g_lbl_size; static GtkTreeView *g_tv_details; static GtkCellRenderer *g_tv_details_renderer_value; static GtkTreeViewColumn *g_tv_details_col_checkbox; //static GtkCellRenderer *g_tv_details_renderer_checkbox; static GtkListStore *g_ls_details; static GtkBox *g_box_buttons; //TODO: needs not be global static GtkNotebook *g_notebook; static GtkListStore *g_ls_sensitive_list; static GtkTreeView *g_tv_sensitive_list; static GtkTreeSelection *g_tv_sensitive_sel; static GtkRadioButton *g_rb_forbidden_words; static GtkRadioButton *g_rb_custom_search; static GtkExpander *g_exp_search; static gulong g_tv_sensitive_sel_hndlr; static gboolean g_warning_issued; static GtkSpinner *g_spinner_event_log; static GtkImage *g_img_process_fail; static GtkButton *g_btn_startcast; static GtkExpander *g_exp_report_log; static GtkWidget *g_top_most_window; static void add_workflow_buttons(GtkBox *box, GHashTable *workflows, GCallback func); static void set_auto_event_chain(GtkButton *button, gpointer user_data); static void start_event_run(const char *event_name); enum { /* Note: need to update types in * gtk_list_store_new(DETAIL_NUM_COLUMNS, TYPE1, TYPE2...) * if you change these: */ DETAIL_COLUMN_CHECKBOX, DETAIL_COLUMN_NAME, DETAIL_COLUMN_VALUE, DETAIL_NUM_COLUMNS, }; /* Search in bt */ static guint g_timeout = 0; static GtkEntry *g_search_entry_bt; static const gchar *g_search_text; static search_item_t *g_current_highlighted_word; enum { SEARCH_COLUMN_FILE, SEARCH_COLUMN_TEXT, SEARCH_COLUMN_ITEM, }; static GtkBuilder *g_builder; static PangoFontDescription *g_monospace_font; /* THE PAGE FLOW * page_0: introduction/summary * page_1: user comments * page_2: event selection * page_3: backtrace editor * page_4: summary * page_5: reporting progress * page_6: finished */ enum { PAGENO_SUMMARY, // 0 PAGENO_EVENT_SELECTOR, // 1 PAGENO_EDIT_COMMENT, // 2 PAGENO_EDIT_ELEMENTS, // 3 PAGENO_REVIEW_DATA, // 4 PAGENO_EVENT_PROGRESS, // 5 PAGENO_EVENT_DONE, // 6 PAGENO_NOT_SHOWN, // 7 NUM_PAGES // 8 }; /* Use of arrays (instead of, say, #defines to C strings) * allows cheaper page_obj_t->name == PAGE_FOO comparisons * instead of strcmp. */ static const gchar PAGE_SUMMARY[] = "page_0"; static const gchar PAGE_EVENT_SELECTOR[] = "page_1"; static const gchar PAGE_EDIT_COMMENT[] = "page_2"; static const gchar PAGE_EDIT_ELEMENTS[] = "page_3"; static const gchar PAGE_REVIEW_DATA[] = "page_4"; static const gchar PAGE_EVENT_PROGRESS[] = "page_5"; static const gchar PAGE_EVENT_DONE[] = "page_6"; static const gchar PAGE_NOT_SHOWN[] = "page_7"; static const gchar *const page_names[] = { PAGE_SUMMARY, PAGE_EVENT_SELECTOR, PAGE_EDIT_COMMENT, PAGE_EDIT_ELEMENTS, PAGE_REVIEW_DATA, PAGE_EVENT_PROGRESS, PAGE_EVENT_DONE, PAGE_NOT_SHOWN, NULL }; #define PRIVATE_TICKET_CB "private_ticket_cb" #define SENSITIVE_DATA_WARN "sensitive_data_warning" #define SENSITIVE_LIST "ls_sensitive_words" static const gchar *misc_widgets[] = { SENSITIVE_DATA_WARN, SENSITIVE_LIST, NULL }; typedef struct { const gchar *name; const gchar *title; GtkWidget *page_widget; int page_no; } page_obj_t; static page_obj_t pages[NUM_PAGES]; static struct strbuf *cmd_output = NULL; /* Utility functions */ static void clear_warnings(void); static void show_warnings(void); static void add_warning(const char *warning); static bool check_minimal_bt_rating(const char *event_name); static char *get_next_processed_event(GList **events_list); static void on_next_btn_cb(GtkWidget *btn, gpointer user_data); /* wizard.glade file as a string WIZARD_GLADE_CONTENTS: */ #include "wizard_glade.c" static GtkBuilder *make_builder() { GError *error = NULL; GtkBuilder *builder = gtk_builder_new(); if (!g_glade_file) { /* load additional widgets from glade */ gtk_builder_add_objects_from_string(builder, WIZARD_GLADE_CONTENTS, sizeof(WIZARD_GLADE_CONTENTS) - 1, (gchar**)misc_widgets, &error); if (error != NULL) error_msg_and_die("Error loading glade data: %s", error->message); /* Load pages from internal string */ gtk_builder_add_objects_from_string(builder, WIZARD_GLADE_CONTENTS, sizeof(WIZARD_GLADE_CONTENTS) - 1, (gchar**)page_names, &error); if (error != NULL) error_msg_and_die("Error loading glade data: %s", error->message); } else { /* -g FILE: load UI from it */ /* load additional widgets from glade */ gtk_builder_add_objects_from_file(builder, g_glade_file, (gchar**)misc_widgets, &error); if (error != NULL) error_msg_and_die("Can't load %s: %s", g_glade_file, error->message); gtk_builder_add_objects_from_file(builder, g_glade_file, (gchar**)page_names, &error); if (error != NULL) error_msg_and_die("Can't load %s: %s", g_glade_file, error->message); } return builder; } static void label_wrapper(GtkWidget *widget, gpointer data_unused) { if (GTK_IS_CONTAINER(widget)) { gtk_container_foreach((GtkContainer*)widget, label_wrapper, NULL); return; } if (GTK_IS_LABEL(widget)) { GtkLabel *label = (GtkLabel*)widget; gtk_label_set_line_wrap(label, 1); //const char *txt = gtk_label_get_label(label); //log("label '%s' set to wrap", txt); } } static void wrap_all_labels(GtkWidget *widget) { label_wrapper(widget, NULL); } static void wrap_fixer(GtkWidget *widget, gpointer data_unused) { if (GTK_IS_CONTAINER(widget)) { gtk_container_foreach((GtkContainer*)widget, wrap_fixer, NULL); return; } if (GTK_IS_LABEL(widget)) { GtkLabel *label = (GtkLabel*)widget; //const char *txt = gtk_label_get_label(label); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 13) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 13 && GTK_MICRO_VERSION < 5)) GtkMisc *misc = (GtkMisc*)widget; gfloat yalign; // = 111; gint ypad; // = 111; if (gtk_label_get_line_wrap(label) && (gtk_misc_get_alignment(misc, NULL, &yalign), yalign == 0) && (gtk_misc_get_padding(misc, NULL, &ypad), ypad == 0) #else if (gtk_label_get_line_wrap(label) && (gtk_widget_get_halign(widget) == GTK_ALIGN_START) && (gtk_widget_get_margin_top(widget) == 0) && (gtk_widget_get_margin_bottom(widget) == 0) #endif ) { //log("label '%s' set to autowrap", txt); make_label_autowrap_on_resize(label); return; } //log("label '%s' not set to autowrap %g %d", txt, yalign, ypad); } } static void fix_all_wrapped_labels(GtkWidget *widget) { wrap_fixer(widget, NULL); } static void remove_child_widget(GtkWidget *widget, gpointer unused) { /* Destroy will safely remove it and free the memory * if there are no refs left */ gtk_widget_destroy(widget); } static void update_window_title(void) { /* prgname can be null according to gtk documentation */ const char *prgname = g_get_prgname(); const char *reason = problem_data_get_content_or_NULL(g_cd, FILENAME_REASON); char *title = xasprintf("%s - %s", (reason ? reason : g_dump_dir_name), (prgname ? prgname : "report")); gtk_window_set_title(g_wnd_assistant, title); free(title); } static bool ask_continue_before_steal(const char *base_dir, const char *dump_dir) { char *msg = xasprintf(_("Need writable directory, but '%s' is not writable." " Move it to '%s' and operate on the moved data?"), dump_dir, base_dir); const bool response = run_ask_yes_no_yesforever_dialog("ask_steal_dir", msg, GTK_WINDOW(g_wnd_assistant)); free(msg); return response; } struct dump_dir *wizard_open_directory_for_writing(const char *dump_dir_name) { struct dump_dir *dd = open_directory_for_writing(dump_dir_name, ask_continue_before_steal); if (dd && strcmp(g_dump_dir_name, dd->dd_dirname) != 0) { char *old_name = g_dump_dir_name; g_dump_dir_name = xstrdup(dd->dd_dirname); update_window_title(); free(old_name); } return dd; } void show_error_as_msgbox(const char *msg) { GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE, "%s", msg ); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); } static void load_text_to_text_view(GtkTextView *tv, const char *name) { /* Add to set of loaded files */ /* a key_destroy_func() is provided therefore if the key for name already exists */ /* a result of xstrdup() is freed */ g_hash_table_insert(g_loaded_texts, (gpointer)xstrdup(name), (gpointer)1); const char *str = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : NULL; /* Bad: will choke at any text with non-Unicode parts: */ /* gtk_text_buffer_set_text(tb, (str ? str : ""), -1);*/ /* Start torturing ourself instead: */ reload_text_to_text_view(tv, str); } static gchar *get_malloced_string_from_text_view(GtkTextView *tv) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(tv); GtkTextIter start; GtkTextIter end; gtk_text_buffer_get_start_iter(buffer, &start); gtk_text_buffer_get_end_iter(buffer, &end); return gtk_text_buffer_get_text(buffer, &start, &end, FALSE); } static void save_text_if_changed(const char *name, const char *new_value) { /* a text value can't be change if the file is not loaded */ /* returns NULL if the name is not found; otherwise nonzero */ if (!g_hash_table_lookup(g_loaded_texts, name)) return; const char *old_value = g_cd ? problem_data_get_content_or_NULL(g_cd, name) : ""; if (!old_value) old_value = ""; if (strcmp(new_value, old_value) != 0) { struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); if (dd) dd_save_text(dd, name, new_value); //FIXME: else: what to do with still-unsaved data in the widget?? dd_close(dd); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); } } static void save_text_from_text_view(GtkTextView *tv, const char *name) { gchar *new_str = get_malloced_string_from_text_view(tv); save_text_if_changed(name, new_str); free(new_str); } static void append_to_textview(GtkTextView *tv, const char *str) { GtkTextBuffer *tb = gtk_text_view_get_buffer(tv); /* Ensure we insert text at the end */ GtkTextIter text_iter; gtk_text_buffer_get_end_iter(tb, &text_iter); gtk_text_buffer_place_cursor(tb, &text_iter); /* Deal with possible broken Unicode */ const gchar *end; while (!g_utf8_validate(str, -1, &end)) { gtk_text_buffer_insert_at_cursor(tb, str, end - str); char buf[8]; unsigned len = snprintf(buf, sizeof(buf), "<%02X>", (unsigned char)*end); gtk_text_buffer_insert_at_cursor(tb, buf, len); str = end + 1; } gtk_text_buffer_get_end_iter(tb, &text_iter); const char *last = str; GList *urls = find_url_tokens(str); for (GList *u = urls; u; u = g_list_next(u)) { const struct url_token *const t = (struct url_token *)u->data; if (last < t->start) gtk_text_buffer_insert(tb, &text_iter, last, t->start - last); GtkTextTag *tag; tag = gtk_text_buffer_create_tag (tb, NULL, "foreground", "blue", "underline", PANGO_UNDERLINE_SINGLE, NULL); char *url = xstrndup(t->start, t->len); g_object_set_data (G_OBJECT (tag), "url", url); gtk_text_buffer_insert_with_tags(tb, &text_iter, url, -1, tag, NULL); last = t->start + t->len; } g_list_free_full(urls, g_free); if (last[0] != '\0') gtk_text_buffer_insert(tb, &text_iter, last, strlen(last)); /* Scroll so that the end of the log is visible */ gtk_text_view_scroll_to_iter(tv, &text_iter, /*within_margin:*/ 0.0, /*use_align:*/ FALSE, /*xalign:*/ 0, /*yalign:*/ 0); } /* Looks at all tags covering the position of iter in the text view, * and if one of them is a link, follow it by showing the page identified * by the data attached to it. */ static void open_browse_if_link(GtkWidget *text_view, GtkTextIter *iter) { GSList *tags = NULL, *tagp = NULL; tags = gtk_text_iter_get_tags (iter); for (tagp = tags; tagp != NULL; tagp = tagp->next) { GtkTextTag *tag = tagp->data; const char *url = g_object_get_data (G_OBJECT (tag), "url"); if (url != 0) { /* http://techbase.kde.org/KDE_System_Administration/Environment_Variables#KDE_FULL_SESSION */ if (getenv("KDE_FULL_SESSION") != NULL) { gint exitcode; gchar *arg[3]; /* kde-open is from kdebase-runtime, it should be there. */ arg[0] = (char *) "kde-open"; arg[1] = (char *) url; arg[2] = NULL; const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL, NULL, NULL, NULL, NULL, &exitcode, NULL); if (spawn_ret) break; } GError *error = NULL; if (!gtk_show_uri(/* use default screen */ NULL, url, GDK_CURRENT_TIME, &error)) error_msg("Can't open url '%s': %s", url, error->message); break; } } if (tags) g_slist_free (tags); } /* Links can be activated by pressing Enter. */ static gboolean key_press_event(GtkWidget *text_view, GdkEventKey *event) { GtkTextIter iter; GtkTextBuffer *buffer; switch (event->keyval) { case GDK_KEY_Return: case GDK_KEY_KP_Enter: buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW (text_view)); gtk_text_buffer_get_iter_at_mark(buffer, &iter, gtk_text_buffer_get_insert(buffer)); open_browse_if_link(text_view, &iter); break; default: break; } return FALSE; } /* Links can also be activated by clicking. */ static gboolean event_after(GtkWidget *text_view, GdkEvent *ev) { GtkTextIter start, end, iter; GtkTextBuffer *buffer; GdkEventButton *event; gint x, y; if (ev->type != GDK_BUTTON_RELEASE) return FALSE; event = (GdkEventButton *)ev; if (event->button != GDK_BUTTON_PRIMARY) return FALSE; buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(text_view)); /* we shouldn't follow a link if the user has selected something */ gtk_text_buffer_get_selection_bounds(buffer, &start, &end); if (gtk_text_iter_get_offset(&start) != gtk_text_iter_get_offset(&end)) return FALSE; gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW (text_view), GTK_TEXT_WINDOW_WIDGET, event->x, event->y, &x, &y); gtk_text_view_get_iter_at_location(GTK_TEXT_VIEW (text_view), &iter, x, y); open_browse_if_link(text_view, &iter); return FALSE; } static gboolean hovering_over_link = FALSE; static GdkCursor *hand_cursor = NULL; static GdkCursor *regular_cursor = NULL; /* Looks at all tags covering the position (x, y) in the text view, * and if one of them is a link, change the cursor to the "hands" cursor * typically used by web browsers. */ static void set_cursor_if_appropriate(GtkTextView *text_view, gint x, gint y) { GSList *tags = NULL, *tagp = NULL; GtkTextIter iter; gboolean hovering = FALSE; gtk_text_view_get_iter_at_location(text_view, &iter, x, y); tags = gtk_text_iter_get_tags(&iter); for (tagp = tags; tagp != NULL; tagp = tagp->next) { GtkTextTag *tag = tagp->data; gpointer url = g_object_get_data(G_OBJECT (tag), "url"); if (url != 0) { hovering = TRUE; break; } } if (hovering != hovering_over_link) { hovering_over_link = hovering; if (hovering_over_link) gdk_window_set_cursor(gtk_text_view_get_window(text_view, GTK_TEXT_WINDOW_TEXT), hand_cursor); else gdk_window_set_cursor(gtk_text_view_get_window(text_view, GTK_TEXT_WINDOW_TEXT), regular_cursor); } if (tags) g_slist_free (tags); } /* Update the cursor image if the pointer moved. */ static gboolean motion_notify_event(GtkWidget *text_view, GdkEventMotion *event) { gint x, y; gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(text_view), GTK_TEXT_WINDOW_WIDGET, event->x, event->y, &x, &y); set_cursor_if_appropriate(GTK_TEXT_VIEW(text_view), x, y); return FALSE; } /* Also update the cursor image if the window becomes visible * (e.g. when a window covering it got iconified). */ static gboolean visibility_notify_event(GtkWidget *text_view, GdkEventVisibility *event) { gint wx, wy, bx, by; GdkWindow *win = gtk_text_view_get_window(GTK_TEXT_VIEW(text_view), GTK_TEXT_WINDOW_TEXT); GdkDeviceManager *device_manager = gdk_display_get_device_manager(gdk_window_get_display (win)); GdkDevice *pointer = gdk_device_manager_get_client_pointer(device_manager); gdk_window_get_device_position(gtk_widget_get_window(text_view), pointer, &wx, &wy, NULL); gtk_text_view_window_to_buffer_coords(GTK_TEXT_VIEW(text_view), GTK_TEXT_WINDOW_WIDGET, wx, wy, &bx, &by); set_cursor_if_appropriate(GTK_TEXT_VIEW (text_view), bx, by); return FALSE; } /* event_gui_data_t */ static event_gui_data_t *new_event_gui_data_t(void) { return xzalloc(sizeof(event_gui_data_t)); } static void free_event_gui_data_t(event_gui_data_t *evdata, void *unused) { if (evdata) { free(evdata->event_name); free(evdata); } } /* tv_details handling */ static struct problem_item *get_current_problem_item_or_NULL(GtkTreeView *tree_view, gchar **pp_item_name) { GtkTreeModel *model; GtkTreeIter iter; GtkTreeSelection* selection = gtk_tree_view_get_selection(tree_view); if (selection == NULL) return NULL; if (!gtk_tree_selection_get_selected(selection, &model, &iter)) return NULL; *pp_item_name = NULL; gtk_tree_model_get(model, &iter, DETAIL_COLUMN_NAME, pp_item_name, -1); if (!*pp_item_name) /* paranoia, should never happen */ return NULL; struct problem_item *item = problem_data_get_item_or_NULL(g_cd, *pp_item_name); return item; } static void tv_details_row_activated( GtkTreeView *tree_view, GtkTreePath *tree_path_UNUSED, GtkTreeViewColumn *column, gpointer user_data) { gchar *item_name; struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name); if (!item || !(item->flags & CD_FLAG_TXT)) goto ret; if (!strchr(item->content, '\n')) /* one line? */ goto ret; /* yes */ gint exitcode; gchar *arg[3]; arg[0] = (char *) "xdg-open"; arg[1] = concat_path_file(g_dump_dir_name, item_name); arg[2] = NULL; const gboolean spawn_ret = g_spawn_sync(NULL, arg, NULL, G_SPAWN_SEARCH_PATH | G_SPAWN_STDOUT_TO_DEV_NULL, NULL, NULL, NULL, NULL, &exitcode, NULL); if (spawn_ret == FALSE || exitcode != EXIT_SUCCESS) { GtkWidget *dialog = gtk_dialog_new_with_buttons(_("View/edit a text file"), GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, NULL, NULL); GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); GtkWidget *scrolled = gtk_scrolled_window_new(NULL, NULL); GtkWidget *textview = gtk_text_view_new(); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Save"), GTK_RESPONSE_OK); gtk_dialog_add_button(GTK_DIALOG(dialog), _("_Cancel"), GTK_RESPONSE_CANCEL); gtk_box_pack_start(GTK_BOX(vbox), scrolled, TRUE, TRUE, 0); gtk_widget_set_size_request(scrolled, 640, 480); gtk_widget_show(scrolled); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 7) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 7 && GTK_MICRO_VERSION < 8)) /* http://developer.gnome.org/gtk3/unstable/GtkScrolledWindow.html#gtk-scrolled-window-add-with-viewport */ /* gtk_scrolled_window_add_with_viewport has been deprecated since version 3.8 and should not be used in newly-written code. */ gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled), textview); #else /* gtk_container_add() will now automatically add a GtkViewport if the child doesn't implement GtkScrollable. */ gtk_container_add(GTK_CONTAINER(scrolled), textview); #endif gtk_widget_show(textview); load_text_to_text_view(GTK_TEXT_VIEW(textview), item_name); if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) save_text_from_text_view(GTK_TEXT_VIEW(textview), item_name); gtk_widget_destroy(textview); gtk_widget_destroy(scrolled); gtk_widget_destroy(dialog); } free(arg[1]); ret: g_free(item_name); } /* static gboolean tv_details_select_cursor_row( GtkTreeView *tree_view, gboolean arg1, gpointer user_data) {...} */ static void tv_details_cursor_changed( GtkTreeView *tree_view, gpointer user_data_UNUSED) { /* I see this being called on window "destroy" signal when the tree_view is not a tree view anymore (or destroyed?) causing this error msg: (abrt:12804): Gtk-CRITICAL **: gtk_tree_selection_get_selected: assertion `GTK_IS_TREE_SELECTION (selection)' failed (abrt:12804): GLib-GObject-WARNING **: invalid uninstantiatable type `(null)' in cast to `GObject' (abrt:12804): GLib-GObject-CRITICAL **: g_object_set: assertion `G_IS_OBJECT (object)' failed */ if (!GTK_IS_TREE_VIEW(tree_view)) return; gchar *item_name = NULL; struct problem_item *item = get_current_problem_item_or_NULL(tree_view, &item_name); g_free(item_name); /* happens when closing the wizard by clicking 'X' */ if (!item) return; gboolean editable = (item /* With this, copying of non-editable fields are more difficult */ //&& (item->flags & CD_FLAG_ISEDITABLE) && (item->flags & CD_FLAG_TXT) && !strchr(item->content, '\n') ); /* Allow user to select the text with mouse. * Has undesirable side-effect of allowing user to "edit" the text, * but changes aren't saved (the old text reappears as soon as user * leaves the field). Need to disable editing somehow. */ g_object_set(G_OBJECT(g_tv_details_renderer_value), "editable", editable, NULL); } static void g_tv_details_checkbox_toggled( GtkCellRendererToggle *cell_renderer_UNUSED, gchar *tree_path, gpointer user_data_UNUSED) { //log("%s: path:'%s'", __func__, tree_path); GtkTreeIter iter; if (!gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(g_ls_details), &iter, tree_path)) return; gchar *item_name = NULL; gtk_tree_model_get(GTK_TREE_MODEL(g_ls_details), &iter, DETAIL_COLUMN_NAME, &item_name, -1); if (!item_name) /* paranoia, should never happen */ return; struct problem_item *item = problem_data_get_item_or_NULL(g_cd, item_name); g_free(item_name); if (!item) /* paranoia */ return; int cur_value; if (item->selected_by_user == 0) cur_value = item->default_by_reporter; else cur_value = !!(item->selected_by_user + 1); /* map -1,1 to 0,1 */ //log("%s: allowed:%d reqd:%d def:%d user:%d cur:%d", __func__, // item->allowed_by_reporter, // item->required_by_reporter, // item->default_by_reporter, // item->selected_by_user, // cur_value //); if (item->allowed_by_reporter && !item->required_by_reporter) { cur_value = !cur_value; item->selected_by_user = cur_value * 2 - 1; /* map 0,1 to -1,1 */ //log("%s: now ->selected_by_user=%d", __func__, item->selected_by_user); gtk_list_store_set(g_ls_details, &iter, DETAIL_COLUMN_CHECKBOX, cur_value, -1); } } /* update_gui_state_from_problem_data */ static gint find_by_button(gconstpointer a, gconstpointer button) { const event_gui_data_t *evdata = a; return (evdata->toggle_button != button); } static void check_event_config(const char *event_name) { GHashTable *errors = validate_event(event_name); if (errors != NULL) { g_hash_table_unref(errors); show_event_config_dialog(event_name, GTK_WINDOW(g_top_most_window)); } } static void event_rb_was_toggled(GtkButton *button, gpointer user_data) { /* Note: called both when item is selected and _unselected_, * use gtk_toggle_button_get_active() to determine state. */ GList *found = g_list_find_custom(g_list_events, button, find_by_button); if (found) { event_gui_data_t *evdata = found->data; if (gtk_toggle_button_get_active(evdata->toggle_button)) { free(g_event_selected); g_event_selected = xstrdup(evdata->event_name); check_event_config(evdata->event_name); clear_warnings(); const bool good_rating = check_minimal_bt_rating(g_event_selected); show_warnings(); gtk_widget_set_sensitive(g_btn_next, good_rating); } } } /* event_name contains "EVENT1\nEVENT2\nEVENT3\n". * Add new radio buttons to GtkBox for each EVENTn. * Remember them in GList **p_event_list (list of event_gui_data_t's). * Set "toggled" callback on each button to given GCallback if it's not NULL. * Return active button (or NULL if none created). */ /* helper */ static char *missing_items_in_comma_list(const char *input_item_list) { if (!input_item_list) return NULL; char *item_list = xstrdup(input_item_list); char *result = item_list; char *dst = item_list; while (item_list[0]) { char *end = strchr(item_list, ','); if (end) *end = '\0'; if (!problem_data_get_item_or_NULL(g_cd, item_list)) { if (dst != result) *dst++ = ','; dst = stpcpy(dst, item_list); } if (!end) break; *end = ','; item_list = end + 1; } if (result == dst) { free(result); result = NULL; } return result; } static event_gui_data_t *add_event_buttons(GtkBox *box, GList **p_event_list, char *event_name, GCallback func) { //log_info("removing all buttons from box %p", box); gtk_container_foreach(GTK_CONTAINER(box), &remove_child_widget, NULL); g_list_foreach(*p_event_list, (GFunc)free_event_gui_data_t, NULL); g_list_free(*p_event_list); *p_event_list = NULL; g_black_event_count = 0; if (!event_name || !event_name[0]) { GtkWidget *lbl = gtk_label_new(_("No reporting targets are defined for this problem. Check configuration in /etc/libreport/*")); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 13) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 13 && GTK_MICRO_VERSION < 5)) gtk_misc_set_alignment(GTK_MISC(lbl), /*x*/ 0.0, /*y*/ 0.0); #else gtk_widget_set_halign (lbl, GTK_ALIGN_START); gtk_widget_set_valign (lbl, GTK_ALIGN_END); #endif make_label_autowrap_on_resize(GTK_LABEL(lbl)); gtk_box_pack_start(box, lbl, /*expand*/ true, /*fill*/ false, /*padding*/ 0); return NULL; } event_gui_data_t *first_button = NULL; event_gui_data_t *active_button = NULL; while (1) { if (!event_name || !event_name[0]) break; char *event_name_end = strchr(event_name, '\n'); *event_name_end = '\0'; event_config_t *cfg = get_event_config(event_name); /* Form a pretty text representation of event */ /* By default, use event name: */ const char *event_screen_name = event_name; const char *event_description = NULL; char *tmp_description = NULL; bool red_choice = false; bool green_choice = false; if (cfg) { /* .xml has (presumably) prettier description, use it: */ if (ec_get_screen_name(cfg)) event_screen_name = ec_get_screen_name(cfg); event_description = ec_get_description(cfg); char *missing = missing_items_in_comma_list(cfg->ec_requires_items); if (missing) { red_choice = true; event_description = tmp_description = xasprintf(_("(requires: %s)"), missing); free(missing); } else if (cfg->ec_creates_items) { if (problem_data_get_item_or_NULL(g_cd, cfg->ec_creates_items)) { char *missing = missing_items_in_comma_list(cfg->ec_creates_items); if (missing) free(missing); else { green_choice = true; event_description = tmp_description = xasprintf(_("(not needed, data already exist: %s)"), cfg->ec_creates_items); } } } } if (!green_choice && !red_choice) g_black_event_count++; //log_info("adding button '%s' to box %p", event_name, box); char *event_label = xasprintf("%s%s%s", event_screen_name, (event_description ? " - " : ""), event_description ? event_description : "" ); free(tmp_description); GtkWidget *button = gtk_radio_button_new_with_label_from_widget( (first_button ? GTK_RADIO_BUTTON(first_button->toggle_button) : NULL), event_label ); free(event_label); if (green_choice || red_choice) { GtkWidget *child = gtk_bin_get_child(GTK_BIN(button)); if (child) { static const GdkRGBA red = { .red = 1.0, .green = 0.0, .blue = 0.0, .alpha = 1.0, }; static const GdkRGBA green = { .red = 0.0, .green = 0.5, .blue = 0.0, .alpha = 1.0, }; const GdkRGBA *color = (green_choice ? &green : &red); //gtk_widget_modify_text(button, GTK_STATE_NORMAL, color); gtk_widget_override_color(child, GTK_STATE_FLAG_NORMAL, color); } } if (func) g_signal_connect(G_OBJECT(button), "toggled", func, xstrdup(event_name)); if (cfg && ec_get_long_desc(cfg)) gtk_widget_set_tooltip_text(button, ec_get_long_desc(cfg)); event_gui_data_t *event_gui_data = new_event_gui_data_t(); event_gui_data->event_name = xstrdup(event_name); event_gui_data->toggle_button = GTK_TOGGLE_BUTTON(button); *p_event_list = g_list_append(*p_event_list, event_gui_data); if (!first_button) first_button = event_gui_data; if (!green_choice && !red_choice && !active_button) { gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(button), true); active_button = event_gui_data; } *event_name_end = '\n'; event_name = event_name_end + 1; gtk_box_pack_start(box, button, /*expand*/ false, /*fill*/ false, /*padding*/ 0); gtk_widget_show_all(GTK_WIDGET(button)); wrap_all_labels(button); /* Disabled - seems that above is enough... */ /*fix_all_wrapped_labels(button);*/ } gtk_widget_show_all(GTK_WIDGET(box)); return active_button; } struct cd_stats { off_t filesize; unsigned filecount; }; static void save_items_from_notepad(void) { gint n_pages = gtk_notebook_get_n_pages(g_notebook); int i = 0; GtkWidget *notebook_child; GtkTextView *tev; GtkWidget *tab_lbl; const char *item_name; for (i = 0; i < n_pages; i++) { //notebook_page->scrolled_window->text_view notebook_child = gtk_notebook_get_nth_page(g_notebook, i); tev = GTK_TEXT_VIEW(gtk_bin_get_child(GTK_BIN(notebook_child))); tab_lbl = gtk_notebook_get_tab_label(g_notebook, notebook_child); item_name = gtk_label_get_text(GTK_LABEL(tab_lbl)); log_notice("saving: '%s'", item_name); save_text_from_text_view(tev, item_name); } } static void remove_tabs_from_notebook(GtkNotebook *notebook) { gint n_pages = gtk_notebook_get_n_pages(notebook); int ii; for (ii = 0; ii < n_pages; ii++) { /* removing a page changes the indices, so we always need to remove * page 0 */ gtk_notebook_remove_page(notebook, 0); //we need to always the page 0 } /* Turn off the changed callback during the update */ g_signal_handler_block(g_tv_sensitive_sel, g_tv_sensitive_sel_hndlr); g_current_highlighted_word = NULL; GtkTreeIter iter; gboolean valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_ls_sensitive_list), &iter); while (valid) { char *text = NULL; search_item_t *word = NULL; gtk_tree_model_get(GTK_TREE_MODEL(g_ls_sensitive_list), &iter, SEARCH_COLUMN_TEXT, &text, SEARCH_COLUMN_ITEM, &word, -1); free(text); free(word); valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(g_ls_sensitive_list), &iter); } gtk_list_store_clear(g_ls_sensitive_list); g_signal_handler_unblock(g_tv_sensitive_sel, g_tv_sensitive_sel_hndlr); } static void append_item_to_ls_details(gpointer name, gpointer value, gpointer data) { problem_item *item = (problem_item*)value; struct cd_stats *stats = data; GtkTreeIter iter; gtk_list_store_append(g_ls_details, &iter); stats->filecount++; //FIXME: use the human-readable problem_item_format(item) instead of item->content. if (item->flags & CD_FLAG_TXT) { if (item->flags & CD_FLAG_ISEDITABLE && strcmp(name, FILENAME_ANACONDA_TB) != 0) { GtkWidget *tab_lbl = gtk_label_new((char *)name); GtkWidget *tev = gtk_text_view_new(); if (strcmp(name, FILENAME_COMMENT) == 0 || strcmp(name, FILENAME_REASON) == 0) gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(tev), GTK_WRAP_WORD); gtk_widget_override_font(GTK_WIDGET(tev), g_monospace_font); load_text_to_text_view(GTK_TEXT_VIEW(tev), (char *)name); /* init searching */ GtkTextBuffer *buf = gtk_text_view_get_buffer(GTK_TEXT_VIEW(tev)); /* found items background */ gtk_text_buffer_create_tag(buf, "search_result_bg", "background", "red", NULL); gtk_text_buffer_create_tag(buf, "current_result_bg", "background", "green", NULL); GtkWidget *sw = gtk_scrolled_window_new(NULL, NULL); gtk_container_add(GTK_CONTAINER(sw), tev); gtk_notebook_append_page(g_notebook, sw, tab_lbl); } stats->filesize += strlen(item->content); /* If not multiline... */ if (!strchr(item->content, '\n')) { gtk_list_store_set(g_ls_details, &iter, DETAIL_COLUMN_NAME, (char *)name, DETAIL_COLUMN_VALUE, item->content, -1); } else { gtk_list_store_set(g_ls_details, &iter, DETAIL_COLUMN_NAME, (char *)name, DETAIL_COLUMN_VALUE, _("(click here to view/edit)"), -1); } } else if (item->flags & CD_FLAG_BIN) { struct stat statbuf; statbuf.st_size = 0; if (stat(item->content, &statbuf) == 0) { stats->filesize += statbuf.st_size; char *msg = xasprintf(_("(binary file, %llu bytes)"), (long long)statbuf.st_size); gtk_list_store_set(g_ls_details, &iter, DETAIL_COLUMN_NAME, (char *)name, DETAIL_COLUMN_VALUE, msg, -1); free(msg); } } int cur_value; if (item->selected_by_user == 0) cur_value = item->default_by_reporter; else cur_value = !!(item->selected_by_user + 1); /* map -1,1 to 0,1 */ gtk_list_store_set(g_ls_details, &iter, DETAIL_COLUMN_CHECKBOX, cur_value, -1); } /* Based on selected reporter, update item checkboxes */ static void update_ls_details_checkboxes(const char *event_name) { event_config_t *cfg = get_event_config(event_name); //log("%s: event:'%s', cfg:'%p'", __func__, g_event_selected, cfg); GHashTableIter iter; char *name; struct problem_item *item; g_hash_table_iter_init(&iter, g_cd); string_vector_ptr_t global_exclude = get_global_always_excluded_elements(); while (g_hash_table_iter_next(&iter, (void**)&name, (void**)&item)) { /* Decide whether item is allowed, required, and what's the default */ item->allowed_by_reporter = 1; if (global_exclude) item->allowed_by_reporter = !is_in_string_list(name, (const_string_vector_const_ptr_t)global_exclude); if (cfg) { if (is_in_comma_separated_list_of_glob_patterns(name, cfg->ec_exclude_items_always)) item->allowed_by_reporter = 0; if ((item->flags & CD_FLAG_BIN) && cfg->ec_exclude_binary_items) item->allowed_by_reporter = 0; } item->default_by_reporter = item->allowed_by_reporter; if (cfg) { if (is_in_comma_separated_list_of_glob_patterns(name, cfg->ec_exclude_items_by_default)) item->default_by_reporter = 0; if (is_in_comma_separated_list_of_glob_patterns(name, cfg->ec_include_items_by_default)) item->allowed_by_reporter = item->default_by_reporter = 1; } item->required_by_reporter = 0; if (cfg) { if (is_in_comma_separated_list_of_glob_patterns(name, cfg->ec_requires_items)) item->default_by_reporter = item->allowed_by_reporter = item->required_by_reporter = 1; } int cur_value; if (item->selected_by_user == 0) cur_value = item->default_by_reporter; else cur_value = !!(item->selected_by_user + 1); /* map -1,1 to 0,1 */ //log("%s: '%s' allowed:%d reqd:%d def:%d user:%d", __func__, name, // item->allowed_by_reporter, // item->required_by_reporter, // item->default_by_reporter, // item->selected_by_user //); /* Find corresponding line and update checkbox */ GtkTreeIter iter; if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_ls_details), &iter)) { do { gchar *item_name = NULL; gtk_tree_model_get(GTK_TREE_MODEL(g_ls_details), &iter, DETAIL_COLUMN_NAME, &item_name, -1); if (!item_name) /* paranoia, should never happen */ continue; int differ = strcmp(name, item_name); g_free(item_name); if (differ) continue; gtk_list_store_set(g_ls_details, &iter, DETAIL_COLUMN_CHECKBOX, cur_value, -1); //log("%s: changed gtk_list_store_set to %d", __func__, (item->allowed_by_reporter && item->selected_by_user >= 0)); break; } while (gtk_tree_model_iter_next(GTK_TREE_MODEL(g_ls_details), &iter)); } } } void update_gui_state_from_problem_data(int flags) { update_window_title(); remove_tabs_from_notebook(g_notebook); const char *reason = problem_data_get_content_or_NULL(g_cd, FILENAME_REASON); const char *not_reportable = problem_data_get_content_or_NULL(g_cd, FILENAME_NOT_REPORTABLE); char *t = xasprintf("%s%s%s", not_reportable ? : "", not_reportable ? " " : "", reason ? : _("(no description)")); gtk_label_set_text(g_lbl_cd_reason, t); free(t); gtk_list_store_clear(g_ls_details); struct cd_stats stats = { 0 }; g_hash_table_foreach(g_cd, append_item_to_ls_details, &stats); char *msg = xasprintf(_("%llu bytes, %u files"), (long long)stats.filesize, stats.filecount); gtk_label_set_text(g_lbl_size, msg); free(msg); load_text_to_text_view(g_tv_comment, FILENAME_COMMENT); add_workflow_buttons(g_box_workflows, g_workflow_list, G_CALLBACK(set_auto_event_chain)); /* Update event radio buttons * show them only in expert mode */ event_gui_data_t *active_button = NULL; if (g_expert_mode == true) { //this widget doesn't react to show_all, so we need to "force" it gtk_widget_show(GTK_WIDGET(g_box_events)); active_button = add_event_buttons( g_box_events, &g_list_events, g_events, G_CALLBACK(event_rb_was_toggled) ); } if (flags & UPDATE_SELECTED_EVENT && g_expert_mode) { /* Update the value of currently selected event */ free(g_event_selected); g_event_selected = NULL; if (active_button) { g_event_selected = xstrdup(active_button->event_name); } log_info("g_event_selected='%s'", g_event_selected); } /* We can't just do gtk_widget_show_all once in main: * We created new widgets (buttons). Need to make them visible. */ gtk_widget_show_all(GTK_WIDGET(g_wnd_assistant)); } /* start_event_run */ struct analyze_event_data { struct run_event_state *run_state; char *event_name; GList *env_list; GIOChannel *channel; struct strbuf *event_log; int event_log_state; int fd; /*guint event_source_id;*/ }; enum { LOGSTATE_FIRSTLINE = 0, LOGSTATE_BEGLINE, LOGSTATE_ERRLINE, LOGSTATE_MIDLINE, }; static void set_excluded_envvar(void) { struct strbuf *item_list = strbuf_new(); const char *fmt = "%s"; GtkTreeIter iter; if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_ls_details), &iter)) { do { gchar *item_name = NULL; gboolean checked = 0; gtk_tree_model_get(GTK_TREE_MODEL(g_ls_details), &iter, DETAIL_COLUMN_NAME, &item_name, DETAIL_COLUMN_CHECKBOX, &checked, -1); if (!item_name) /* paranoia, should never happen */ continue; if (!checked) { strbuf_append_strf(item_list, fmt, item_name); fmt = ",%s"; } g_free(item_name); } while (gtk_tree_model_iter_next(GTK_TREE_MODEL(g_ls_details), &iter)); } char *var = strbuf_free_nobuf(item_list); //log("EXCLUDE_FROM_REPORT='%s'", var); if (var) { xsetenv("EXCLUDE_FROM_REPORT", var); free(var); } else unsetenv("EXCLUDE_FROM_REPORT"); } static int spawn_next_command_in_evd(struct analyze_event_data *evd) { evd->env_list = export_event_config(evd->event_name); int r = spawn_next_command(evd->run_state, g_dump_dir_name, evd->event_name, EXECFLG_SETPGID); if (r >= 0) { g_event_child_pid = evd->run_state->command_pid; } else { unexport_event_config(evd->env_list); evd->env_list = NULL; } return r; } static void save_to_event_log(struct analyze_event_data *evd, const char *str) { static const char delim[] = { [LOGSTATE_FIRSTLINE] = '>', [LOGSTATE_BEGLINE] = ' ', [LOGSTATE_ERRLINE] = '*', }; while (str[0]) { char *end = strchrnul(str, '\n'); char end_char = *end; if (end_char == '\n') end++; switch (evd->event_log_state) { case LOGSTATE_FIRSTLINE: case LOGSTATE_BEGLINE: case LOGSTATE_ERRLINE: /* skip empty lines */ if (str[0] == '\n') goto next; strbuf_append_strf(evd->event_log, "%s%c %.*s", iso_date_string(NULL), delim[evd->event_log_state], (int)(end - str), str ); break; case LOGSTATE_MIDLINE: strbuf_append_strf(evd->event_log, "%.*s", (int)(end - str), str); break; } evd->event_log_state = LOGSTATE_MIDLINE; if (end_char != '\n') break; evd->event_log_state = LOGSTATE_BEGLINE; next: str = end; } } static void update_event_log_on_disk(const char *str) { /* Load existing log */ struct dump_dir *dd = dd_opendir(g_dump_dir_name, 0); if (!dd) return; char *event_log = dd_load_text_ext(dd, FILENAME_EVENT_LOG, DD_FAIL_QUIETLY_ENOENT); /* Append new log part to existing log */ unsigned len = strlen(event_log); if (len != 0 && event_log[len - 1] != '\n') event_log = append_to_malloced_string(event_log, "\n"); event_log = append_to_malloced_string(event_log, str); /* Trim log according to size watermarks */ len = strlen(event_log); char *new_log = event_log; if (len > EVENT_LOG_HIGH_WATERMARK) { new_log += len - EVENT_LOG_LOW_WATERMARK; new_log = strchrnul(new_log, '\n'); if (new_log[0]) new_log++; } /* Save */ dd_save_text(dd, FILENAME_EVENT_LOG, new_log); free(event_log); dd_close(dd); } static bool cancel_event_run() { if (g_event_child_pid <= 0) return false; kill(- g_event_child_pid, SIGTERM); return true; } static void on_btn_cancel_event(GtkButton *button) { cancel_event_run(); } static bool is_processing_finished() { return !g_expert_mode && !g_auto_event_list; } static void hide_next_step_button() { /* replace 'Forward' with 'Close' button */ /* 1. hide next button */ gtk_widget_hide(g_btn_next); /* 2. move close button to the last position */ gtk_box_set_child_packing(g_box_buttons, g_btn_close, false, false, 5, GTK_PACK_END); } static void show_next_step_button() { gtk_box_set_child_packing(g_box_buttons, g_btn_close, false, false, 5, GTK_PACK_START); gtk_widget_show(g_btn_next); } enum { TERMINATE_NOFLAGS = 0, TERMINATE_WITH_RERUN = 1 << 0, }; static void terminate_event_chain(int flags) { if (g_expert_mode) return; hide_next_step_button(); if ((flags & TERMINATE_WITH_RERUN)) return; free(g_event_selected); g_event_selected = NULL; g_list_free_full(g_auto_event_list, free); g_auto_event_list = NULL; } static void cancel_processing(GtkLabel *status_label, const char *message, int terminate_flags) { gtk_label_set_text(status_label, message ? message : _("Processing was canceled")); terminate_event_chain(terminate_flags); } static void update_command_run_log(const char* message, struct analyze_event_data *evd) { const bool it_is_a_dot = (message[0] == '.' && message[1] == '\0'); if (!it_is_a_dot) gtk_label_set_text(g_lbl_event_log, message); /* Don't append new line behind single dot */ const char *log_msg = it_is_a_dot ? message : xasprintf("%s\n", message); append_to_textview(g_tv_event_log, log_msg); save_to_event_log(evd, log_msg); /* Because of single dot, see lines above */ if (log_msg != message) free((void *)log_msg); } static void run_event_gtk_error(const char *error_line, void *param) { update_command_run_log(error_line, (struct analyze_event_data *)param); } static char *run_event_gtk_logging(char *log_line, void *param) { struct analyze_event_data *evd = (struct analyze_event_data *)param; update_command_run_log(log_line, evd); return log_line; } static void log_request_response_communication(const char *request, const char *response, struct analyze_event_data *evd) { char *message = xasprintf(response ? "%s '%s'" : "%s", request, response); update_command_run_log(message, evd); free(message); } static void run_event_gtk_alert(const char *msg, void *args) { GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE, "%s", msg); char *tagged_msg = tag_url(msg, "\n"); gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog), tagged_msg); free(tagged_msg); gtk_dialog_run(GTK_DIALOG(dialog)); gtk_widget_destroy(dialog); log_request_response_communication(msg, NULL, (struct analyze_event_data *)args); } static void gtk_entry_emit_dialog_response_ok(GtkEntry *entry, GtkDialog *dialog) { /* Don't close the dialogue if the entry is empty */ if (gtk_entry_get_text_length(entry) > 0) gtk_dialog_response(dialog, GTK_RESPONSE_OK); } static char *ask_helper(const char *msg, void *args, bool password) { GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_OK_CANCEL, "%s", msg); char *tagged_msg = tag_url(msg, "\n"); gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_OK); gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog), tagged_msg); free(tagged_msg); GtkWidget *vbox = gtk_dialog_get_content_area(GTK_DIALOG(dialog)); GtkWidget *textbox = gtk_entry_new(); /* gtk_entry_set_editable(GTK_ENTRY(textbox), TRUE); * is not available in gtk3, so please use the highlevel * g_object_set */ g_object_set(G_OBJECT(textbox), "editable", TRUE, NULL); g_signal_connect(textbox, "activate", G_CALLBACK(gtk_entry_emit_dialog_response_ok), dialog); if (password) gtk_entry_set_visibility(GTK_ENTRY(textbox), FALSE); gtk_box_pack_start(GTK_BOX(vbox), textbox, TRUE, TRUE, 0); gtk_widget_show(textbox); char *response = NULL; if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_OK) { const char *text = gtk_entry_get_text(GTK_ENTRY(textbox)); response = xstrdup(text); } gtk_widget_destroy(textbox); gtk_widget_destroy(dialog); const char *log_response = ""; if (response) log_response = password ? "********" : response; log_request_response_communication(msg, log_response, (struct analyze_event_data *)args); return response ? response : xstrdup(""); } static char *run_event_gtk_ask(const char *msg, void *args) { return ask_helper(msg, args, false); } static int run_event_gtk_ask_yes_no(const char *msg, void *args) { GtkWidget *dialog = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, "%s", msg); char *tagged_msg = tag_url(msg, "\n"); gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(dialog), tagged_msg); free(tagged_msg); /* Esc -> No, Enter -> Yes */ gtk_dialog_set_default_response(GTK_DIALOG(dialog), GTK_RESPONSE_YES); const int ret = gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_YES; gtk_widget_destroy(dialog); log_request_response_communication(msg, ret ? "YES" : "NO", (struct analyze_event_data *)args); return ret; } static int run_event_gtk_ask_yes_no_yesforever(const char *key, const char *msg, void *args) { const int ret = run_ask_yes_no_yesforever_dialog(key, msg, GTK_WINDOW(g_wnd_assistant)); log_request_response_communication(msg, ret ? "YES" : "NO", (struct analyze_event_data *)args); return ret; } static int run_event_gtk_ask_yes_no_save_result(const char *key, const char *msg, void *args) { const int ret = run_ask_yes_no_save_result_dialog(key, msg, GTK_WINDOW(g_wnd_assistant)); log_request_response_communication(msg, ret ? "YES" : "NO", (struct analyze_event_data *)args); return ret; } static char *run_event_gtk_ask_password(const char *msg, void *args) { return ask_helper(msg, args, true); } static bool event_need_review(const char *event_name) { event_config_t *event_cfg = get_event_config(event_name); return !event_cfg || !event_cfg->ec_skip_review; } static void on_btn_failed_cb(GtkButton *button) { /* Since the Repeat button has been introduced, the event chain isn't * terminated upon a failure in order to be able to continue in processing * in the retry action. * * Now, user decided to run the emergency analysis instead of trying to * reconfigure libreport, so we have to terminate the event chain. */ gtk_widget_hide(g_btn_repeat); terminate_event_chain(TERMINATE_NOFLAGS); /* Show detailed log */ gtk_expander_set_expanded(g_exp_report_log, TRUE); clear_warnings(); update_ls_details_checkboxes(EMERGENCY_ANALYSIS_EVENT_NAME); start_event_run(EMERGENCY_ANALYSIS_EVENT_NAME); /* single shot button -> hide after click */ gtk_widget_hide(GTK_WIDGET(button)); } static gint select_next_page_no(gint current_page_no, gpointer data); static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data); static void on_btn_repeat_cb(GtkButton *button) { g_auto_event_list = g_list_prepend(g_auto_event_list, g_event_selected); g_event_selected = NULL; show_next_step_button(); clear_warnings(); const gint current_page_no = gtk_notebook_get_current_page(g_assistant); const int next_page_no = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL); if (current_page_no == next_page_no) on_page_prepare(g_assistant, gtk_notebook_get_nth_page(g_assistant, next_page_no), NULL); else gtk_notebook_set_current_page(g_assistant, next_page_no); } static void on_failed_event(const char *event_name) { /* Don't show the 'on failure' button if the processed event * was started by that button. (avoid infinite loop) */ if (strcmp(event_name, EMERGENCY_ANALYSIS_EVENT_NAME) == 0) return; add_warning( _("Processing of the problem failed. This can have many reasons but there are three most common:\n"\ "\t▫ <b>network connection problems</b>\n"\ "\t▫ <b>corrupted problem data</b>\n"\ "\t▫ <b>invalid configuration</b>" )); if (!g_expert_mode) { add_warning( _("If you want to update the configuration and try to report again, please open <b>Preferences</b> item\n" "in the application menu and after applying the configuration changes click <b>Repeat</b> button.")); gtk_widget_show(g_btn_repeat); } add_warning( _("If you are sure that this problem is not caused by network problems neither by invalid configuration\n" "and want to help us, please click on the upload button and provide all problem data for a deep analysis.\n"\ "<i>Before you do that, please consider the security risks. Problem data may contain sensitive information like\n"\ "passwords. The uploaded data are stored in a protected storage and only a limited number of persons can read them.</i>")); show_warnings(); gtk_widget_show(g_btn_onfail); } static gboolean consume_cmd_output(GIOChannel *source, GIOCondition condition, gpointer data) { struct analyze_event_data *evd = data; struct run_event_state *run_state = evd->run_state; bool stop_requested = false; int retval = consume_event_command_output(run_state, g_dump_dir_name); if (retval < 0 && errno == EAGAIN) /* We got all buffered data, but fd is still open. Done for now */ return TRUE; /* "please don't remove this event (yet)" */ /* EOF/error */ if (WIFEXITED(run_state->process_status) && WEXITSTATUS(run_state->process_status) == EXIT_STOP_EVENT_RUN ) { retval = 0; run_state->process_status = 0; stop_requested = true; terminate_event_chain(TERMINATE_NOFLAGS); } unexport_event_config(evd->env_list); evd->env_list = NULL; /* Make sure "Cancel" button won't send anything (process is gone) */ g_event_child_pid = -1; evd->run_state->command_pid = -1; /* just for consistency */ /* Write a final message to the log */ if (evd->event_log->len != 0 && evd->event_log->buf[evd->event_log->len - 1] != '\n') save_to_event_log(evd, "\n"); /* If program failed, or if it finished successfully without saying anything... */ if (retval != 0 || evd->event_log_state == LOGSTATE_FIRSTLINE) { char *msg = exit_status_as_string(evd->event_name, run_state->process_status); if (retval != 0) { /* If program failed, emit *error* line */ evd->event_log_state = LOGSTATE_ERRLINE; } append_to_textview(g_tv_event_log, msg); save_to_event_log(evd, msg); free(msg); } /* Append log to FILENAME_EVENT_LOG */ update_event_log_on_disk(evd->event_log->buf); strbuf_clear(evd->event_log); evd->event_log_state = LOGSTATE_FIRSTLINE; struct dump_dir *dd = NULL; if (geteuid() == 0) { /* Reset mode/uig/gid to correct values for all files created by event run */ dd = dd_opendir(g_dump_dir_name, 0); if (dd) dd_sanitize_mode_and_owner(dd); } if (retval == 0 && !g_expert_mode) { /* Check whether NOT_REPORTABLE element appeared. If it did, we'll stop * even if exit code is "success". */ if (!dd) /* why? because dd may be already open by the code above */ dd = dd_opendir(g_dump_dir_name, DD_OPEN_READONLY | DD_FAIL_QUIETLY_EACCES); if (!dd) xfunc_die(); char *not_reportable = dd_load_text_ext(dd, FILENAME_NOT_REPORTABLE, 0 | DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT | DD_FAIL_QUIETLY_EACCES); if (not_reportable) retval = 256; free(not_reportable); } if (dd) dd_close(dd); /* Stop if exit code is not 0, or no more commands */ if (stop_requested || retval != 0 || spawn_next_command_in_evd(evd) < 0 ) { log_notice("done running event on '%s': %d", g_dump_dir_name, retval); append_to_textview(g_tv_event_log, "\n"); /* Free child output buffer */ strbuf_free(cmd_output); cmd_output = NULL; /* Hide spinner and stop btn */ gtk_widget_hide(GTK_WIDGET(g_spinner_event_log)); gtk_widget_hide(g_btn_stop); /* Enable (un-gray out) navigation buttons */ gtk_widget_set_sensitive(g_btn_close, true); gtk_widget_set_sensitive(g_btn_next, true); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(UPDATE_SELECTED_EVENT); if (retval != 0) { gtk_widget_show(GTK_WIDGET(g_img_process_fail)); /* 256 means NOT_REPORTABLE */ if (retval == 256) cancel_processing(g_lbl_event_log, _("Processing was interrupted because the problem is not reportable."), TERMINATE_NOFLAGS); else { /* We use SIGTERM to stop event processing on user's request. * So SIGTERM is not a failure. */ if (retval == EXIT_CANCEL_BY_USER || WTERMSIG(run_state->process_status) == SIGTERM) cancel_processing(g_lbl_event_log, /* default message */ NULL, TERMINATE_NOFLAGS); else { cancel_processing(g_lbl_event_log, _("Processing failed."), TERMINATE_WITH_RERUN); on_failed_event(evd->event_name); } } } else { gtk_label_set_text(g_lbl_event_log, is_processing_finished() ? _("Processing finished.") : _("Processing finished, please proceed to the next step.")); } g_source_remove(g_event_source_id); g_event_source_id = 0; close(evd->fd); g_io_channel_unref(evd->channel); free_run_event_state(evd->run_state); strbuf_free(evd->event_log); free(evd->event_name); free(evd); /* Inform abrt-gui that it is a good idea to rescan the directory */ kill(getppid(), SIGCHLD); if (is_processing_finished()) hide_next_step_button(); else if (retval == 0 && !g_verbose && !g_expert_mode) on_next_btn_cb(GTK_WIDGET(g_btn_next), NULL); return FALSE; /* "please remove this event" */ } /* New command was started. Continue waiting for input */ /* Transplant cmd's output fd onto old one, so that main loop * is none the wiser that fd it waits on has changed */ xmove_fd(evd->run_state->command_out_fd, evd->fd); evd->run_state->command_out_fd = evd->fd; /* just to keep it consistent */ ndelay_on(evd->fd); /* Revive "Cancel" button */ g_event_child_pid = evd->run_state->command_pid; return TRUE; /* "please don't remove this event (yet)" */ } static int ask_replace_old_private_group_name(void) { char *message = xasprintf(_("Private ticket is requested but the group name 'private' has been deprecated. " "We kindly ask you to use 'fedora_contrib_private' group name. " "Click Yes button or update the configuration manually. Or click No button, if you really want to use 'private' group.\n\n" "If you are not sure what this dialogue means, please trust us and click Yes button.\n\n" "Read more about the private bug reports at:\n" "https://github.com/abrt/abrt/wiki/FAQ#creating-private-bugzilla-tickets\n" "https://bugzilla.redhat.com/show_bug.cgi?id=1044653\n")); char *markup_message = xasprintf(_("Private ticket is requested but the group name <i>private</i> has been deprecated. " "We kindly ask you to use <i>fedora_contrib_private</i> group name. " "Click Yes button or update the configuration manually. Or click No button, if you really want to use <i>private</i> group.\n\n" "If you are not sure what this dialogue means, please trust us and click Yes button.\n\n" "Read more about the private bug reports at:\n" "<a href=\"https://github.com/abrt/abrt/wiki/FAQ#creating-private-bugzilla-tickets\">" "https://github.com/abrt/abrt/wiki/FAQ#creating-private-bugzilla-tickets</a>\n" "<a href=\"https://bugzilla.redhat.com/show_bug.cgi?id=1044653\">https://bugzilla.redhat.com/show_bug.cgi?id=1044653</a>\n")); GtkWidget *old_private_group = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_YES_NO, message); gtk_window_set_transient_for(GTK_WINDOW(old_private_group), GTK_WINDOW(g_wnd_assistant)); gtk_message_dialog_set_markup(GTK_MESSAGE_DIALOG(old_private_group), markup_message); free(message); free(markup_message); /* Esc -> No, Enter -> Yes */ gtk_dialog_set_default_response(GTK_DIALOG(old_private_group), GTK_RESPONSE_YES); gint result = gtk_dialog_run(GTK_DIALOG(old_private_group)); gtk_widget_destroy(old_private_group); return result == GTK_RESPONSE_YES; } /* * https://bugzilla.redhat.com/show_bug.cgi?id=1044653 */ static void correct_bz_private_goup_name(const char *event_name) { if (strcmp("report_Bugzilla", event_name) == 0 && gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(gtk_builder_get_object(g_builder, PRIVATE_TICKET_CB)))) { event_config_t *cfg = get_event_config(event_name); if (NULL != cfg) { GList *item = cfg->options; for ( ; item != NULL; item = g_list_next(item)) { event_option_t *opt = item->data; if (strcmp("Bugzilla_PrivateGroups", opt->eo_name) == 0 && opt->eo_value && strcmp(opt->eo_value, "private") == 0 && ask_replace_old_private_group_name()) { free(opt->eo_value); opt->eo_value = xstrdup("fedora_contrib_private"); } } } } } static void start_event_run(const char *event_name) { /* Start event asynchronously on the dump dir * (synchronous run would freeze GUI until completion) */ /* https://bugzilla.redhat.com/show_bug.cgi?id=1044653 */ correct_bz_private_goup_name(event_name); struct run_event_state *state = new_run_event_state(); state->logging_callback = run_event_gtk_logging; state->error_callback = run_event_gtk_error; state->alert_callback = run_event_gtk_alert; state->ask_callback = run_event_gtk_ask; state->ask_yes_no_callback = run_event_gtk_ask_yes_no; state->ask_yes_no_yesforever_callback = run_event_gtk_ask_yes_no_yesforever; state->ask_yes_no_save_result_callback = run_event_gtk_ask_yes_no_save_result; state->ask_password_callback = run_event_gtk_ask_password; if (prepare_commands(state, g_dump_dir_name, event_name) == 0) { no_cmds: /* No commands needed?! (This is untypical) */ free_run_event_state(state); //TODO: better msg? char *msg = xasprintf(_("No processing for event '%s' is defined"), event_name); append_to_textview(g_tv_event_log, msg); free(msg); cancel_processing(g_lbl_event_log, _("Processing failed."), TERMINATE_NOFLAGS); return; } struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); dd_close(dd); if (!dd) { free_run_event_state(state); if (!g_expert_mode) { cancel_processing(g_lbl_event_log, _("Processing interrupted: can't continue without writable directory."), TERMINATE_NOFLAGS); } return; /* user refused to steal, or write error, etc... */ } set_excluded_envvar(); GList *env_list = export_event_config(event_name); if (spawn_next_command(state, g_dump_dir_name, event_name, EXECFLG_SETPGID) < 0) { unexport_event_config(env_list); goto no_cmds; } g_event_child_pid = state->command_pid; /* At least one command is needed, and we started first one. * Hook its output fd to the main loop. */ struct analyze_event_data *evd = xzalloc(sizeof(*evd)); evd->run_state = state; evd->event_name = xstrdup(event_name); evd->env_list = env_list; evd->event_log = strbuf_new(); evd->fd = state->command_out_fd; state->logging_param = evd; state->error_param = evd; state->interaction_param = evd; ndelay_on(evd->fd); evd->channel = g_io_channel_unix_new(evd->fd); g_event_source_id = g_io_add_watch(evd->channel, G_IO_IN | G_IO_ERR | G_IO_HUP, /* need HUP to detect EOF w/o any data */ consume_cmd_output, evd ); gtk_label_set_text(g_lbl_event_log, _("Processing...")); log_notice("running event '%s' on '%s'", event_name, g_dump_dir_name); char *msg = xasprintf("--- Running %s ---\n", event_name); append_to_textview(g_tv_event_log, msg); free(msg); /* don't bother testing if they are visible, this is faster */ gtk_widget_hide(GTK_WIDGET(g_img_process_fail)); gtk_widget_show(GTK_WIDGET(g_spinner_event_log)); gtk_widget_show(g_btn_stop); /* Disable (gray out) navigation buttons */ gtk_widget_set_sensitive(g_btn_close, false); gtk_widget_set_sensitive(g_btn_next, false); } /* * the widget is added as a child of the VBox in the warning area * */ static void add_widget_to_warning_area(GtkWidget *widget) { g_warning_issued = true; gtk_box_pack_start(g_box_warning_labels, widget, false, false, 0); gtk_widget_show_all(widget); } /* Backtrace checkbox handling */ static void add_warning(const char *warning) { char *label_str = xasprintf("• %s", warning); GtkWidget *warning_lbl = gtk_label_new(NULL); gtk_label_set_markup(GTK_LABEL(warning_lbl), label_str); /* should be safe to free it, gtk calls strdup() to copy it */ free(label_str); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 13) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 13 && GTK_MICRO_VERSION < 5)) gtk_misc_set_alignment(GTK_MISC(warning_lbl), 0.0, 0.0); #else gtk_widget_set_halign (warning_lbl, GTK_ALIGN_START); gtk_widget_set_valign (warning_lbl, GTK_ALIGN_END); #endif gtk_label_set_justify(GTK_LABEL(warning_lbl), GTK_JUSTIFY_LEFT); gtk_label_set_line_wrap(GTK_LABEL(warning_lbl), TRUE); add_widget_to_warning_area(warning_lbl); } static void on_sensitive_ticket_clicked_cb(GtkWidget *button, gpointer user_data) { if (gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(button))) { xsetenv(CREATE_PRIVATE_TICKET, "1"); } else { safe_unsetenv(CREATE_PRIVATE_TICKET); } } static void add_sensitive_data_warning(void) { GtkBuilder *builder = make_builder(); GtkWidget *sens_data_warn = GTK_WIDGET(gtk_builder_get_object(builder, SENSITIVE_DATA_WARN)); GtkButton *sens_ticket_cb = GTK_BUTTON(gtk_builder_get_object(builder, PRIVATE_TICKET_CB)); g_signal_connect(sens_ticket_cb, "toggled", G_CALLBACK(on_sensitive_ticket_clicked_cb), NULL); add_widget_to_warning_area(GTK_WIDGET(sens_data_warn)); g_object_unref(builder); } static void show_warnings(void) { if (g_warning_issued) gtk_widget_show(g_widget_warnings_area); } static void clear_warnings(void) { /* erase all warnings */ if (!g_warning_issued) return; gtk_widget_hide(g_widget_warnings_area); gtk_container_foreach(GTK_CONTAINER(g_box_warning_labels), &remove_child_widget, NULL); g_warning_issued = false; } /* TODO : this function should not set a warning directly, it makes the function unusable for add_event_buttons(); */ static bool check_minimal_bt_rating(const char *event_name) { bool acceptable_rating = true; event_config_t *event_cfg = NULL; if (!event_name) error_msg_and_die(_("Cannot check backtrace rating because of invalid event name")); else if (prefixcmp(event_name, "report") != 0) { log_info("No checks for bactrace rating because event '%s' doesn't report.", event_name); return acceptable_rating; } else event_cfg = get_event_config(event_name); char *description = NULL; acceptable_rating = check_problem_rating_usability(event_cfg, g_cd, &description, NULL); if (description) { add_warning(description); free(description); } return acceptable_rating; } static void on_bt_approve_toggle(GtkToggleButton *togglebutton, gpointer user_data) { gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt)); } static void toggle_eb_comment(void) { /* The page doesn't exist with report-only option */ if (pages[PAGENO_EDIT_COMMENT].page_widget == NULL) return; bool good = gtk_text_buffer_get_char_count(gtk_text_view_get_buffer(g_tv_comment)) >= 10 || gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(g_cb_no_comment)); /* Allow next page only when the comment has at least 10 chars */ gtk_widget_set_sensitive(g_btn_next, good); /* And show the eventbox with label */ if (good) gtk_widget_hide(GTK_WIDGET(g_eb_comment)); else gtk_widget_show(GTK_WIDGET(g_eb_comment)); } static void on_comment_changed(GtkTextBuffer *buffer, gpointer user_data) { toggle_eb_comment(); } static void on_no_comment_toggled(GtkToggleButton *togglebutton, gpointer user_data) { toggle_eb_comment(); } static void on_log_changed(GtkTextBuffer *buffer, gpointer user_data) { gtk_widget_show(GTK_WIDGET(g_exp_report_log)); } #if 0 static void log_ready_state(void) { char buf[NUM_PAGES+1]; for (int i = 0; i < NUM_PAGES; i++) { char ch = '_'; if (pages[i].page_widget) ch = gtk_assistant_get_page_complete(g_assistant, pages[i].page_widget) ? '+' : '-'; buf[i] = ch; } buf[NUM_PAGES] = 0; log("Completeness:[%s]", buf); } #endif static GList *find_words_in_text_buffer(int page, GtkTextView *tev, GList *words, GList *ignore_sitem_list, GtkTextIter start_find, GtkTextIter end_find, bool case_insensitive ) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(tev); gtk_text_buffer_set_modified(buffer, FALSE); GList *found_words = NULL; GtkTextIter start_match; GtkTextIter end_match; for (GList *w = words; w; w = g_list_next(w)) { gtk_text_buffer_get_start_iter(buffer, &start_find); const char *search_word = w->data; while (search_word && search_word[0] && gtk_text_iter_forward_search(&start_find, search_word, GTK_TEXT_SEARCH_TEXT_ONLY | (case_insensitive ? GTK_TEXT_SEARCH_CASE_INSENSITIVE : 0), &start_match, &end_match, NULL)) { search_item_t *found_word = sitem_new( page, buffer, tev, start_match, end_match ); int offset = gtk_text_iter_get_offset(&end_match); gtk_text_buffer_get_iter_at_offset(buffer, &start_find, offset); if (sitem_is_in_sitemlist(found_word, ignore_sitem_list)) { sitem_free(found_word); // don't count the word if it's part of some of the ignored words continue; } found_words = g_list_prepend(found_words, found_word); } } return found_words; } static void search_item_to_list_store_item(GtkListStore *store, GtkTreeIter *new_row, const gchar *file_name, search_item_t *word) { GtkTextIter *beg = gtk_text_iter_copy(&(word->start)); gtk_text_iter_backward_line(beg); GtkTextIter *end = gtk_text_iter_copy(&(word->end)); /* the first call moves end variable at the end of the current line */ if (gtk_text_iter_forward_line(end)) { /* the second call moves end variable at the end of the next line */ gtk_text_iter_forward_line(end); /* don't include the last new which causes an empty line in the GUI list */ gtk_text_iter_backward_char(end); } gchar *tmp = gtk_text_buffer_get_text(word->buffer, beg, &(word->start), /*don't include hidden chars*/FALSE); gchar *prefix = g_markup_escape_text(tmp, /*NULL terminated string*/-1); g_free(tmp); tmp = gtk_text_buffer_get_text(word->buffer, &(word->start), &(word->end), /*don't include hidden chars*/FALSE); gchar *text = g_markup_escape_text(tmp, /*NULL terminated string*/-1); g_free(tmp); tmp = gtk_text_buffer_get_text(word->buffer, &(word->end), end, /*don't include hidden chars*/FALSE); gchar *suffix = g_markup_escape_text(tmp, /*NULL terminated string*/-1); g_free(tmp); char *content = xasprintf("%s<span foreground=\"red\">%s</span>%s", prefix, text, suffix); g_free(suffix); g_free(text); g_free(prefix); gtk_text_iter_free(end); gtk_text_iter_free(beg); gtk_list_store_set(store, new_row, SEARCH_COLUMN_FILE, file_name, SEARCH_COLUMN_TEXT, content, SEARCH_COLUMN_ITEM, word, -1); } static bool highligh_words_in_textview(int page, GtkTextView *tev, GList *words, GList *ignored_words, bool case_insensitive) { GtkTextBuffer *buffer = gtk_text_view_get_buffer(tev); gtk_text_buffer_set_modified(buffer, FALSE); GtkWidget *notebook_child = gtk_notebook_get_nth_page(g_notebook, page); GtkWidget *tab_lbl = gtk_notebook_get_tab_label(g_notebook, notebook_child); /* Remove old results */ bool buffer_removing = false; GtkTreeIter iter; gboolean valid = gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_ls_sensitive_list), &iter); /* Turn off the changed callback during the update */ g_signal_handler_block(g_tv_sensitive_sel, g_tv_sensitive_sel_hndlr); while (valid) { char *text = NULL; search_item_t *word = NULL; gtk_tree_model_get(GTK_TREE_MODEL(g_ls_sensitive_list), &iter, SEARCH_COLUMN_TEXT, &text, SEARCH_COLUMN_ITEM, &word, -1); free(text); if (word->buffer == buffer) { buffer_removing = true; valid = gtk_list_store_remove(g_ls_sensitive_list, &iter); if (word == g_current_highlighted_word) g_current_highlighted_word = NULL; free(word); } else { if(buffer_removing) break; valid = gtk_tree_model_iter_next(GTK_TREE_MODEL(g_ls_sensitive_list), &iter); } } /* Turn on the changed callback after the update */ g_signal_handler_unblock(g_tv_sensitive_sel, g_tv_sensitive_sel_hndlr); GtkTextIter start_find; gtk_text_buffer_get_start_iter(buffer, &start_find); GtkTextIter end_find; gtk_text_buffer_get_end_iter(buffer, &end_find); gtk_text_buffer_remove_tag_by_name(buffer, "search_result_bg", &start_find, &end_find); gtk_text_buffer_remove_tag_by_name(buffer, "current_result_bg", &start_find, &end_find); PangoAttrList *attrs = gtk_label_get_attributes(GTK_LABEL(tab_lbl)); gtk_label_set_attributes(GTK_LABEL(tab_lbl), NULL); pango_attr_list_unref(attrs); GList *result = NULL; GList *ignored_words_in_buffer = NULL; ignored_words_in_buffer = find_words_in_text_buffer(page, tev, ignored_words, NULL, start_find, end_find, /*case sensitive*/false); result = find_words_in_text_buffer(page, tev, words, ignored_words_in_buffer, start_find, end_find, case_insensitive ); for (GList *w = result; w; w = g_list_next(w)) { search_item_t *item = (search_item_t *)w->data; gtk_text_buffer_apply_tag_by_name(buffer, "search_result_bg", sitem_get_start_iter(item), sitem_get_end_iter(item)); } if (result) { PangoAttrList *attrs = pango_attr_list_new(); PangoAttribute *foreground_attr = pango_attr_foreground_new(65535, 0, 0); pango_attr_list_insert(attrs, foreground_attr); PangoAttribute *underline_attr = pango_attr_underline_new(PANGO_UNDERLINE_SINGLE); pango_attr_list_insert(attrs, underline_attr); gtk_label_set_attributes(GTK_LABEL(tab_lbl), attrs); /* The current order of the found words is defined by order of words in the * passed list. We have to order the words according to their occurrence in * the buffer. */ result = g_list_sort(result, (GCompareFunc)sitem_compare); GList *search_result = result; for ( ; search_result != NULL; search_result = g_list_next(search_result)) { search_item_t *word = (search_item_t *)search_result->data; const gchar *file_name = gtk_label_get_text(GTK_LABEL(tab_lbl)); /* Create a new row */ GtkTreeIter new_row; if (valid) /* iter variable is valid GtkTreeIter and it means that the results */ /* need to be inserted before this iterator, in this case iter points */ /* to the first word of another GtkTextView */ gtk_list_store_insert_before(g_ls_sensitive_list, &new_row, &iter); else /* the GtkTextView is the last one or the only one, insert the results */ /* at the end of the list store */ gtk_list_store_append(g_ls_sensitive_list, &new_row); /* Assign values to the new row */ search_item_to_list_store_item(g_ls_sensitive_list, &new_row, file_name, word); } } g_list_free_full(ignored_words_in_buffer, free); g_list_free(result); return result != NULL; } static gboolean highligh_words_in_tabs(GList *forbidden_words, GList *allowed_words, bool case_insensitive) { gboolean found = false; gint n_pages = gtk_notebook_get_n_pages(g_notebook); int page = 0; for (page = 0; page < n_pages; page++) { //notebook_page->scrolled_window->text_view GtkWidget *notebook_child = gtk_notebook_get_nth_page(g_notebook, page); GtkWidget *tab_lbl = gtk_notebook_get_tab_label(g_notebook, notebook_child); const char *const lbl_txt = gtk_label_get_text(GTK_LABEL(tab_lbl)); if (strncmp(lbl_txt, "page 1", 5) == 0 || strcmp(FILENAME_COMMENT, lbl_txt) == 0) continue; GtkTextView *tev = GTK_TEXT_VIEW(gtk_bin_get_child(GTK_BIN(notebook_child))); found |= highligh_words_in_textview(page, tev, forbidden_words, allowed_words, case_insensitive); } GtkTreeIter iter; if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(g_ls_sensitive_list), &iter)) gtk_tree_selection_select_iter(g_tv_sensitive_sel, &iter); return found; } static gboolean highlight_forbidden(void) { GList *forbidden_words = load_words_from_file(FORBIDDEN_WORDS_BLACKLLIST); GList *allowed_words = load_words_from_file(FORBIDDEN_WORDS_WHITELIST); const gboolean result = highligh_words_in_tabs(forbidden_words, allowed_words, /*case sensitive*/false); list_free_with_free(forbidden_words); list_free_with_free(allowed_words); return result; } static char *get_next_processed_event(GList **events_list) { if (!events_list || !*events_list) return NULL; char *event_name = (char *)(*events_list)->data; const size_t event_len = strlen(event_name); /* pop the current event */ *events_list = g_list_delete_link(*events_list, *events_list); if (event_name[event_len - 1] == '*') { log_info("Expanding event '%s'", event_name); struct dump_dir *dd = dd_opendir(g_dump_dir_name, DD_OPEN_READONLY); if (!dd) error_msg_and_die("Can't open directory '%s'", g_dump_dir_name); /* Erase '*' */ event_name[event_len - 1] = '\0'; /* get 'event1\nevent2\nevent3\n' or '' if no event is possible */ char *expanded_events = list_possible_events(dd, g_dump_dir_name, event_name); dd_close(dd); free(event_name); GList *expanded_list = NULL; /* add expanded events from event having trailing '*' */ char *next = event_name = expanded_events; while ((next = strchr(event_name, '\n'))) { /* 'event1\0event2\nevent3\n' */ next[0] = '\0'; /* 'event1' */ event_name = xstrdup(event_name); log_debug("Adding a new expanded event '%s' to the processed list", event_name); /* the last event is not added to the expanded list */ ++next; if (next[0] == '\0') break; expanded_list = g_list_prepend(expanded_list, event_name); /* 'event2\nevent3\n' */ event_name = next; } free(expanded_events); /* It's OK we can safely compare address even if them were previously freed */ if (event_name != expanded_events) /* the last expanded event name is stored in event_name */ *events_list = g_list_concat(expanded_list, *events_list); else { log_info("No event was expanded, will continue with the next one."); /* no expanded event try the next event */ return get_next_processed_event(events_list); } } clear_warnings(); const bool acceptable = check_minimal_bt_rating(event_name); show_warnings(); if (!acceptable) { /* a node for this event was already removed */ free(event_name); g_list_free_full(*events_list, free); *events_list = NULL; return NULL; } return event_name; } static void on_page_prepare(GtkNotebook *assistant, GtkWidget *page, gpointer user_data) { //int page_no = gtk_assistant_get_current_page(g_assistant); //log_ready_state(); /* This suppresses [Last] button: assistant thinks that * we never have this page ready unless we are on it * -> therefore there is at least one non-ready page * -> therefore it won't show [Last] */ // Doesn't work: if Completeness:[++++++-+++], // then [Last] btn will still be shown. //gtk_assistant_set_page_complete(g_assistant, // pages[PAGENO_REVIEW_DATA].page_widget, // pages[PAGENO_REVIEW_DATA].page_widget == page //); /* If processing is finished and if it was terminated because of an error * the event progress page is selected. So, it does not make sense to show * the next step button and we MUST NOT clear warnings. */ if (!is_processing_finished()) { /* some pages hide it, so restore it to it's default */ show_next_step_button(); clear_warnings(); } gtk_widget_hide(g_btn_detail); gtk_widget_hide(g_btn_onfail); if (!g_expert_mode) gtk_widget_hide(g_btn_repeat); /* Save text fields if changed */ /* Must be called before any GUI operation because the following two * functions causes recreating of the text items tabs, thus all updates to * these tabs will be lost */ save_items_from_notepad(); save_text_from_text_view(g_tv_comment, FILENAME_COMMENT); if (pages[PAGENO_SUMMARY].page_widget == page) { if (!g_expert_mode) { /* Skip intro screen */ int n = select_next_page_no(pages[PAGENO_SUMMARY].page_no, NULL); log_info("switching to page_no:%d", n); gtk_notebook_set_current_page(assistant, n); return; } } if (pages[PAGENO_EDIT_ELEMENTS].page_widget == page) { if (highlight_forbidden()) { add_sensitive_data_warning(); show_warnings(); gtk_expander_set_expanded(g_exp_search, TRUE); } else gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(g_rb_custom_search), TRUE); show_warnings(); } if (pages[PAGENO_REVIEW_DATA].page_widget == page) { update_ls_details_checkboxes(g_event_selected); gtk_widget_set_sensitive(g_btn_next, gtk_toggle_button_get_active(g_tb_approve_bt)); } if (pages[PAGENO_EDIT_COMMENT].page_widget == page) { gtk_widget_show(g_btn_detail); gtk_widget_set_sensitive(g_btn_next, false); on_comment_changed(gtk_text_view_get_buffer(g_tv_comment), NULL); } //log_ready_state(); if (pages[PAGENO_EVENT_PROGRESS].page_widget == page) { log_info("g_event_selected:'%s'", g_event_selected); if (g_event_selected && g_event_selected[0] ) { clear_warnings(); start_event_run(g_event_selected); } } if(pages[PAGENO_EVENT_SELECTOR].page_widget == page) { if (!g_expert_mode && !g_auto_event_list) hide_next_step_button(); } } //static void event_rb_was_toggled(GtkButton *button, gpointer user_data) static void set_auto_event_chain(GtkButton *button, gpointer user_data) { //event is selected, so make sure the expert mode is disabled g_expert_mode = false; workflow_t *w = (workflow_t *)user_data; config_item_info_t *info = workflow_get_config_info(w); log_notice("selected workflow '%s'", ci_get_screen_name(info)); GList *wf_event_list = wf_get_event_list(w); while(wf_event_list) { g_auto_event_list = g_list_append(g_auto_event_list, xstrdup(ec_get_name(wf_event_list->data))); load_single_event_config_data_from_user_storage((event_config_t *)wf_event_list->data); wf_event_list = g_list_next(wf_event_list); } gint current_page_no = gtk_notebook_get_current_page(g_assistant); gint next_page_no = select_next_page_no(current_page_no, NULL); /* if pageno is not change 'switch-page' signal is not emitted */ if (current_page_no == next_page_no) on_page_prepare(g_assistant, gtk_notebook_get_nth_page(g_assistant, next_page_no), NULL); else gtk_notebook_set_current_page(g_assistant, next_page_no); /* Show Next Step button which was hidden on Selector page in non-expert * mode. Next Step button must be hidden because Selector page shows only * workflow buttons in non-expert mode. */ show_next_step_button(); } static void add_workflow_buttons(GtkBox *box, GHashTable *workflows, GCallback func) { gtk_container_foreach(GTK_CONTAINER(box), &remove_child_widget, NULL); GList *possible_workflows = list_possible_events_glist(g_dump_dir_name, "workflow"); GHashTable *workflow_table = load_workflow_config_data_from_list( possible_workflows, WORKFLOWS_DIR); g_list_free_full(possible_workflows, free); g_object_set_data_full(G_OBJECT(box), "workflows", workflow_table, (GDestroyNotify)g_hash_table_destroy); GList *wf_list = g_hash_table_get_values(workflow_table); wf_list = g_list_sort(wf_list, (GCompareFunc)wf_priority_compare); for (GList *wf_iter = wf_list; wf_iter; wf_iter = g_list_next(wf_iter)) { workflow_t *w = (workflow_t *)wf_iter->data; char *btn_label = xasprintf("<b>%s</b>\n%s", wf_get_screen_name(w), wf_get_description(w)); GtkWidget *button = gtk_button_new_with_label(btn_label); GList *children = gtk_container_get_children(GTK_CONTAINER(button)); GtkWidget *label = (GtkWidget *)children->data; gtk_label_set_use_markup(GTK_LABEL(label), true); gtk_widget_set_halign(label, GTK_ALIGN_START); gtk_widget_set_margin_top(label, 10); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 11) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 11 && GTK_MICRO_VERSION < 2)) gtk_widget_set_margin_left(label, 40); #else gtk_widget_set_margin_start(label, 40); #endif gtk_widget_set_margin_bottom(label, 10); g_list_free(children); free(btn_label); g_signal_connect(button, "clicked", func, w); gtk_box_pack_start(box, button, true, false, 2); } g_list_free(wf_list); } static char *setup_next_processed_event(GList **events_list) { free(g_event_selected); g_event_selected = NULL; char *event = get_next_processed_event(&g_auto_event_list); if (!event) { /* No next event, go to progress page and finish */ gtk_label_set_text(g_lbl_event_log, _("Processing finished.")); /* we don't know the result of the previous event here * so at least hide the spinner, because we're obviously finished */ gtk_widget_hide(GTK_WIDGET(g_spinner_event_log)); hide_next_step_button(); return NULL; } log_notice("selected -e EVENT:%s", event); return event; } static bool get_sensitive_data_permission(const char *event_name) { event_config_t *event_cfg = get_event_config(event_name); if (!event_cfg || !event_cfg->ec_sending_sensitive_data) return true; char *msg = xasprintf(_("Event '%s' requires permission to send possibly sensitive data." "\nDo you want to continue?"), ec_get_screen_name(event_cfg) ? ec_get_screen_name(event_cfg) : event_name); const bool response = run_ask_yes_no_yesforever_dialog("ask_send_sensitive_data", msg, GTK_WINDOW(g_wnd_assistant)); free(msg); return response; } static gint select_next_page_no(gint current_page_no, gpointer data) { GtkWidget *page; again: log_notice("%s: current_page_no:%d", __func__, current_page_no); current_page_no++; page = gtk_notebook_get_nth_page(g_assistant, current_page_no); if (pages[PAGENO_EVENT_SELECTOR].page_widget == page) { if (!g_expert_mode && (g_auto_event_list == NULL)) { return current_page_no; //stay here and let user select the workflow } if (!g_expert_mode) { /* (note: this frees and sets to NULL g_event_selected) */ char *event = setup_next_processed_event(&g_auto_event_list); if (!event) { current_page_no = pages[PAGENO_EVENT_PROGRESS].page_no - 1; goto again; } if (!get_sensitive_data_permission(event)) { free(event); cancel_processing(g_lbl_event_log, /* default message */ NULL, TERMINATE_NOFLAGS); current_page_no = pages[PAGENO_EVENT_PROGRESS].page_no - 1; goto again; } if (problem_data_get_content_or_NULL(g_cd, FILENAME_NOT_REPORTABLE)) { free(event); char *msg = xasprintf(_("This problem should not be reported " "(it is likely a known problem). %s"), problem_data_get_content_or_NULL(g_cd, FILENAME_NOT_REPORTABLE) ); cancel_processing(g_lbl_event_log, msg, TERMINATE_NOFLAGS); free(msg); current_page_no = pages[PAGENO_EVENT_PROGRESS].page_no - 1; goto again; } g_event_selected = event; /* Notify a user that some configuration options miss values, but */ /* don't force him to provide them. */ check_event_config(g_event_selected); /* >>> and this but this is clearer * because it does exactly the same thing * but I'm pretty scared to touch it */ current_page_no = pages[PAGENO_EVENT_SELECTOR].page_no + 1; goto event_was_selected; } } if (pages[PAGENO_EVENT_SELECTOR + 1].page_widget == page) { event_was_selected: if (!g_event_selected) { /* Go back to selectors */ current_page_no = pages[PAGENO_EVENT_SELECTOR].page_no - 1; goto again; } if (!event_need_review(g_event_selected)) { current_page_no = pages[PAGENO_EVENT_PROGRESS].page_no - 1; goto again; } } #if 0 if (pages[PAGENO_EDIT_COMMENT].page_widget == page) { if (problem_data_get_content_or_NULL(g_cd, FILENAME_COMMENT)) goto again; /* no comment, skip this page */ } #endif if (pages[PAGENO_EVENT_DONE].page_widget == page) { if (g_auto_event_list) { /* Go back to selectors */ current_page_no = pages[PAGENO_SUMMARY].page_no; } goto again; } if (pages[PAGENO_NOT_SHOWN].page_widget == page) { if (!g_expert_mode) exit(0); /* No! this would SEGV (infinitely recurse into select_next_page_no) */ /*gtk_assistant_commit(g_assistant);*/ current_page_no = pages[PAGENO_EVENT_SELECTOR].page_no - 1; goto again; } log_notice("%s: selected page #%d", __func__, current_page_no); return current_page_no; } static void rehighlight_forbidden_words(int page, GtkTextView *tev) { GList *forbidden_words = load_words_from_file(FORBIDDEN_WORDS_BLACKLLIST); GList *allowed_words = load_words_from_file(FORBIDDEN_WORDS_WHITELIST); highligh_words_in_textview(page, tev, forbidden_words, allowed_words, /*case sensitive*/false); list_free_with_free(forbidden_words); list_free_with_free(allowed_words); } static void on_sensitive_word_selection_changed(GtkTreeSelection *sel, gpointer user_data) { search_item_t *old_word = g_current_highlighted_word; g_current_highlighted_word = NULL; if (old_word && FALSE == gtk_text_buffer_get_modified(old_word->buffer)) gtk_text_buffer_remove_tag_by_name(old_word->buffer, "current_result_bg", &(old_word->start), &(old_word->end)); GtkTreeModel *model; GtkTreeIter iter; if (!gtk_tree_selection_get_selected(sel, &model, &iter)) return; search_item_t *new_word; gtk_tree_model_get(model, &iter, SEARCH_COLUMN_ITEM, &new_word, -1); if (gtk_text_buffer_get_modified(new_word->buffer)) { if (g_search_text == NULL) rehighlight_forbidden_words(new_word->page, new_word->tev); else { log_notice("searching again: '%s'", g_search_text); GList *searched_words = g_list_append(NULL, (gpointer)g_search_text); highligh_words_in_textview(new_word->page, new_word->tev, searched_words, NULL, /*case insensitive*/true); g_list_free(searched_words); } return; } g_current_highlighted_word = new_word; gtk_notebook_set_current_page(g_notebook, new_word->page); gtk_text_buffer_apply_tag_by_name(new_word->buffer, "current_result_bg", &(new_word->start), &(new_word->end)); gtk_text_buffer_place_cursor(new_word->buffer, &(new_word->start)); gtk_text_view_scroll_to_iter(new_word->tev, &(new_word->start), 0.0, false, 0, 0); } static void highlight_search(GtkEntry *entry) { g_search_text = gtk_entry_get_text(entry); log_notice("searching: '%s'", g_search_text); GList *words = g_list_append(NULL, (gpointer)g_search_text); highligh_words_in_tabs(words, NULL, /*case insensitive*/true); g_list_free(words); } static gboolean highlight_search_on_timeout(gpointer user_data) { g_timeout = 0; highlight_search(GTK_ENTRY(user_data)); /* returning false will make glib to remove this event */ return false; } static void search_timeout(GtkEntry *entry) { /* this little hack makes the search start searching after 500 milisec after * user stops writing into entry box * if this part is removed, then the search will be started on every * change of the search entry */ if (g_timeout != 0) g_source_remove(g_timeout); g_timeout = g_timeout_add(500, &highlight_search_on_timeout, (gpointer)entry); } static void on_forbidden_words_toggled(GtkToggleButton *btn, gpointer user_data) { g_search_text = NULL; log_notice("nothing to search for, highlighting forbidden words instead"); highlight_forbidden(); } static void on_custom_search_toggled(GtkToggleButton *btn, gpointer user_data) { const gboolean custom_search = gtk_toggle_button_get_active(btn); gtk_widget_set_sensitive(GTK_WIDGET(g_search_entry_bt), custom_search); if (custom_search) highlight_search(g_search_entry_bt); } static void save_edited_one_liner(GtkCellRendererText *renderer, gchar *tree_path, gchar *new_text, gpointer user_data) { //log("path:'%s' new_text:'%s'", tree_path, new_text); GtkTreeIter iter; if (!gtk_tree_model_get_iter_from_string(GTK_TREE_MODEL(g_ls_details), &iter, tree_path)) return; gchar *item_name = NULL; gtk_tree_model_get(GTK_TREE_MODEL(g_ls_details), &iter, DETAIL_COLUMN_NAME, &item_name, -1); if (!item_name) /* paranoia, should never happen */ return; struct problem_item *item = problem_data_get_item_or_NULL(g_cd, item_name); if (item && (item->flags & CD_FLAG_ISEDITABLE)) { struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); if (dd) { dd_save_text(dd, item_name, new_text); free(item->content); item->content = xstrdup(new_text); gtk_list_store_set(g_ls_details, &iter, DETAIL_COLUMN_VALUE, new_text, -1); } dd_close(dd); } } static void on_btn_add_file(GtkButton *button) { GtkWidget *dialog = gtk_file_chooser_dialog_new( "Attach File", GTK_WINDOW(g_wnd_assistant), GTK_FILE_CHOOSER_ACTION_OPEN, _("_Cancel"), GTK_RESPONSE_CANCEL, _("_Open"), GTK_RESPONSE_ACCEPT, NULL ); char *filename = NULL; if (gtk_dialog_run(GTK_DIALOG(dialog)) == GTK_RESPONSE_ACCEPT) filename = gtk_file_chooser_get_filename(GTK_FILE_CHOOSER(dialog)); gtk_widget_destroy(dialog); if (filename) { char *basename = strrchr(filename, '/'); if (!basename) /* wtf? (never happens) */ goto free_and_ret; basename++; /* TODO: ask for the name to save it as? For now, just use basename */ char *message = NULL; struct stat statbuf; if (stat(filename, &statbuf) != 0 || !S_ISREG(statbuf.st_mode)) { message = xasprintf(_("'%s' is not an ordinary file"), filename); goto show_msgbox; } struct problem_item *item = problem_data_get_item_or_NULL(g_cd, basename); if (!item || (item->flags & CD_FLAG_ISEDITABLE)) { struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); if (dd) { dd_close(dd); char *new_name = concat_path_file(g_dump_dir_name, basename); if (strcmp(filename, new_name) == 0) { message = xstrdup(_("You are trying to copy a file onto itself")); } else { off_t r = copy_file(filename, new_name, 0666); if (r < 0) { message = xasprintf(_("Can't copy '%s': %s"), filename, strerror(errno)); unlink(new_name); } if (!message) { problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(/* don't update selected event */ 0); /* Set flags for the new item */ update_ls_details_checkboxes(g_event_selected); } } free(new_name); } } else message = xasprintf(_("Item '%s' already exists and is not modifiable"), basename); if (message) { show_msgbox: ; GtkWidget *dlg = gtk_message_dialog_new(GTK_WINDOW(g_wnd_assistant), GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_WARNING, GTK_BUTTONS_CLOSE, message); free(message); gtk_window_set_transient_for(GTK_WINDOW(dlg), GTK_WINDOW(g_wnd_assistant)); gtk_dialog_run(GTK_DIALOG(dlg)); gtk_widget_destroy(dlg); } free_and_ret: g_free(filename); } } static void on_btn_detail(GtkButton *button) { GtkWidget *pdd = problem_details_dialog_new(g_cd, g_wnd_assistant); gtk_dialog_run(GTK_DIALOG(pdd)); } /* [Del] key handling in item list */ static void delete_item(GtkTreeView *treeview) { GtkTreeSelection *selection = gtk_tree_view_get_selection(treeview); if (selection) { GtkTreeIter iter; GtkTreeModel *store = gtk_tree_view_get_model(treeview); if (gtk_tree_selection_get_selected(selection, &store, &iter) == TRUE) { GValue d_item_name = { 0 }; gtk_tree_model_get_value(store, &iter, DETAIL_COLUMN_NAME, &d_item_name); const char *item_name = g_value_get_string(&d_item_name); if (item_name) { struct problem_item *item = problem_data_get_item_or_NULL(g_cd, item_name); if (item->flags & CD_FLAG_ISEDITABLE) { // GtkTreePath *old_path = gtk_tree_model_get_path(store, &iter); struct dump_dir *dd = wizard_open_directory_for_writing(g_dump_dir_name); if (dd) { char *filename = concat_path_file(g_dump_dir_name, item_name); unlink(filename); free(filename); dd_close(dd); g_hash_table_remove(g_cd, item_name); gtk_list_store_remove(g_ls_details, &iter); } // /* Try to retain the same cursor position */ // sanitize_cursor(old_path); // gtk_tree_path_free(old_path); } } } } } static gint on_key_press_event_in_item_list(GtkTreeView *treeview, GdkEventKey *key, gpointer unused) { int k = key->keyval; if (k == GDK_KEY_Delete || k == GDK_KEY_KP_Delete) { delete_item(treeview); return TRUE; } return FALSE; } /* Initialization */ static void on_next_btn_cb(GtkWidget *btn, gpointer user_data) { gint current_page_no = gtk_notebook_get_current_page(g_assistant); gint next_page_no = select_next_page_no(current_page_no, NULL); /* if pageno is not change 'switch-page' signal is not emitted */ if (current_page_no == next_page_no) on_page_prepare(g_assistant, gtk_notebook_get_nth_page(g_assistant, next_page_no), NULL); else gtk_notebook_set_current_page(g_assistant, next_page_no); } static void add_pages(void) { g_builder = make_builder(); int i; int page_no = 0; for (i = 0; page_names[i] != NULL; i++) { GtkWidget *page = GTK_WIDGET(gtk_builder_get_object(g_builder, page_names[i])); pages[i].page_widget = page; pages[i].page_no = page_no++; gtk_notebook_append_page(g_assistant, page, gtk_label_new(pages[i].title)); log_notice("added page: %s", page_names[i]); } /* Set pointers to objects we might need to work with */ g_lbl_cd_reason = GTK_LABEL( gtk_builder_get_object(g_builder, "lbl_cd_reason")); g_box_events = GTK_BOX( gtk_builder_get_object(g_builder, "vb_events")); g_box_workflows = GTK_BOX( gtk_builder_get_object(g_builder, "vb_workflows")); g_lbl_event_log = GTK_LABEL( gtk_builder_get_object(g_builder, "lbl_event_log")); g_tv_event_log = GTK_TEXT_VIEW( gtk_builder_get_object(g_builder, "tv_event_log")); g_tv_comment = GTK_TEXT_VIEW( gtk_builder_get_object(g_builder, "tv_comment")); g_eb_comment = GTK_EVENT_BOX( gtk_builder_get_object(g_builder, "eb_comment")); g_cb_no_comment = GTK_CHECK_BUTTON( gtk_builder_get_object(g_builder, "cb_no_comment")); g_tv_details = GTK_TREE_VIEW( gtk_builder_get_object(g_builder, "tv_details")); g_tb_approve_bt = GTK_TOGGLE_BUTTON(gtk_builder_get_object(g_builder, "cb_approve_bt")); g_search_entry_bt = GTK_ENTRY( gtk_builder_get_object(g_builder, "entry_search_bt")); g_container_details1 = GTK_CONTAINER( gtk_builder_get_object(g_builder, "container_details1")); g_container_details2 = GTK_CONTAINER( gtk_builder_get_object(g_builder, "container_details2")); g_btn_add_file = GTK_BUTTON( gtk_builder_get_object(g_builder, "btn_add_file")); g_lbl_size = GTK_LABEL( gtk_builder_get_object(g_builder, "lbl_size")); g_notebook = GTK_NOTEBOOK( gtk_builder_get_object(g_builder, "notebook_edit")); g_ls_sensitive_list = GTK_LIST_STORE( gtk_builder_get_object(g_builder, "ls_sensitive_words")); g_tv_sensitive_list = GTK_TREE_VIEW( gtk_builder_get_object(g_builder, "tv_sensitive_words")); g_tv_sensitive_sel = GTK_TREE_SELECTION( gtk_builder_get_object(g_builder, "tv_sensitive_words_selection")); g_rb_forbidden_words = GTK_RADIO_BUTTON( gtk_builder_get_object(g_builder, "rb_forbidden_words")); g_rb_custom_search = GTK_RADIO_BUTTON( gtk_builder_get_object(g_builder, "rb_custom_search")); g_exp_search = GTK_EXPANDER( gtk_builder_get_object(g_builder, "expander_search")); g_spinner_event_log = GTK_SPINNER( gtk_builder_get_object(g_builder, "spinner_event_log")); g_img_process_fail = GTK_IMAGE( gtk_builder_get_object(g_builder, "img_process_fail")); g_btn_startcast = GTK_BUTTON( gtk_builder_get_object(g_builder, "btn_startcast")); g_exp_report_log = GTK_EXPANDER( gtk_builder_get_object(g_builder, "expand_report")); gtk_widget_set_no_show_all(GTK_WIDGET(g_spinner_event_log), true); gtk_widget_override_font(GTK_WIDGET(g_tv_event_log), g_monospace_font); fix_all_wrapped_labels(GTK_WIDGET(g_assistant)); g_signal_connect(g_cb_no_comment, "toggled", G_CALLBACK(on_no_comment_toggled), NULL); g_signal_connect(g_rb_forbidden_words, "toggled", G_CALLBACK(on_forbidden_words_toggled), NULL); g_signal_connect(g_rb_custom_search, "toggled", G_CALLBACK(on_custom_search_toggled), NULL); /* Set color of the comment evenbox */ GdkRGBA color; gdk_rgba_parse(&color, "#CC3333"); gtk_widget_override_color(GTK_WIDGET(g_eb_comment), GTK_STATE_FLAG_NORMAL, &color); g_signal_connect(g_tv_details, "key-press-event", G_CALLBACK(on_key_press_event_in_item_list), NULL); g_tv_sensitive_sel_hndlr = g_signal_connect(g_tv_sensitive_sel, "changed", G_CALLBACK(on_sensitive_word_selection_changed), NULL); } static void create_details_treeview(void) { GtkCellRenderer *renderer; GtkTreeViewColumn *column; renderer = gtk_cell_renderer_toggle_new(); column = gtk_tree_view_column_new_with_attributes( _("Include"), renderer, /* which "attr" of renderer to set from which COLUMN? (can be repeated) */ "active", DETAIL_COLUMN_CHECKBOX, NULL); g_tv_details_col_checkbox = column; gtk_tree_view_append_column(g_tv_details, column); /* This column has a handler */ g_signal_connect(renderer, "toggled", G_CALLBACK(g_tv_details_checkbox_toggled), NULL); renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes( _("Name"), renderer, "text", DETAIL_COLUMN_NAME, NULL); gtk_tree_view_append_column(g_tv_details, column); /* This column has a clickable header for sorting */ gtk_tree_view_column_set_sort_column_id(column, DETAIL_COLUMN_NAME); g_tv_details_renderer_value = renderer = gtk_cell_renderer_text_new(); g_signal_connect(renderer, "edited", G_CALLBACK(save_edited_one_liner), NULL); column = gtk_tree_view_column_new_with_attributes( _("Value"), renderer, "text", DETAIL_COLUMN_VALUE, NULL); gtk_tree_view_append_column(g_tv_details, column); /* This column has a clickable header for sorting */ gtk_tree_view_column_set_sort_column_id(column, DETAIL_COLUMN_VALUE); /* renderer = gtk_cell_renderer_text_new(); column = gtk_tree_view_column_new_with_attributes( _("Path"), renderer, "text", DETAIL_COLUMN_PATH, NULL); gtk_tree_view_append_column(g_tv_details, column); */ g_ls_details = gtk_list_store_new(DETAIL_NUM_COLUMNS, G_TYPE_BOOLEAN, G_TYPE_STRING, G_TYPE_STRING); gtk_tree_view_set_model(g_tv_details, GTK_TREE_MODEL(g_ls_details)); g_signal_connect(g_tv_details, "row-activated", G_CALLBACK(tv_details_row_activated), NULL); g_signal_connect(g_tv_details, "cursor-changed", G_CALLBACK(tv_details_cursor_changed), NULL); /* [Enter] on a row: * g_signal_connect(g_tv_details, "select-cursor-row", G_CALLBACK(tv_details_select_cursor_row), NULL); */ } static void init_page(page_obj_t *page, const char *name, const char *title) { page->name = name; page->title = title; } static void init_pages(void) { init_page(&pages[0], PAGE_SUMMARY , _("Problem description") ); init_page(&pages[1], PAGE_EVENT_SELECTOR , _("Select how to report this problem")); init_page(&pages[2], PAGE_EDIT_COMMENT,_("Provide additional information")); init_page(&pages[3], PAGE_EDIT_ELEMENTS , _("Review the data") ); init_page(&pages[4], PAGE_REVIEW_DATA , _("Confirm data to report")); init_page(&pages[5], PAGE_EVENT_PROGRESS , _("Processing") ); init_page(&pages[6], PAGE_EVENT_DONE , _("Processing done") ); //do we still need this? init_page(&pages[7], PAGE_NOT_SHOWN , "" ); } static void assistant_quit_cb(void *obj, void *data) { /* Suppress execution of consume_cmd_output() */ if (g_event_source_id != 0) { g_source_remove(g_event_source_id); g_event_source_id = 0; } cancel_event_run(); if (g_loaded_texts) { g_hash_table_destroy(g_loaded_texts); g_loaded_texts = NULL; } gtk_widget_destroy(GTK_WIDGET(g_wnd_assistant)); g_wnd_assistant = (void *)0xdeadbeaf; } static void on_btn_startcast(GtkWidget *btn, gpointer user_data) { const char *args[15]; args[0] = (char *) "fros"; args[1] = NULL; pid_t castapp = 0; castapp = fork_execv_on_steroids( EXECFLG_QUIET, (char **)args, NULL, /*env_vec:*/ NULL, g_dump_dir_name, /*uid (ignored):*/ 0 ); gtk_widget_hide(GTK_WIDGET(g_wnd_assistant)); /*flush all gui events before we start waitpid * otherwise the main window wouldn't hide */ while (gtk_events_pending()) gtk_main_iteration_do(false); int status; safe_waitpid(castapp, &status, 0); problem_data_reload_from_dump_dir(); update_gui_state_from_problem_data(0 /* don't update the selected event */); gtk_widget_show(GTK_WIDGET(g_wnd_assistant)); } static bool is_screencast_available() { const char *args[3]; args[0] = (char *) "fros"; args[1] = "--is-available"; args[2] = NULL; pid_t castapp = 0; castapp = fork_execv_on_steroids( EXECFLG_QUIET, (char **)args, NULL, /*env_vec:*/ NULL, g_dump_dir_name, /*uid (ignored):*/ 0 ); int status; safe_waitpid(castapp, &status, 0); /* 0 means that it's available */ return status == 0; } void create_assistant(GtkApplication *app, bool expert_mode) { g_loaded_texts = g_hash_table_new_full(g_str_hash, g_str_equal, g_free, NULL); g_expert_mode = expert_mode; g_monospace_font = pango_font_description_from_string("monospace"); g_assistant = GTK_NOTEBOOK(gtk_notebook_new()); /* Show tabs only in verbose expert mode * * It is safe to let users randomly switch tabs only in expert mode because * in all other modes a data for the selected page may not be ready and it * will probably cause unexpected behaviour like crash. */ gtk_notebook_set_show_tabs(g_assistant, (g_verbose != 0 && g_expert_mode)); g_btn_close = gtk_button_new_with_mnemonic(_("_Close")); gtk_button_set_image(GTK_BUTTON(g_btn_close), gtk_image_new_from_icon_name("window-close-symbolic", GTK_ICON_SIZE_BUTTON)); g_btn_stop = gtk_button_new_with_mnemonic(_("_Stop")); gtk_button_set_image(GTK_BUTTON(g_btn_stop), gtk_image_new_from_icon_name("process-stop-symbolic", GTK_ICON_SIZE_BUTTON)); gtk_widget_set_no_show_all(g_btn_stop, true); /* else gtk_widget_hide won't work */ g_btn_onfail = gtk_button_new_with_label(_("Upload for analysis")); gtk_button_set_image(GTK_BUTTON(g_btn_onfail), gtk_image_new_from_icon_name("go-up-symbolic", GTK_ICON_SIZE_BUTTON)); gtk_widget_set_no_show_all(g_btn_onfail, true); /* else gtk_widget_hide won't work */ g_btn_repeat = gtk_button_new_with_label(_("Repeat")); gtk_widget_set_no_show_all(g_btn_repeat, true); /* else gtk_widget_hide won't work */ g_btn_next = gtk_button_new_with_mnemonic(_("_Forward")); gtk_button_set_image(GTK_BUTTON(g_btn_next), gtk_image_new_from_icon_name("go-next-symbolic", GTK_ICON_SIZE_BUTTON)); gtk_widget_set_no_show_all(g_btn_next, true); /* else gtk_widget_hide won't work */ g_btn_detail = gtk_button_new_with_mnemonic(_("Details")); gtk_widget_set_no_show_all(g_btn_detail, true); /* else gtk_widget_hide won't work */ g_box_buttons = GTK_BOX(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0)); gtk_box_pack_start(g_box_buttons, g_btn_close, false, false, 5); gtk_box_pack_start(g_box_buttons, g_btn_stop, false, false, 5); gtk_box_pack_start(g_box_buttons, g_btn_onfail, false, false, 5); gtk_box_pack_start(g_box_buttons, g_btn_repeat, false, false, 5); /* Btns above are to the left, the rest are to the right: */ #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 13) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 13 && GTK_MICRO_VERSION < 5)) GtkWidget *w = gtk_alignment_new(0.0, 0.0, 1.0, 1.0); gtk_box_pack_start(g_box_buttons, w, true, true, 5); gtk_box_pack_start(g_box_buttons, g_btn_detail, false, false, 5); gtk_box_pack_start(g_box_buttons, g_btn_next, false, false, 5); #else gtk_widget_set_valign(GTK_WIDGET(g_btn_next), GTK_ALIGN_END); gtk_box_pack_end(g_box_buttons, g_btn_next, false, false, 5); gtk_box_pack_end(g_box_buttons, g_btn_detail, false, false, 5); #endif { /* Warnings area widget definition start */ g_box_warning_labels = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0)); gtk_widget_set_visible(GTK_WIDGET(g_box_warning_labels), TRUE); GtkBox *vbox = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0)); gtk_widget_set_visible(GTK_WIDGET(vbox), TRUE); gtk_box_pack_start(vbox, GTK_WIDGET(g_box_warning_labels), false, false, 5); GtkWidget *image = gtk_image_new_from_icon_name("dialog-warning-symbolic", GTK_ICON_SIZE_DIALOG); gtk_widget_set_visible(image, TRUE); g_widget_warnings_area = GTK_WIDGET(gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 0)); gtk_widget_set_visible(g_widget_warnings_area, FALSE); gtk_widget_set_no_show_all(g_widget_warnings_area, TRUE); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 13) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 13 && GTK_MICRO_VERSION < 5)) GtkWidget *alignment_left = gtk_alignment_new(0.5,0.5,1,1); gtk_widget_set_visible(alignment_left, TRUE); gtk_box_pack_start(GTK_BOX(g_widget_warnings_area), alignment_left, true, false, 0); #else gtk_widget_set_valign(GTK_WIDGET(image), GTK_ALIGN_CENTER); gtk_widget_set_valign(GTK_WIDGET(vbox), GTK_ALIGN_CENTER); #endif gtk_box_pack_start(GTK_BOX(g_widget_warnings_area), image, false, false, 5); gtk_box_pack_start(GTK_BOX(g_widget_warnings_area), GTK_WIDGET(vbox), false, false, 0); #if ((GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION < 13) || (GTK_MAJOR_VERSION == 3 && GTK_MINOR_VERSION == 13 && GTK_MICRO_VERSION < 5)) GtkWidget *alignment_right = gtk_alignment_new(0.5,0.5,1,1); gtk_widget_set_visible(alignment_right, TRUE); gtk_box_pack_start(GTK_BOX(g_widget_warnings_area), alignment_right, true, false, 0); #endif } /* Warnings area widget definition end */ g_box_assistant = GTK_BOX(gtk_box_new(GTK_ORIENTATION_VERTICAL, 0)); gtk_box_pack_start(g_box_assistant, GTK_WIDGET(g_assistant), true, true, 0); gtk_box_pack_start(g_box_assistant, GTK_WIDGET(g_widget_warnings_area), false, false, 0); gtk_box_pack_start(g_box_assistant, GTK_WIDGET(g_box_buttons), false, false, 5); gtk_widget_show_all(GTK_WIDGET(g_box_buttons)); gtk_widget_hide(g_btn_stop); gtk_widget_hide(g_btn_onfail); gtk_widget_hide(g_btn_repeat); gtk_widget_show(g_btn_next); g_wnd_assistant = GTK_WINDOW(gtk_application_window_new(app)); gtk_container_add(GTK_CONTAINER(g_wnd_assistant), GTK_WIDGET(g_box_assistant)); gtk_window_set_default_size(g_wnd_assistant, DEFAULT_WIDTH, DEFAULT_HEIGHT); /* set_default sets icon for every windows used in this app, so we don't * have to set the icon for those windows manually */ gtk_window_set_default_icon_name("abrt"); init_pages(); add_pages(); create_details_treeview(); ProblemDetailsWidget *details = problem_details_widget_new(g_cd); gtk_container_add(GTK_CONTAINER(g_container_details1), GTK_WIDGET(details)); g_signal_connect(g_btn_close, "clicked", G_CALLBACK(assistant_quit_cb), NULL); g_signal_connect(g_btn_stop, "clicked", G_CALLBACK(on_btn_cancel_event), NULL); g_signal_connect(g_btn_onfail, "clicked", G_CALLBACK(on_btn_failed_cb), NULL); g_signal_connect(g_btn_repeat, "clicked", G_CALLBACK(on_btn_repeat_cb), NULL); g_signal_connect(g_btn_next, "clicked", G_CALLBACK(on_next_btn_cb), NULL); g_signal_connect(g_wnd_assistant, "destroy", G_CALLBACK(assistant_quit_cb), NULL); g_signal_connect(g_assistant, "switch-page", G_CALLBACK(on_page_prepare), NULL); g_signal_connect(g_tb_approve_bt, "toggled", G_CALLBACK(on_bt_approve_toggle), NULL); g_signal_connect(gtk_text_view_get_buffer(g_tv_comment), "changed", G_CALLBACK(on_comment_changed), NULL); g_signal_connect(g_btn_add_file, "clicked", G_CALLBACK(on_btn_add_file), NULL); g_signal_connect(g_btn_detail, "clicked", G_CALLBACK(on_btn_detail), NULL); if (is_screencast_available()) { /* we need to override the activate-link handler, because we use * the link button instead of normal button and if we wouldn't override it * gtk would try to run it's defualt action and open the associated URI * but since the URI is empty it would complain about it... */ g_signal_connect(g_btn_startcast, "activate-link", G_CALLBACK(on_btn_startcast), NULL); } else { gtk_widget_set_sensitive(GTK_WIDGET(g_btn_startcast), false); gtk_widget_set_tooltip_markup(GTK_WIDGET(g_btn_startcast), _("In order to enable the built-in screencasting " "functionality the package fros-recordmydesktop has to be installed. " "Please run the following command if you want to install it." "\n\n" "<b>su -c \"yum install fros-recordmydesktop\"</b>" )); } g_signal_connect(g_search_entry_bt, "changed", G_CALLBACK(search_timeout), NULL); g_signal_connect (g_tv_event_log, "key-press-event", G_CALLBACK (key_press_event), NULL); g_signal_connect (g_tv_event_log, "event-after", G_CALLBACK (event_after), NULL); g_signal_connect (g_tv_event_log, "motion-notify-event", G_CALLBACK (motion_notify_event), NULL); g_signal_connect (g_tv_event_log, "visibility-notify-event", G_CALLBACK (visibility_notify_event), NULL); g_signal_connect (gtk_text_view_get_buffer(g_tv_event_log), "changed", G_CALLBACK (on_log_changed), NULL); hand_cursor = gdk_cursor_new (GDK_HAND2); regular_cursor = gdk_cursor_new (GDK_XTERM); /* switch to right starting page */ on_page_prepare(g_assistant, gtk_notebook_get_nth_page(g_assistant, 0), NULL); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1674_0
crossvul-cpp_data_good_5130_0
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> */ /* * Changes: * Pedro Roque : Fast Retransmit/Recovery. * Two receive queues. * Retransmit queue handled by TCP. * Better retransmit timer handling. * New congestion avoidance. * Header prediction. * Variable renaming. * * Eric : Fast Retransmit. * Randy Scott : MSS option defines. * Eric Schenk : Fixes to slow start algorithm. * Eric Schenk : Yet another double ACK bug. * Eric Schenk : Delayed ACK bug fixes. * Eric Schenk : Floyd style fast retrans war avoidance. * David S. Miller : Don't allow zero congestion window. * Eric Schenk : Fix retransmitter so that it sends * next packet on ack of previous packet. * Andi Kleen : Moved open_request checking here * and process RSTs for open_requests. * Andi Kleen : Better prune_queue, and other fixes. * Andrey Savochkin: Fix RTT measurements in the presence of * timestamps. * Andrey Savochkin: Check sequence numbers correctly when * removing SACKs due to in sequence incoming * data segments. * Andi Kleen: Make sure we never ack data there is not * enough room for. Also make this condition * a fatal error if it might still happen. * Andi Kleen: Add tcp_measure_rcv_mss to make * connections with MSS<min(MTU,ann. MSS) * work without delayed acks. * Andi Kleen: Process packets with PSH set in the * fast path. * J Hadi Salim: ECN support * Andrei Gurtov, * Pasi Sarolahti, * Panu Kuhlberg: Experimental audit of TCP (re)transmission * engine. Lots of bugs are found. * Pasi Sarolahti: F-RTO for dealing with spurious RTOs */ #define pr_fmt(fmt) "TCP: " fmt #include <linux/mm.h> #include <linux/slab.h> #include <linux/module.h> #include <linux/sysctl.h> #include <linux/kernel.h> #include <linux/prefetch.h> #include <net/dst.h> #include <net/tcp.h> #include <net/inet_common.h> #include <linux/ipsec.h> #include <asm/unaligned.h> #include <linux/errqueue.h> int sysctl_tcp_timestamps __read_mostly = 1; int sysctl_tcp_window_scaling __read_mostly = 1; int sysctl_tcp_sack __read_mostly = 1; int sysctl_tcp_fack __read_mostly = 1; int sysctl_tcp_max_reordering __read_mostly = 300; int sysctl_tcp_dsack __read_mostly = 1; int sysctl_tcp_app_win __read_mostly = 31; int sysctl_tcp_adv_win_scale __read_mostly = 1; EXPORT_SYMBOL(sysctl_tcp_adv_win_scale); /* rfc5961 challenge ack rate limiting */ int sysctl_tcp_challenge_ack_limit = 1000; int sysctl_tcp_stdurg __read_mostly; int sysctl_tcp_rfc1337 __read_mostly; int sysctl_tcp_max_orphans __read_mostly = NR_FILE; int sysctl_tcp_frto __read_mostly = 2; int sysctl_tcp_min_rtt_wlen __read_mostly = 300; int sysctl_tcp_thin_dupack __read_mostly; int sysctl_tcp_moderate_rcvbuf __read_mostly = 1; int sysctl_tcp_early_retrans __read_mostly = 3; int sysctl_tcp_invalid_ratelimit __read_mostly = HZ/2; #define FLAG_DATA 0x01 /* Incoming frame contained data. */ #define FLAG_WIN_UPDATE 0x02 /* Incoming ACK was a window update. */ #define FLAG_DATA_ACKED 0x04 /* This ACK acknowledged new data. */ #define FLAG_RETRANS_DATA_ACKED 0x08 /* "" "" some of which was retransmitted. */ #define FLAG_SYN_ACKED 0x10 /* This ACK acknowledged SYN. */ #define FLAG_DATA_SACKED 0x20 /* New SACK. */ #define FLAG_ECE 0x40 /* ECE in this ACK */ #define FLAG_LOST_RETRANS 0x80 /* This ACK marks some retransmission lost */ #define FLAG_SLOWPATH 0x100 /* Do not skip RFC checks for window update.*/ #define FLAG_ORIG_SACK_ACKED 0x200 /* Never retransmitted data are (s)acked */ #define FLAG_SND_UNA_ADVANCED 0x400 /* Snd_una was changed (!= FLAG_DATA_ACKED) */ #define FLAG_DSACKING_ACK 0x800 /* SACK blocks contained D-SACK info */ #define FLAG_SACK_RENEGING 0x2000 /* snd_una advanced to a sacked seq */ #define FLAG_UPDATE_TS_RECENT 0x4000 /* tcp_replace_ts_recent() */ #define FLAG_ACKED (FLAG_DATA_ACKED|FLAG_SYN_ACKED) #define FLAG_NOT_DUP (FLAG_DATA|FLAG_WIN_UPDATE|FLAG_ACKED) #define FLAG_CA_ALERT (FLAG_DATA_SACKED|FLAG_ECE) #define FLAG_FORWARD_PROGRESS (FLAG_ACKED|FLAG_DATA_SACKED) #define TCP_REMNANT (TCP_FLAG_FIN|TCP_FLAG_URG|TCP_FLAG_SYN|TCP_FLAG_PSH) #define TCP_HP_BITS (~(TCP_RESERVED_BITS|TCP_FLAG_PSH)) #define REXMIT_NONE 0 /* no loss recovery to do */ #define REXMIT_LOST 1 /* retransmit packets marked lost */ #define REXMIT_NEW 2 /* FRTO-style transmit of unsent/new packets */ /* Adapt the MSS value used to make delayed ack decision to the * real world. */ static void tcp_measure_rcv_mss(struct sock *sk, const struct sk_buff *skb) { struct inet_connection_sock *icsk = inet_csk(sk); const unsigned int lss = icsk->icsk_ack.last_seg_size; unsigned int len; icsk->icsk_ack.last_seg_size = 0; /* skb->len may jitter because of SACKs, even if peer * sends good full-sized frames. */ len = skb_shinfo(skb)->gso_size ? : skb->len; if (len >= icsk->icsk_ack.rcv_mss) { icsk->icsk_ack.rcv_mss = len; } else { /* Otherwise, we make more careful check taking into account, * that SACKs block is variable. * * "len" is invariant segment length, including TCP header. */ len += skb->data - skb_transport_header(skb); if (len >= TCP_MSS_DEFAULT + sizeof(struct tcphdr) || /* If PSH is not set, packet should be * full sized, provided peer TCP is not badly broken. * This observation (if it is correct 8)) allows * to handle super-low mtu links fairly. */ (len >= TCP_MIN_MSS + sizeof(struct tcphdr) && !(tcp_flag_word(tcp_hdr(skb)) & TCP_REMNANT))) { /* Subtract also invariant (if peer is RFC compliant), * tcp header plus fixed timestamp option length. * Resulting "len" is MSS free of SACK jitter. */ len -= tcp_sk(sk)->tcp_header_len; icsk->icsk_ack.last_seg_size = len; if (len == lss) { icsk->icsk_ack.rcv_mss = len; return; } } if (icsk->icsk_ack.pending & ICSK_ACK_PUSHED) icsk->icsk_ack.pending |= ICSK_ACK_PUSHED2; icsk->icsk_ack.pending |= ICSK_ACK_PUSHED; } } static void tcp_incr_quickack(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); unsigned int quickacks = tcp_sk(sk)->rcv_wnd / (2 * icsk->icsk_ack.rcv_mss); if (quickacks == 0) quickacks = 2; if (quickacks > icsk->icsk_ack.quick) icsk->icsk_ack.quick = min(quickacks, TCP_MAX_QUICKACKS); } static void tcp_enter_quickack_mode(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); tcp_incr_quickack(sk); icsk->icsk_ack.pingpong = 0; icsk->icsk_ack.ato = TCP_ATO_MIN; } /* Send ACKs quickly, if "quick" count is not exhausted * and the session is not interactive. */ static bool tcp_in_quickack_mode(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); const struct dst_entry *dst = __sk_dst_get(sk); return (dst && dst_metric(dst, RTAX_QUICKACK)) || (icsk->icsk_ack.quick && !icsk->icsk_ack.pingpong); } static void tcp_ecn_queue_cwr(struct tcp_sock *tp) { if (tp->ecn_flags & TCP_ECN_OK) tp->ecn_flags |= TCP_ECN_QUEUE_CWR; } static void tcp_ecn_accept_cwr(struct tcp_sock *tp, const struct sk_buff *skb) { if (tcp_hdr(skb)->cwr) tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR; } static void tcp_ecn_withdraw_cwr(struct tcp_sock *tp) { tp->ecn_flags &= ~TCP_ECN_DEMAND_CWR; } static void __tcp_ecn_check_ce(struct tcp_sock *tp, const struct sk_buff *skb) { switch (TCP_SKB_CB(skb)->ip_dsfield & INET_ECN_MASK) { case INET_ECN_NOT_ECT: /* Funny extension: if ECT is not set on a segment, * and we already seen ECT on a previous segment, * it is probably a retransmit. */ if (tp->ecn_flags & TCP_ECN_SEEN) tcp_enter_quickack_mode((struct sock *)tp); break; case INET_ECN_CE: if (tcp_ca_needs_ecn((struct sock *)tp)) tcp_ca_event((struct sock *)tp, CA_EVENT_ECN_IS_CE); if (!(tp->ecn_flags & TCP_ECN_DEMAND_CWR)) { /* Better not delay acks, sender can have a very low cwnd */ tcp_enter_quickack_mode((struct sock *)tp); tp->ecn_flags |= TCP_ECN_DEMAND_CWR; } tp->ecn_flags |= TCP_ECN_SEEN; break; default: if (tcp_ca_needs_ecn((struct sock *)tp)) tcp_ca_event((struct sock *)tp, CA_EVENT_ECN_NO_CE); tp->ecn_flags |= TCP_ECN_SEEN; break; } } static void tcp_ecn_check_ce(struct tcp_sock *tp, const struct sk_buff *skb) { if (tp->ecn_flags & TCP_ECN_OK) __tcp_ecn_check_ce(tp, skb); } static void tcp_ecn_rcv_synack(struct tcp_sock *tp, const struct tcphdr *th) { if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || th->cwr)) tp->ecn_flags &= ~TCP_ECN_OK; } static void tcp_ecn_rcv_syn(struct tcp_sock *tp, const struct tcphdr *th) { if ((tp->ecn_flags & TCP_ECN_OK) && (!th->ece || !th->cwr)) tp->ecn_flags &= ~TCP_ECN_OK; } static bool tcp_ecn_rcv_ecn_echo(const struct tcp_sock *tp, const struct tcphdr *th) { if (th->ece && !th->syn && (tp->ecn_flags & TCP_ECN_OK)) return true; return false; } /* Buffer size and advertised window tuning. * * 1. Tuning sk->sk_sndbuf, when connection enters established state. */ static void tcp_sndbuf_expand(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); int sndmem, per_mss; u32 nr_segs; /* Worst case is non GSO/TSO : each frame consumes one skb * and skb->head is kmalloced using power of two area of memory */ per_mss = max_t(u32, tp->rx_opt.mss_clamp, tp->mss_cache) + MAX_TCP_HEADER + SKB_DATA_ALIGN(sizeof(struct skb_shared_info)); per_mss = roundup_pow_of_two(per_mss) + SKB_DATA_ALIGN(sizeof(struct sk_buff)); nr_segs = max_t(u32, TCP_INIT_CWND, tp->snd_cwnd); nr_segs = max_t(u32, nr_segs, tp->reordering + 1); /* Fast Recovery (RFC 5681 3.2) : * Cubic needs 1.7 factor, rounded to 2 to include * extra cushion (application might react slowly to POLLOUT) */ sndmem = 2 * nr_segs * per_mss; if (sk->sk_sndbuf < sndmem) sk->sk_sndbuf = min(sndmem, sysctl_tcp_wmem[2]); } /* 2. Tuning advertised window (window_clamp, rcv_ssthresh) * * All tcp_full_space() is split to two parts: "network" buffer, allocated * forward and advertised in receiver window (tp->rcv_wnd) and * "application buffer", required to isolate scheduling/application * latencies from network. * window_clamp is maximal advertised window. It can be less than * tcp_full_space(), in this case tcp_full_space() - window_clamp * is reserved for "application" buffer. The less window_clamp is * the smoother our behaviour from viewpoint of network, but the lower * throughput and the higher sensitivity of the connection to losses. 8) * * rcv_ssthresh is more strict window_clamp used at "slow start" * phase to predict further behaviour of this connection. * It is used for two goals: * - to enforce header prediction at sender, even when application * requires some significant "application buffer". It is check #1. * - to prevent pruning of receive queue because of misprediction * of receiver window. Check #2. * * The scheme does not work when sender sends good segments opening * window and then starts to feed us spaghetti. But it should work * in common situations. Otherwise, we have to rely on queue collapsing. */ /* Slow part of check#2. */ static int __tcp_grow_window(const struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Optimize this! */ int truesize = tcp_win_from_space(skb->truesize) >> 1; int window = tcp_win_from_space(sysctl_tcp_rmem[2]) >> 1; while (tp->rcv_ssthresh <= window) { if (truesize <= skb->len) return 2 * inet_csk(sk)->icsk_ack.rcv_mss; truesize >>= 1; window >>= 1; } return 0; } static void tcp_grow_window(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Check #1 */ if (tp->rcv_ssthresh < tp->window_clamp && (int)tp->rcv_ssthresh < tcp_space(sk) && !tcp_under_memory_pressure(sk)) { int incr; /* Check #2. Increase window, if skb with such overhead * will fit to rcvbuf in future. */ if (tcp_win_from_space(skb->truesize) <= skb->len) incr = 2 * tp->advmss; else incr = __tcp_grow_window(sk, skb); if (incr) { incr = max_t(int, incr, 2 * skb->len); tp->rcv_ssthresh = min(tp->rcv_ssthresh + incr, tp->window_clamp); inet_csk(sk)->icsk_ack.quick |= 1; } } } /* 3. Tuning rcvbuf, when connection enters established state. */ static void tcp_fixup_rcvbuf(struct sock *sk) { u32 mss = tcp_sk(sk)->advmss; int rcvmem; rcvmem = 2 * SKB_TRUESIZE(mss + MAX_TCP_HEADER) * tcp_default_init_rwnd(mss); /* Dynamic Right Sizing (DRS) has 2 to 3 RTT latency * Allow enough cushion so that sender is not limited by our window */ if (sysctl_tcp_moderate_rcvbuf) rcvmem <<= 2; if (sk->sk_rcvbuf < rcvmem) sk->sk_rcvbuf = min(rcvmem, sysctl_tcp_rmem[2]); } /* 4. Try to fixup all. It is made immediately after connection enters * established state. */ void tcp_init_buffer_space(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int maxwin; if (!(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) tcp_fixup_rcvbuf(sk); if (!(sk->sk_userlocks & SOCK_SNDBUF_LOCK)) tcp_sndbuf_expand(sk); tp->rcvq_space.space = tp->rcv_wnd; tp->rcvq_space.time = tcp_time_stamp; tp->rcvq_space.seq = tp->copied_seq; maxwin = tcp_full_space(sk); if (tp->window_clamp >= maxwin) { tp->window_clamp = maxwin; if (sysctl_tcp_app_win && maxwin > 4 * tp->advmss) tp->window_clamp = max(maxwin - (maxwin >> sysctl_tcp_app_win), 4 * tp->advmss); } /* Force reservation of one segment. */ if (sysctl_tcp_app_win && tp->window_clamp > 2 * tp->advmss && tp->window_clamp + tp->advmss > maxwin) tp->window_clamp = max(2 * tp->advmss, maxwin - tp->advmss); tp->rcv_ssthresh = min(tp->rcv_ssthresh, tp->window_clamp); tp->snd_cwnd_stamp = tcp_time_stamp; } /* 5. Recalculate window clamp after socket hit its memory bounds. */ static void tcp_clamp_window(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_ack.quick = 0; if (sk->sk_rcvbuf < sysctl_tcp_rmem[2] && !(sk->sk_userlocks & SOCK_RCVBUF_LOCK) && !tcp_under_memory_pressure(sk) && sk_memory_allocated(sk) < sk_prot_mem_limits(sk, 0)) { sk->sk_rcvbuf = min(atomic_read(&sk->sk_rmem_alloc), sysctl_tcp_rmem[2]); } if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf) tp->rcv_ssthresh = min(tp->window_clamp, 2U * tp->advmss); } /* Initialize RCV_MSS value. * RCV_MSS is an our guess about MSS used by the peer. * We haven't any direct information about the MSS. * It's better to underestimate the RCV_MSS rather than overestimate. * Overestimations make us ACKing less frequently than needed. * Underestimations are more easy to detect and fix by tcp_measure_rcv_mss(). */ void tcp_initialize_rcv_mss(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); unsigned int hint = min_t(unsigned int, tp->advmss, tp->mss_cache); hint = min(hint, tp->rcv_wnd / 2); hint = min(hint, TCP_MSS_DEFAULT); hint = max(hint, TCP_MIN_MSS); inet_csk(sk)->icsk_ack.rcv_mss = hint; } EXPORT_SYMBOL(tcp_initialize_rcv_mss); /* Receiver "autotuning" code. * * The algorithm for RTT estimation w/o timestamps is based on * Dynamic Right-Sizing (DRS) by Wu Feng and Mike Fisk of LANL. * <http://public.lanl.gov/radiant/pubs.html#DRS> * * More detail on this code can be found at * <http://staff.psc.edu/jheffner/>, * though this reference is out of date. A new paper * is pending. */ static void tcp_rcv_rtt_update(struct tcp_sock *tp, u32 sample, int win_dep) { u32 new_sample = tp->rcv_rtt_est.rtt; long m = sample; if (m == 0) m = 1; if (new_sample != 0) { /* If we sample in larger samples in the non-timestamp * case, we could grossly overestimate the RTT especially * with chatty applications or bulk transfer apps which * are stalled on filesystem I/O. * * Also, since we are only going for a minimum in the * non-timestamp case, we do not smooth things out * else with timestamps disabled convergence takes too * long. */ if (!win_dep) { m -= (new_sample >> 3); new_sample += m; } else { m <<= 3; if (m < new_sample) new_sample = m; } } else { /* No previous measure. */ new_sample = m << 3; } if (tp->rcv_rtt_est.rtt != new_sample) tp->rcv_rtt_est.rtt = new_sample; } static inline void tcp_rcv_rtt_measure(struct tcp_sock *tp) { if (tp->rcv_rtt_est.time == 0) goto new_measure; if (before(tp->rcv_nxt, tp->rcv_rtt_est.seq)) return; tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rcv_rtt_est.time, 1); new_measure: tp->rcv_rtt_est.seq = tp->rcv_nxt + tp->rcv_wnd; tp->rcv_rtt_est.time = tcp_time_stamp; } static inline void tcp_rcv_rtt_measure_ts(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); if (tp->rx_opt.rcv_tsecr && (TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq >= inet_csk(sk)->icsk_ack.rcv_mss)) tcp_rcv_rtt_update(tp, tcp_time_stamp - tp->rx_opt.rcv_tsecr, 0); } /* * This function should be called every time data is copied to user space. * It calculates the appropriate TCP receive buffer space. */ void tcp_rcv_space_adjust(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int time; int copied; time = tcp_time_stamp - tp->rcvq_space.time; if (time < (tp->rcv_rtt_est.rtt >> 3) || tp->rcv_rtt_est.rtt == 0) return; /* Number of bytes copied to user in last RTT */ copied = tp->copied_seq - tp->rcvq_space.seq; if (copied <= tp->rcvq_space.space) goto new_measure; /* A bit of theory : * copied = bytes received in previous RTT, our base window * To cope with packet losses, we need a 2x factor * To cope with slow start, and sender growing its cwin by 100 % * every RTT, we need a 4x factor, because the ACK we are sending * now is for the next RTT, not the current one : * <prev RTT . ><current RTT .. ><next RTT .... > */ if (sysctl_tcp_moderate_rcvbuf && !(sk->sk_userlocks & SOCK_RCVBUF_LOCK)) { int rcvwin, rcvmem, rcvbuf; /* minimal window to cope with packet losses, assuming * steady state. Add some cushion because of small variations. */ rcvwin = (copied << 1) + 16 * tp->advmss; /* If rate increased by 25%, * assume slow start, rcvwin = 3 * copied * If rate increased by 50%, * assume sender can use 2x growth, rcvwin = 4 * copied */ if (copied >= tp->rcvq_space.space + (tp->rcvq_space.space >> 2)) { if (copied >= tp->rcvq_space.space + (tp->rcvq_space.space >> 1)) rcvwin <<= 1; else rcvwin += (rcvwin >> 1); } rcvmem = SKB_TRUESIZE(tp->advmss + MAX_TCP_HEADER); while (tcp_win_from_space(rcvmem) < tp->advmss) rcvmem += 128; rcvbuf = min(rcvwin / tp->advmss * rcvmem, sysctl_tcp_rmem[2]); if (rcvbuf > sk->sk_rcvbuf) { sk->sk_rcvbuf = rcvbuf; /* Make the window clamp follow along. */ tp->window_clamp = rcvwin; } } tp->rcvq_space.space = copied; new_measure: tp->rcvq_space.seq = tp->copied_seq; tp->rcvq_space.time = tcp_time_stamp; } /* There is something which you must keep in mind when you analyze the * behavior of the tp->ato delayed ack timeout interval. When a * connection starts up, we want to ack as quickly as possible. The * problem is that "good" TCP's do slow start at the beginning of data * transmission. The means that until we send the first few ACK's the * sender will sit on his end and only queue most of his data, because * he can only send snd_cwnd unacked packets at any given time. For * each ACK we send, he increments snd_cwnd and transmits more of his * queue. -DaveM */ static void tcp_event_data_recv(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); u32 now; inet_csk_schedule_ack(sk); tcp_measure_rcv_mss(sk, skb); tcp_rcv_rtt_measure(tp); now = tcp_time_stamp; if (!icsk->icsk_ack.ato) { /* The _first_ data packet received, initialize * delayed ACK engine. */ tcp_incr_quickack(sk); icsk->icsk_ack.ato = TCP_ATO_MIN; } else { int m = now - icsk->icsk_ack.lrcvtime; if (m <= TCP_ATO_MIN / 2) { /* The fastest case is the first. */ icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + TCP_ATO_MIN / 2; } else if (m < icsk->icsk_ack.ato) { icsk->icsk_ack.ato = (icsk->icsk_ack.ato >> 1) + m; if (icsk->icsk_ack.ato > icsk->icsk_rto) icsk->icsk_ack.ato = icsk->icsk_rto; } else if (m > icsk->icsk_rto) { /* Too long gap. Apparently sender failed to * restart window, so that we send ACKs quickly. */ tcp_incr_quickack(sk); sk_mem_reclaim(sk); } } icsk->icsk_ack.lrcvtime = now; tcp_ecn_check_ce(tp, skb); if (skb->len >= 128) tcp_grow_window(sk, skb); } /* Called to compute a smoothed rtt estimate. The data fed to this * routine either comes from timestamps, or from segments that were * known _not_ to have been retransmitted [see Karn/Partridge * Proceedings SIGCOMM 87]. The algorithm is from the SIGCOMM 88 * piece by Van Jacobson. * NOTE: the next three routines used to be one big routine. * To save cycles in the RFC 1323 implementation it was better to break * it up into three procedures. -- erics */ static void tcp_rtt_estimator(struct sock *sk, long mrtt_us) { struct tcp_sock *tp = tcp_sk(sk); long m = mrtt_us; /* RTT */ u32 srtt = tp->srtt_us; /* The following amusing code comes from Jacobson's * article in SIGCOMM '88. Note that rtt and mdev * are scaled versions of rtt and mean deviation. * This is designed to be as fast as possible * m stands for "measurement". * * On a 1990 paper the rto value is changed to: * RTO = rtt + 4 * mdev * * Funny. This algorithm seems to be very broken. * These formulae increase RTO, when it should be decreased, increase * too slowly, when it should be increased quickly, decrease too quickly * etc. I guess in BSD RTO takes ONE value, so that it is absolutely * does not matter how to _calculate_ it. Seems, it was trap * that VJ failed to avoid. 8) */ if (srtt != 0) { m -= (srtt >> 3); /* m is now error in rtt est */ srtt += m; /* rtt = 7/8 rtt + 1/8 new */ if (m < 0) { m = -m; /* m is now abs(error) */ m -= (tp->mdev_us >> 2); /* similar update on mdev */ /* This is similar to one of Eifel findings. * Eifel blocks mdev updates when rtt decreases. * This solution is a bit different: we use finer gain * for mdev in this case (alpha*beta). * Like Eifel it also prevents growth of rto, * but also it limits too fast rto decreases, * happening in pure Eifel. */ if (m > 0) m >>= 3; } else { m -= (tp->mdev_us >> 2); /* similar update on mdev */ } tp->mdev_us += m; /* mdev = 3/4 mdev + 1/4 new */ if (tp->mdev_us > tp->mdev_max_us) { tp->mdev_max_us = tp->mdev_us; if (tp->mdev_max_us > tp->rttvar_us) tp->rttvar_us = tp->mdev_max_us; } if (after(tp->snd_una, tp->rtt_seq)) { if (tp->mdev_max_us < tp->rttvar_us) tp->rttvar_us -= (tp->rttvar_us - tp->mdev_max_us) >> 2; tp->rtt_seq = tp->snd_nxt; tp->mdev_max_us = tcp_rto_min_us(sk); } } else { /* no previous measure. */ srtt = m << 3; /* take the measured time to be rtt */ tp->mdev_us = m << 1; /* make sure rto = 3*rtt */ tp->rttvar_us = max(tp->mdev_us, tcp_rto_min_us(sk)); tp->mdev_max_us = tp->rttvar_us; tp->rtt_seq = tp->snd_nxt; } tp->srtt_us = max(1U, srtt); } /* Set the sk_pacing_rate to allow proper sizing of TSO packets. * Note: TCP stack does not yet implement pacing. * FQ packet scheduler can be used to implement cheap but effective * TCP pacing, to smooth the burst on large writes when packets * in flight is significantly lower than cwnd (or rwin) */ int sysctl_tcp_pacing_ss_ratio __read_mostly = 200; int sysctl_tcp_pacing_ca_ratio __read_mostly = 120; static void tcp_update_pacing_rate(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); u64 rate; /* set sk_pacing_rate to 200 % of current rate (mss * cwnd / srtt) */ rate = (u64)tp->mss_cache * ((USEC_PER_SEC / 100) << 3); /* current rate is (cwnd * mss) / srtt * In Slow Start [1], set sk_pacing_rate to 200 % the current rate. * In Congestion Avoidance phase, set it to 120 % the current rate. * * [1] : Normal Slow Start condition is (tp->snd_cwnd < tp->snd_ssthresh) * If snd_cwnd >= (tp->snd_ssthresh / 2), we are approaching * end of slow start and should slow down. */ if (tp->snd_cwnd < tp->snd_ssthresh / 2) rate *= sysctl_tcp_pacing_ss_ratio; else rate *= sysctl_tcp_pacing_ca_ratio; rate *= max(tp->snd_cwnd, tp->packets_out); if (likely(tp->srtt_us)) do_div(rate, tp->srtt_us); /* ACCESS_ONCE() is needed because sch_fq fetches sk_pacing_rate * without any lock. We want to make sure compiler wont store * intermediate values in this location. */ ACCESS_ONCE(sk->sk_pacing_rate) = min_t(u64, rate, sk->sk_max_pacing_rate); } /* Calculate rto without backoff. This is the second half of Van Jacobson's * routine referred to above. */ static void tcp_set_rto(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); /* Old crap is replaced with new one. 8) * * More seriously: * 1. If rtt variance happened to be less 50msec, it is hallucination. * It cannot be less due to utterly erratic ACK generation made * at least by solaris and freebsd. "Erratic ACKs" has _nothing_ * to do with delayed acks, because at cwnd>2 true delack timeout * is invisible. Actually, Linux-2.4 also generates erratic * ACKs in some circumstances. */ inet_csk(sk)->icsk_rto = __tcp_set_rto(tp); /* 2. Fixups made earlier cannot be right. * If we do not estimate RTO correctly without them, * all the algo is pure shit and should be replaced * with correct one. It is exactly, which we pretend to do. */ /* NOTE: clamping at TCP_RTO_MIN is not required, current algo * guarantees that rto is higher. */ tcp_bound_rto(sk); } __u32 tcp_init_cwnd(const struct tcp_sock *tp, const struct dst_entry *dst) { __u32 cwnd = (dst ? dst_metric(dst, RTAX_INITCWND) : 0); if (!cwnd) cwnd = TCP_INIT_CWND; return min_t(__u32, cwnd, tp->snd_cwnd_clamp); } /* * Packet counting of FACK is based on in-order assumptions, therefore TCP * disables it when reordering is detected */ void tcp_disable_fack(struct tcp_sock *tp) { /* RFC3517 uses different metric in lost marker => reset on change */ if (tcp_is_fack(tp)) tp->lost_skb_hint = NULL; tp->rx_opt.sack_ok &= ~TCP_FACK_ENABLED; } /* Take a notice that peer is sending D-SACKs */ static void tcp_dsack_seen(struct tcp_sock *tp) { tp->rx_opt.sack_ok |= TCP_DSACK_SEEN; } static void tcp_update_reordering(struct sock *sk, const int metric, const int ts) { struct tcp_sock *tp = tcp_sk(sk); if (metric > tp->reordering) { int mib_idx; tp->reordering = min(sysctl_tcp_max_reordering, metric); /* This exciting event is worth to be remembered. 8) */ if (ts) mib_idx = LINUX_MIB_TCPTSREORDER; else if (tcp_is_reno(tp)) mib_idx = LINUX_MIB_TCPRENOREORDER; else if (tcp_is_fack(tp)) mib_idx = LINUX_MIB_TCPFACKREORDER; else mib_idx = LINUX_MIB_TCPSACKREORDER; NET_INC_STATS(sock_net(sk), mib_idx); #if FASTRETRANS_DEBUG > 1 pr_debug("Disorder%d %d %u f%u s%u rr%d\n", tp->rx_opt.sack_ok, inet_csk(sk)->icsk_ca_state, tp->reordering, tp->fackets_out, tp->sacked_out, tp->undo_marker ? tp->undo_retrans : 0); #endif tcp_disable_fack(tp); } if (metric > 0) tcp_disable_early_retrans(tp); tp->rack.reord = 1; } /* This must be called before lost_out is incremented */ static void tcp_verify_retransmit_hint(struct tcp_sock *tp, struct sk_buff *skb) { if (!tp->retransmit_skb_hint || before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(tp->retransmit_skb_hint)->seq)) tp->retransmit_skb_hint = skb; if (!tp->lost_out || after(TCP_SKB_CB(skb)->end_seq, tp->retransmit_high)) tp->retransmit_high = TCP_SKB_CB(skb)->end_seq; } static void tcp_skb_mark_lost(struct tcp_sock *tp, struct sk_buff *skb) { if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) { tcp_verify_retransmit_hint(tp, skb); tp->lost_out += tcp_skb_pcount(skb); TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; } } void tcp_skb_mark_lost_uncond_verify(struct tcp_sock *tp, struct sk_buff *skb) { tcp_verify_retransmit_hint(tp, skb); if (!(TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_ACKED))) { tp->lost_out += tcp_skb_pcount(skb); TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; } } /* This procedure tags the retransmission queue when SACKs arrive. * * We have three tag bits: SACKED(S), RETRANS(R) and LOST(L). * Packets in queue with these bits set are counted in variables * sacked_out, retrans_out and lost_out, correspondingly. * * Valid combinations are: * Tag InFlight Description * 0 1 - orig segment is in flight. * S 0 - nothing flies, orig reached receiver. * L 0 - nothing flies, orig lost by net. * R 2 - both orig and retransmit are in flight. * L|R 1 - orig is lost, retransmit is in flight. * S|R 1 - orig reached receiver, retrans is still in flight. * (L|S|R is logically valid, it could occur when L|R is sacked, * but it is equivalent to plain S and code short-curcuits it to S. * L|S is logically invalid, it would mean -1 packet in flight 8)) * * These 6 states form finite state machine, controlled by the following events: * 1. New ACK (+SACK) arrives. (tcp_sacktag_write_queue()) * 2. Retransmission. (tcp_retransmit_skb(), tcp_xmit_retransmit_queue()) * 3. Loss detection event of two flavors: * A. Scoreboard estimator decided the packet is lost. * A'. Reno "three dupacks" marks head of queue lost. * A''. Its FACK modification, head until snd.fack is lost. * B. SACK arrives sacking SND.NXT at the moment, when the * segment was retransmitted. * 4. D-SACK added new rule: D-SACK changes any tag to S. * * It is pleasant to note, that state diagram turns out to be commutative, * so that we are allowed not to be bothered by order of our actions, * when multiple events arrive simultaneously. (see the function below). * * Reordering detection. * -------------------- * Reordering metric is maximal distance, which a packet can be displaced * in packet stream. With SACKs we can estimate it: * * 1. SACK fills old hole and the corresponding segment was not * ever retransmitted -> reordering. Alas, we cannot use it * when segment was retransmitted. * 2. The last flaw is solved with D-SACK. D-SACK arrives * for retransmitted and already SACKed segment -> reordering.. * Both of these heuristics are not used in Loss state, when we cannot * account for retransmits accurately. * * SACK block validation. * ---------------------- * * SACK block range validation checks that the received SACK block fits to * the expected sequence limits, i.e., it is between SND.UNA and SND.NXT. * Note that SND.UNA is not included to the range though being valid because * it means that the receiver is rather inconsistent with itself reporting * SACK reneging when it should advance SND.UNA. Such SACK block this is * perfectly valid, however, in light of RFC2018 which explicitly states * that "SACK block MUST reflect the newest segment. Even if the newest * segment is going to be discarded ...", not that it looks very clever * in case of head skb. Due to potentional receiver driven attacks, we * choose to avoid immediate execution of a walk in write queue due to * reneging and defer head skb's loss recovery to standard loss recovery * procedure that will eventually trigger (nothing forbids us doing this). * * Implements also blockage to start_seq wrap-around. Problem lies in the * fact that though start_seq (s) is before end_seq (i.e., not reversed), * there's no guarantee that it will be before snd_nxt (n). The problem * happens when start_seq resides between end_seq wrap (e_w) and snd_nxt * wrap (s_w): * * <- outs wnd -> <- wrapzone -> * u e n u_w e_w s n_w * | | | | | | | * |<------------+------+----- TCP seqno space --------------+---------->| * ...-- <2^31 ->| |<--------... * ...---- >2^31 ------>| |<--------... * * Current code wouldn't be vulnerable but it's better still to discard such * crazy SACK blocks. Doing this check for start_seq alone closes somewhat * similar case (end_seq after snd_nxt wrap) as earlier reversed check in * snd_nxt wrap -> snd_una region will then become "well defined", i.e., * equal to the ideal case (infinite seqno space without wrap caused issues). * * With D-SACK the lower bound is extended to cover sequence space below * SND.UNA down to undo_marker, which is the last point of interest. Yet * again, D-SACK block must not to go across snd_una (for the same reason as * for the normal SACK blocks, explained above). But there all simplicity * ends, TCP might receive valid D-SACKs below that. As long as they reside * fully below undo_marker they do not affect behavior in anyway and can * therefore be safely ignored. In rare cases (which are more or less * theoretical ones), the D-SACK will nicely cross that boundary due to skb * fragmentation and packet reordering past skb's retransmission. To consider * them correctly, the acceptable range must be extended even more though * the exact amount is rather hard to quantify. However, tp->max_window can * be used as an exaggerated estimate. */ static bool tcp_is_sackblock_valid(struct tcp_sock *tp, bool is_dsack, u32 start_seq, u32 end_seq) { /* Too far in future, or reversed (interpretation is ambiguous) */ if (after(end_seq, tp->snd_nxt) || !before(start_seq, end_seq)) return false; /* Nasty start_seq wrap-around check (see comments above) */ if (!before(start_seq, tp->snd_nxt)) return false; /* In outstanding window? ...This is valid exit for D-SACKs too. * start_seq == snd_una is non-sensical (see comments above) */ if (after(start_seq, tp->snd_una)) return true; if (!is_dsack || !tp->undo_marker) return false; /* ...Then it's D-SACK, and must reside below snd_una completely */ if (after(end_seq, tp->snd_una)) return false; if (!before(start_seq, tp->undo_marker)) return true; /* Too old */ if (!after(end_seq, tp->undo_marker)) return false; /* Undo_marker boundary crossing (overestimates a lot). Known already: * start_seq < undo_marker and end_seq >= undo_marker. */ return !before(start_seq, end_seq - tp->max_window); } static bool tcp_check_dsack(struct sock *sk, const struct sk_buff *ack_skb, struct tcp_sack_block_wire *sp, int num_sacks, u32 prior_snd_una) { struct tcp_sock *tp = tcp_sk(sk); u32 start_seq_0 = get_unaligned_be32(&sp[0].start_seq); u32 end_seq_0 = get_unaligned_be32(&sp[0].end_seq); bool dup_sack = false; if (before(start_seq_0, TCP_SKB_CB(ack_skb)->ack_seq)) { dup_sack = true; tcp_dsack_seen(tp); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKRECV); } else if (num_sacks > 1) { u32 end_seq_1 = get_unaligned_be32(&sp[1].end_seq); u32 start_seq_1 = get_unaligned_be32(&sp[1].start_seq); if (!after(end_seq_0, end_seq_1) && !before(start_seq_0, start_seq_1)) { dup_sack = true; tcp_dsack_seen(tp); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKOFORECV); } } /* D-SACK for already forgotten data... Do dumb counting. */ if (dup_sack && tp->undo_marker && tp->undo_retrans > 0 && !after(end_seq_0, prior_snd_una) && after(end_seq_0, tp->undo_marker)) tp->undo_retrans--; return dup_sack; } struct tcp_sacktag_state { int reord; int fack_count; /* Timestamps for earliest and latest never-retransmitted segment * that was SACKed. RTO needs the earliest RTT to stay conservative, * but congestion control should still get an accurate delay signal. */ struct skb_mstamp first_sackt; struct skb_mstamp last_sackt; int flag; }; /* Check if skb is fully within the SACK block. In presence of GSO skbs, * the incoming SACK may not exactly match but we can find smaller MSS * aligned portion of it that matches. Therefore we might need to fragment * which may fail and creates some hassle (caller must handle error case * returns). * * FIXME: this could be merged to shift decision code */ static int tcp_match_skb_to_sack(struct sock *sk, struct sk_buff *skb, u32 start_seq, u32 end_seq) { int err; bool in_sack; unsigned int pkt_len; unsigned int mss; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && !before(end_seq, TCP_SKB_CB(skb)->end_seq); if (tcp_skb_pcount(skb) > 1 && !in_sack && after(TCP_SKB_CB(skb)->end_seq, start_seq)) { mss = tcp_skb_mss(skb); in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); if (!in_sack) { pkt_len = start_seq - TCP_SKB_CB(skb)->seq; if (pkt_len < mss) pkt_len = mss; } else { pkt_len = end_seq - TCP_SKB_CB(skb)->seq; if (pkt_len < mss) return -EINVAL; } /* Round if necessary so that SACKs cover only full MSSes * and/or the remaining small portion (if present) */ if (pkt_len > mss) { unsigned int new_len = (pkt_len / mss) * mss; if (!in_sack && new_len < pkt_len) { new_len += mss; if (new_len >= skb->len) return 0; } pkt_len = new_len; } err = tcp_fragment(sk, skb, pkt_len, mss, GFP_ATOMIC); if (err < 0) return err; } return in_sack; } /* Mark the given newly-SACKed range as such, adjusting counters and hints. */ static u8 tcp_sacktag_one(struct sock *sk, struct tcp_sacktag_state *state, u8 sacked, u32 start_seq, u32 end_seq, int dup_sack, int pcount, const struct skb_mstamp *xmit_time) { struct tcp_sock *tp = tcp_sk(sk); int fack_count = state->fack_count; /* Account D-SACK for retransmitted packet. */ if (dup_sack && (sacked & TCPCB_RETRANS)) { if (tp->undo_marker && tp->undo_retrans > 0 && after(end_seq, tp->undo_marker)) tp->undo_retrans--; if (sacked & TCPCB_SACKED_ACKED) state->reord = min(fack_count, state->reord); } /* Nothing to do; acked frame is about to be dropped (was ACKed). */ if (!after(end_seq, tp->snd_una)) return sacked; if (!(sacked & TCPCB_SACKED_ACKED)) { tcp_rack_advance(tp, xmit_time, sacked); if (sacked & TCPCB_SACKED_RETRANS) { /* If the segment is not tagged as lost, * we do not clear RETRANS, believing * that retransmission is still in flight. */ if (sacked & TCPCB_LOST) { sacked &= ~(TCPCB_LOST|TCPCB_SACKED_RETRANS); tp->lost_out -= pcount; tp->retrans_out -= pcount; } } else { if (!(sacked & TCPCB_RETRANS)) { /* New sack for not retransmitted frame, * which was in hole. It is reordering. */ if (before(start_seq, tcp_highest_sack_seq(tp))) state->reord = min(fack_count, state->reord); if (!after(end_seq, tp->high_seq)) state->flag |= FLAG_ORIG_SACK_ACKED; if (state->first_sackt.v64 == 0) state->first_sackt = *xmit_time; state->last_sackt = *xmit_time; } if (sacked & TCPCB_LOST) { sacked &= ~TCPCB_LOST; tp->lost_out -= pcount; } } sacked |= TCPCB_SACKED_ACKED; state->flag |= FLAG_DATA_SACKED; tp->sacked_out += pcount; tp->delivered += pcount; /* Out-of-order packets delivered */ fack_count += pcount; /* Lost marker hint past SACKed? Tweak RFC3517 cnt */ if (!tcp_is_fack(tp) && tp->lost_skb_hint && before(start_seq, TCP_SKB_CB(tp->lost_skb_hint)->seq)) tp->lost_cnt_hint += pcount; if (fack_count > tp->fackets_out) tp->fackets_out = fack_count; } /* D-SACK. We can detect redundant retransmission in S|R and plain R * frames and clear it. undo_retrans is decreased above, L|R frames * are accounted above as well. */ if (dup_sack && (sacked & TCPCB_SACKED_RETRANS)) { sacked &= ~TCPCB_SACKED_RETRANS; tp->retrans_out -= pcount; } return sacked; } /* Shift newly-SACKed bytes from this skb to the immediately previous * already-SACKed sk_buff. Mark the newly-SACKed bytes as such. */ static bool tcp_shifted_skb(struct sock *sk, struct sk_buff *skb, struct tcp_sacktag_state *state, unsigned int pcount, int shifted, int mss, bool dup_sack) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *prev = tcp_write_queue_prev(sk, skb); u32 start_seq = TCP_SKB_CB(skb)->seq; /* start of newly-SACKed */ u32 end_seq = start_seq + shifted; /* end of newly-SACKed */ BUG_ON(!pcount); /* Adjust counters and hints for the newly sacked sequence * range but discard the return value since prev is already * marked. We must tag the range first because the seq * advancement below implicitly advances * tcp_highest_sack_seq() when skb is highest_sack. */ tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked, start_seq, end_seq, dup_sack, pcount, &skb->skb_mstamp); if (skb == tp->lost_skb_hint) tp->lost_cnt_hint += pcount; TCP_SKB_CB(prev)->end_seq += shifted; TCP_SKB_CB(skb)->seq += shifted; tcp_skb_pcount_add(prev, pcount); BUG_ON(tcp_skb_pcount(skb) < pcount); tcp_skb_pcount_add(skb, -pcount); /* When we're adding to gso_segs == 1, gso_size will be zero, * in theory this shouldn't be necessary but as long as DSACK * code can come after this skb later on it's better to keep * setting gso_size to something. */ if (!TCP_SKB_CB(prev)->tcp_gso_size) TCP_SKB_CB(prev)->tcp_gso_size = mss; /* CHECKME: To clear or not to clear? Mimics normal skb currently */ if (tcp_skb_pcount(skb) <= 1) TCP_SKB_CB(skb)->tcp_gso_size = 0; /* Difference in this won't matter, both ACKed by the same cumul. ACK */ TCP_SKB_CB(prev)->sacked |= (TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS); if (skb->len > 0) { BUG_ON(!tcp_skb_pcount(skb)); NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTED); return false; } /* Whole SKB was eaten :-) */ if (skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = prev; if (skb == tp->lost_skb_hint) { tp->lost_skb_hint = prev; tp->lost_cnt_hint -= tcp_skb_pcount(prev); } TCP_SKB_CB(prev)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags; TCP_SKB_CB(prev)->eor = TCP_SKB_CB(skb)->eor; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) TCP_SKB_CB(prev)->end_seq++; if (skb == tcp_highest_sack(sk)) tcp_advance_highest_sack(sk, skb); tcp_skb_collapse_tstamp(prev, skb); tcp_unlink_write_queue(skb, sk); sk_wmem_free_skb(sk, skb); NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKMERGED); return true; } /* I wish gso_size would have a bit more sane initialization than * something-or-zero which complicates things */ static int tcp_skb_seglen(const struct sk_buff *skb) { return tcp_skb_pcount(skb) == 1 ? skb->len : tcp_skb_mss(skb); } /* Shifting pages past head area doesn't work */ static int skb_can_shift(const struct sk_buff *skb) { return !skb_headlen(skb) && skb_is_nonlinear(skb); } /* Try collapsing SACK blocks spanning across multiple skbs to a single * skb. */ static struct sk_buff *tcp_shift_skb_data(struct sock *sk, struct sk_buff *skb, struct tcp_sacktag_state *state, u32 start_seq, u32 end_seq, bool dup_sack) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *prev; int mss; int pcount = 0; int len; int in_sack; if (!sk_can_gso(sk)) goto fallback; /* Normally R but no L won't result in plain S */ if (!dup_sack && (TCP_SKB_CB(skb)->sacked & (TCPCB_LOST|TCPCB_SACKED_RETRANS)) == TCPCB_SACKED_RETRANS) goto fallback; if (!skb_can_shift(skb)) goto fallback; /* This frame is about to be dropped (was ACKed). */ if (!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) goto fallback; /* Can only happen with delayed DSACK + discard craziness */ if (unlikely(skb == tcp_write_queue_head(sk))) goto fallback; prev = tcp_write_queue_prev(sk, skb); if ((TCP_SKB_CB(prev)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) goto fallback; if (!tcp_skb_can_collapse_to(prev)) goto fallback; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq) && !before(end_seq, TCP_SKB_CB(skb)->end_seq); if (in_sack) { len = skb->len; pcount = tcp_skb_pcount(skb); mss = tcp_skb_seglen(skb); /* TODO: Fix DSACKs to not fragment already SACKed and we can * drop this restriction as unnecessary */ if (mss != tcp_skb_seglen(prev)) goto fallback; } else { if (!after(TCP_SKB_CB(skb)->end_seq, start_seq)) goto noop; /* CHECKME: This is non-MSS split case only?, this will * cause skipped skbs due to advancing loop btw, original * has that feature too */ if (tcp_skb_pcount(skb) <= 1) goto noop; in_sack = !after(start_seq, TCP_SKB_CB(skb)->seq); if (!in_sack) { /* TODO: head merge to next could be attempted here * if (!after(TCP_SKB_CB(skb)->end_seq, end_seq)), * though it might not be worth of the additional hassle * * ...we can probably just fallback to what was done * previously. We could try merging non-SACKed ones * as well but it probably isn't going to buy off * because later SACKs might again split them, and * it would make skb timestamp tracking considerably * harder problem. */ goto fallback; } len = end_seq - TCP_SKB_CB(skb)->seq; BUG_ON(len < 0); BUG_ON(len > skb->len); /* MSS boundaries should be honoured or else pcount will * severely break even though it makes things bit trickier. * Optimize common case to avoid most of the divides */ mss = tcp_skb_mss(skb); /* TODO: Fix DSACKs to not fragment already SACKed and we can * drop this restriction as unnecessary */ if (mss != tcp_skb_seglen(prev)) goto fallback; if (len == mss) { pcount = 1; } else if (len < mss) { goto noop; } else { pcount = len / mss; len = pcount * mss; } } /* tcp_sacktag_one() won't SACK-tag ranges below snd_una */ if (!after(TCP_SKB_CB(skb)->seq + len, tp->snd_una)) goto fallback; if (!skb_shift(prev, skb, len)) goto fallback; if (!tcp_shifted_skb(sk, skb, state, pcount, len, mss, dup_sack)) goto out; /* Hole filled allows collapsing with the next as well, this is very * useful when hole on every nth skb pattern happens */ if (prev == tcp_write_queue_tail(sk)) goto out; skb = tcp_write_queue_next(sk, prev); if (!skb_can_shift(skb) || (skb == tcp_send_head(sk)) || ((TCP_SKB_CB(skb)->sacked & TCPCB_TAGBITS) != TCPCB_SACKED_ACKED) || (mss != tcp_skb_seglen(skb))) goto out; len = skb->len; if (skb_shift(prev, skb, len)) { pcount += tcp_skb_pcount(skb); tcp_shifted_skb(sk, skb, state, tcp_skb_pcount(skb), len, mss, 0); } out: state->fack_count += pcount; return prev; noop: return skb; fallback: NET_INC_STATS(sock_net(sk), LINUX_MIB_SACKSHIFTFALLBACK); return NULL; } static struct sk_buff *tcp_sacktag_walk(struct sk_buff *skb, struct sock *sk, struct tcp_sack_block *next_dup, struct tcp_sacktag_state *state, u32 start_seq, u32 end_seq, bool dup_sack_in) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *tmp; tcp_for_write_queue_from(skb, sk) { int in_sack = 0; bool dup_sack = dup_sack_in; if (skb == tcp_send_head(sk)) break; /* queue is in-order => we can short-circuit the walk early */ if (!before(TCP_SKB_CB(skb)->seq, end_seq)) break; if (next_dup && before(TCP_SKB_CB(skb)->seq, next_dup->end_seq)) { in_sack = tcp_match_skb_to_sack(sk, skb, next_dup->start_seq, next_dup->end_seq); if (in_sack > 0) dup_sack = true; } /* skb reference here is a bit tricky to get right, since * shifting can eat and free both this skb and the next, * so not even _safe variant of the loop is enough. */ if (in_sack <= 0) { tmp = tcp_shift_skb_data(sk, skb, state, start_seq, end_seq, dup_sack); if (tmp) { if (tmp != skb) { skb = tmp; continue; } in_sack = 0; } else { in_sack = tcp_match_skb_to_sack(sk, skb, start_seq, end_seq); } } if (unlikely(in_sack < 0)) break; if (in_sack) { TCP_SKB_CB(skb)->sacked = tcp_sacktag_one(sk, state, TCP_SKB_CB(skb)->sacked, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq, dup_sack, tcp_skb_pcount(skb), &skb->skb_mstamp); if (!before(TCP_SKB_CB(skb)->seq, tcp_highest_sack_seq(tp))) tcp_advance_highest_sack(sk, skb); } state->fack_count += tcp_skb_pcount(skb); } return skb; } /* Avoid all extra work that is being done by sacktag while walking in * a normal way */ static struct sk_buff *tcp_sacktag_skip(struct sk_buff *skb, struct sock *sk, struct tcp_sacktag_state *state, u32 skip_to_seq) { tcp_for_write_queue_from(skb, sk) { if (skb == tcp_send_head(sk)) break; if (after(TCP_SKB_CB(skb)->end_seq, skip_to_seq)) break; state->fack_count += tcp_skb_pcount(skb); } return skb; } static struct sk_buff *tcp_maybe_skipping_dsack(struct sk_buff *skb, struct sock *sk, struct tcp_sack_block *next_dup, struct tcp_sacktag_state *state, u32 skip_to_seq) { if (!next_dup) return skb; if (before(next_dup->start_seq, skip_to_seq)) { skb = tcp_sacktag_skip(skb, sk, state, next_dup->start_seq); skb = tcp_sacktag_walk(skb, sk, NULL, state, next_dup->start_seq, next_dup->end_seq, 1); } return skb; } static int tcp_sack_cache_ok(const struct tcp_sock *tp, const struct tcp_sack_block *cache) { return cache < tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); } static int tcp_sacktag_write_queue(struct sock *sk, const struct sk_buff *ack_skb, u32 prior_snd_una, struct tcp_sacktag_state *state) { struct tcp_sock *tp = tcp_sk(sk); const unsigned char *ptr = (skb_transport_header(ack_skb) + TCP_SKB_CB(ack_skb)->sacked); struct tcp_sack_block_wire *sp_wire = (struct tcp_sack_block_wire *)(ptr+2); struct tcp_sack_block sp[TCP_NUM_SACKS]; struct tcp_sack_block *cache; struct sk_buff *skb; int num_sacks = min(TCP_NUM_SACKS, (ptr[1] - TCPOLEN_SACK_BASE) >> 3); int used_sacks; bool found_dup_sack = false; int i, j; int first_sack_index; state->flag = 0; state->reord = tp->packets_out; if (!tp->sacked_out) { if (WARN_ON(tp->fackets_out)) tp->fackets_out = 0; tcp_highest_sack_reset(sk); } found_dup_sack = tcp_check_dsack(sk, ack_skb, sp_wire, num_sacks, prior_snd_una); if (found_dup_sack) state->flag |= FLAG_DSACKING_ACK; /* Eliminate too old ACKs, but take into * account more or less fresh ones, they can * contain valid SACK info. */ if (before(TCP_SKB_CB(ack_skb)->ack_seq, prior_snd_una - tp->max_window)) return 0; if (!tp->packets_out) goto out; used_sacks = 0; first_sack_index = 0; for (i = 0; i < num_sacks; i++) { bool dup_sack = !i && found_dup_sack; sp[used_sacks].start_seq = get_unaligned_be32(&sp_wire[i].start_seq); sp[used_sacks].end_seq = get_unaligned_be32(&sp_wire[i].end_seq); if (!tcp_is_sackblock_valid(tp, dup_sack, sp[used_sacks].start_seq, sp[used_sacks].end_seq)) { int mib_idx; if (dup_sack) { if (!tp->undo_marker) mib_idx = LINUX_MIB_TCPDSACKIGNOREDNOUNDO; else mib_idx = LINUX_MIB_TCPDSACKIGNOREDOLD; } else { /* Don't count olds caused by ACK reordering */ if ((TCP_SKB_CB(ack_skb)->ack_seq != tp->snd_una) && !after(sp[used_sacks].end_seq, tp->snd_una)) continue; mib_idx = LINUX_MIB_TCPSACKDISCARD; } NET_INC_STATS(sock_net(sk), mib_idx); if (i == 0) first_sack_index = -1; continue; } /* Ignore very old stuff early */ if (!after(sp[used_sacks].end_seq, prior_snd_una)) continue; used_sacks++; } /* order SACK blocks to allow in order walk of the retrans queue */ for (i = used_sacks - 1; i > 0; i--) { for (j = 0; j < i; j++) { if (after(sp[j].start_seq, sp[j + 1].start_seq)) { swap(sp[j], sp[j + 1]); /* Track where the first SACK block goes to */ if (j == first_sack_index) first_sack_index = j + 1; } } } skb = tcp_write_queue_head(sk); state->fack_count = 0; i = 0; if (!tp->sacked_out) { /* It's already past, so skip checking against it */ cache = tp->recv_sack_cache + ARRAY_SIZE(tp->recv_sack_cache); } else { cache = tp->recv_sack_cache; /* Skip empty blocks in at head of the cache */ while (tcp_sack_cache_ok(tp, cache) && !cache->start_seq && !cache->end_seq) cache++; } while (i < used_sacks) { u32 start_seq = sp[i].start_seq; u32 end_seq = sp[i].end_seq; bool dup_sack = (found_dup_sack && (i == first_sack_index)); struct tcp_sack_block *next_dup = NULL; if (found_dup_sack && ((i + 1) == first_sack_index)) next_dup = &sp[i + 1]; /* Skip too early cached blocks */ while (tcp_sack_cache_ok(tp, cache) && !before(start_seq, cache->end_seq)) cache++; /* Can skip some work by looking recv_sack_cache? */ if (tcp_sack_cache_ok(tp, cache) && !dup_sack && after(end_seq, cache->start_seq)) { /* Head todo? */ if (before(start_seq, cache->start_seq)) { skb = tcp_sacktag_skip(skb, sk, state, start_seq); skb = tcp_sacktag_walk(skb, sk, next_dup, state, start_seq, cache->start_seq, dup_sack); } /* Rest of the block already fully processed? */ if (!after(end_seq, cache->end_seq)) goto advance_sp; skb = tcp_maybe_skipping_dsack(skb, sk, next_dup, state, cache->end_seq); /* ...tail remains todo... */ if (tcp_highest_sack_seq(tp) == cache->end_seq) { /* ...but better entrypoint exists! */ skb = tcp_highest_sack(sk); if (!skb) break; state->fack_count = tp->fackets_out; cache++; goto walk; } skb = tcp_sacktag_skip(skb, sk, state, cache->end_seq); /* Check overlap against next cached too (past this one already) */ cache++; continue; } if (!before(start_seq, tcp_highest_sack_seq(tp))) { skb = tcp_highest_sack(sk); if (!skb) break; state->fack_count = tp->fackets_out; } skb = tcp_sacktag_skip(skb, sk, state, start_seq); walk: skb = tcp_sacktag_walk(skb, sk, next_dup, state, start_seq, end_seq, dup_sack); advance_sp: i++; } /* Clear the head of the cache sack blocks so we can skip it next time */ for (i = 0; i < ARRAY_SIZE(tp->recv_sack_cache) - used_sacks; i++) { tp->recv_sack_cache[i].start_seq = 0; tp->recv_sack_cache[i].end_seq = 0; } for (j = 0; j < used_sacks; j++) tp->recv_sack_cache[i++] = sp[j]; if ((state->reord < tp->fackets_out) && ((inet_csk(sk)->icsk_ca_state != TCP_CA_Loss) || tp->undo_marker)) tcp_update_reordering(sk, tp->fackets_out - state->reord, 0); tcp_verify_left_out(tp); out: #if FASTRETRANS_DEBUG > 0 WARN_ON((int)tp->sacked_out < 0); WARN_ON((int)tp->lost_out < 0); WARN_ON((int)tp->retrans_out < 0); WARN_ON((int)tcp_packets_in_flight(tp) < 0); #endif return state->flag; } /* Limits sacked_out so that sum with lost_out isn't ever larger than * packets_out. Returns false if sacked_out adjustement wasn't necessary. */ static bool tcp_limit_reno_sacked(struct tcp_sock *tp) { u32 holes; holes = max(tp->lost_out, 1U); holes = min(holes, tp->packets_out); if ((tp->sacked_out + holes) > tp->packets_out) { tp->sacked_out = tp->packets_out - holes; return true; } return false; } /* If we receive more dupacks than we expected counting segments * in assumption of absent reordering, interpret this as reordering. * The only another reason could be bug in receiver TCP. */ static void tcp_check_reno_reordering(struct sock *sk, const int addend) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_limit_reno_sacked(tp)) tcp_update_reordering(sk, tp->packets_out + addend, 0); } /* Emulate SACKs for SACKless connection: account for a new dupack. */ static void tcp_add_reno_sack(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); u32 prior_sacked = tp->sacked_out; tp->sacked_out++; tcp_check_reno_reordering(sk, 0); if (tp->sacked_out > prior_sacked) tp->delivered++; /* Some out-of-order packet is delivered */ tcp_verify_left_out(tp); } /* Account for ACK, ACKing some data in Reno Recovery phase. */ static void tcp_remove_reno_sacks(struct sock *sk, int acked) { struct tcp_sock *tp = tcp_sk(sk); if (acked > 0) { /* One ACK acked hole. The rest eat duplicate ACKs. */ tp->delivered += max_t(int, acked - tp->sacked_out, 1); if (acked - 1 >= tp->sacked_out) tp->sacked_out = 0; else tp->sacked_out -= acked - 1; } tcp_check_reno_reordering(sk, acked); tcp_verify_left_out(tp); } static inline void tcp_reset_reno_sack(struct tcp_sock *tp) { tp->sacked_out = 0; } void tcp_clear_retrans(struct tcp_sock *tp) { tp->retrans_out = 0; tp->lost_out = 0; tp->undo_marker = 0; tp->undo_retrans = -1; tp->fackets_out = 0; tp->sacked_out = 0; } static inline void tcp_init_undo(struct tcp_sock *tp) { tp->undo_marker = tp->snd_una; /* Retransmission still in flight may cause DSACKs later. */ tp->undo_retrans = tp->retrans_out ? : -1; } /* Enter Loss state. If we detect SACK reneging, forget all SACK information * and reset tags completely, otherwise preserve SACKs. If receiver * dropped its ofo queue, we will know this due to reneging detection. */ void tcp_enter_loss(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct net *net = sock_net(sk); struct sk_buff *skb; bool new_recovery = icsk->icsk_ca_state < TCP_CA_Recovery; bool is_reneg; /* is receiver reneging on SACKs? */ /* Reduce ssthresh if it has not yet been made inside this window. */ if (icsk->icsk_ca_state <= TCP_CA_Disorder || !after(tp->high_seq, tp->snd_una) || (icsk->icsk_ca_state == TCP_CA_Loss && !icsk->icsk_retransmits)) { tp->prior_ssthresh = tcp_current_ssthresh(sk); tp->snd_ssthresh = icsk->icsk_ca_ops->ssthresh(sk); tcp_ca_event(sk, CA_EVENT_LOSS); tcp_init_undo(tp); } tp->snd_cwnd = 1; tp->snd_cwnd_cnt = 0; tp->snd_cwnd_stamp = tcp_time_stamp; tp->retrans_out = 0; tp->lost_out = 0; if (tcp_is_reno(tp)) tcp_reset_reno_sack(tp); skb = tcp_write_queue_head(sk); is_reneg = skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED); if (is_reneg) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSACKRENEGING); tp->sacked_out = 0; tp->fackets_out = 0; } tcp_clear_all_retrans_hints(tp); tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; TCP_SKB_CB(skb)->sacked &= (~TCPCB_TAGBITS)|TCPCB_SACKED_ACKED; if (!(TCP_SKB_CB(skb)->sacked&TCPCB_SACKED_ACKED) || is_reneg) { TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_ACKED; TCP_SKB_CB(skb)->sacked |= TCPCB_LOST; tp->lost_out += tcp_skb_pcount(skb); tp->retransmit_high = TCP_SKB_CB(skb)->end_seq; } } tcp_verify_left_out(tp); /* Timeout in disordered state after receiving substantial DUPACKs * suggests that the degree of reordering is over-estimated. */ if (icsk->icsk_ca_state <= TCP_CA_Disorder && tp->sacked_out >= net->ipv4.sysctl_tcp_reordering) tp->reordering = min_t(unsigned int, tp->reordering, net->ipv4.sysctl_tcp_reordering); tcp_set_ca_state(sk, TCP_CA_Loss); tp->high_seq = tp->snd_nxt; tcp_ecn_queue_cwr(tp); /* F-RTO RFC5682 sec 3.1 step 1: retransmit SND.UNA if no previous * loss recovery is underway except recurring timeout(s) on * the same SND.UNA (sec 3.2). Disable F-RTO on path MTU probing */ tp->frto = sysctl_tcp_frto && (new_recovery || icsk->icsk_retransmits) && !inet_csk(sk)->icsk_mtup.probe_size; } /* If ACK arrived pointing to a remembered SACK, it means that our * remembered SACKs do not reflect real state of receiver i.e. * receiver _host_ is heavily congested (or buggy). * * To avoid big spurious retransmission bursts due to transient SACK * scoreboard oddities that look like reneging, we give the receiver a * little time (max(RTT/2, 10ms)) to send us some more ACKs that will * restore sanity to the SACK scoreboard. If the apparent reneging * persists until this RTO then we'll clear the SACK scoreboard. */ static bool tcp_check_sack_reneging(struct sock *sk, int flag) { if (flag & FLAG_SACK_RENEGING) { struct tcp_sock *tp = tcp_sk(sk); unsigned long delay = max(usecs_to_jiffies(tp->srtt_us >> 4), msecs_to_jiffies(10)); inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, delay, TCP_RTO_MAX); return true; } return false; } static inline int tcp_fackets_out(const struct tcp_sock *tp) { return tcp_is_reno(tp) ? tp->sacked_out + 1 : tp->fackets_out; } /* Heurestics to calculate number of duplicate ACKs. There's no dupACKs * counter when SACK is enabled (without SACK, sacked_out is used for * that purpose). * * Instead, with FACK TCP uses fackets_out that includes both SACKed * segments up to the highest received SACK block so far and holes in * between them. * * With reordering, holes may still be in flight, so RFC3517 recovery * uses pure sacked_out (total number of SACKed segments) even though * it violates the RFC that uses duplicate ACKs, often these are equal * but when e.g. out-of-window ACKs or packet duplication occurs, * they differ. Since neither occurs due to loss, TCP should really * ignore them. */ static inline int tcp_dupack_heuristics(const struct tcp_sock *tp) { return tcp_is_fack(tp) ? tp->fackets_out : tp->sacked_out + 1; } static bool tcp_pause_early_retransmit(struct sock *sk, int flag) { struct tcp_sock *tp = tcp_sk(sk); unsigned long delay; /* Delay early retransmit and entering fast recovery for * max(RTT/4, 2msec) unless ack has ECE mark, no RTT samples * available, or RTO is scheduled to fire first. */ if (sysctl_tcp_early_retrans < 2 || sysctl_tcp_early_retrans > 3 || (flag & FLAG_ECE) || !tp->srtt_us) return false; delay = max(usecs_to_jiffies(tp->srtt_us >> 5), msecs_to_jiffies(2)); if (!time_after(inet_csk(sk)->icsk_timeout, (jiffies + delay))) return false; inet_csk_reset_xmit_timer(sk, ICSK_TIME_EARLY_RETRANS, delay, TCP_RTO_MAX); return true; } /* Linux NewReno/SACK/FACK/ECN state machine. * -------------------------------------- * * "Open" Normal state, no dubious events, fast path. * "Disorder" In all the respects it is "Open", * but requires a bit more attention. It is entered when * we see some SACKs or dupacks. It is split of "Open" * mainly to move some processing from fast path to slow one. * "CWR" CWND was reduced due to some Congestion Notification event. * It can be ECN, ICMP source quench, local device congestion. * "Recovery" CWND was reduced, we are fast-retransmitting. * "Loss" CWND was reduced due to RTO timeout or SACK reneging. * * tcp_fastretrans_alert() is entered: * - each incoming ACK, if state is not "Open" * - when arrived ACK is unusual, namely: * * SACK * * Duplicate ACK. * * ECN ECE. * * Counting packets in flight is pretty simple. * * in_flight = packets_out - left_out + retrans_out * * packets_out is SND.NXT-SND.UNA counted in packets. * * retrans_out is number of retransmitted segments. * * left_out is number of segments left network, but not ACKed yet. * * left_out = sacked_out + lost_out * * sacked_out: Packets, which arrived to receiver out of order * and hence not ACKed. With SACKs this number is simply * amount of SACKed data. Even without SACKs * it is easy to give pretty reliable estimate of this number, * counting duplicate ACKs. * * lost_out: Packets lost by network. TCP has no explicit * "loss notification" feedback from network (for now). * It means that this number can be only _guessed_. * Actually, it is the heuristics to predict lossage that * distinguishes different algorithms. * * F.e. after RTO, when all the queue is considered as lost, * lost_out = packets_out and in_flight = retrans_out. * * Essentially, we have now two algorithms counting * lost packets. * * FACK: It is the simplest heuristics. As soon as we decided * that something is lost, we decide that _all_ not SACKed * packets until the most forward SACK are lost. I.e. * lost_out = fackets_out - sacked_out and left_out = fackets_out. * It is absolutely correct estimate, if network does not reorder * packets. And it loses any connection to reality when reordering * takes place. We use FACK by default until reordering * is suspected on the path to this destination. * * NewReno: when Recovery is entered, we assume that one segment * is lost (classic Reno). While we are in Recovery and * a partial ACK arrives, we assume that one more packet * is lost (NewReno). This heuristics are the same in NewReno * and SACK. * * Imagine, that's all! Forget about all this shamanism about CWND inflation * deflation etc. CWND is real congestion window, never inflated, changes * only according to classic VJ rules. * * Really tricky (and requiring careful tuning) part of algorithm * is hidden in functions tcp_time_to_recover() and tcp_xmit_retransmit_queue(). * The first determines the moment _when_ we should reduce CWND and, * hence, slow down forward transmission. In fact, it determines the moment * when we decide that hole is caused by loss, rather than by a reorder. * * tcp_xmit_retransmit_queue() decides, _what_ we should retransmit to fill * holes, caused by lost packets. * * And the most logically complicated part of algorithm is undo * heuristics. We detect false retransmits due to both too early * fast retransmit (reordering) and underestimated RTO, analyzing * timestamps and D-SACKs. When we detect that some segments were * retransmitted by mistake and CWND reduction was wrong, we undo * window reduction and abort recovery phase. This logic is hidden * inside several functions named tcp_try_undo_<something>. */ /* This function decides, when we should leave Disordered state * and enter Recovery phase, reducing congestion window. * * Main question: may we further continue forward transmission * with the same cwnd? */ static bool tcp_time_to_recover(struct sock *sk, int flag) { struct tcp_sock *tp = tcp_sk(sk); __u32 packets_out; int tcp_reordering = sock_net(sk)->ipv4.sysctl_tcp_reordering; /* Trick#1: The loss is proven. */ if (tp->lost_out) return true; /* Not-A-Trick#2 : Classic rule... */ if (tcp_dupack_heuristics(tp) > tp->reordering) return true; /* Trick#4: It is still not OK... But will it be useful to delay * recovery more? */ packets_out = tp->packets_out; if (packets_out <= tp->reordering && tp->sacked_out >= max_t(__u32, packets_out/2, tcp_reordering) && !tcp_may_send_now(sk)) { /* We have nothing to send. This connection is limited * either by receiver window or by application. */ return true; } /* If a thin stream is detected, retransmit after first * received dupack. Employ only if SACK is supported in order * to avoid possible corner-case series of spurious retransmissions * Use only if there are no unsent data. */ if ((tp->thin_dupack || sysctl_tcp_thin_dupack) && tcp_stream_is_thin(tp) && tcp_dupack_heuristics(tp) > 1 && tcp_is_sack(tp) && !tcp_send_head(sk)) return true; /* Trick#6: TCP early retransmit, per RFC5827. To avoid spurious * retransmissions due to small network reorderings, we implement * Mitigation A.3 in the RFC and delay the retransmission for a short * interval if appropriate. */ if (tp->do_early_retrans && !tp->retrans_out && tp->sacked_out && (tp->packets_out >= (tp->sacked_out + 1) && tp->packets_out < 4) && !tcp_may_send_now(sk)) return !tcp_pause_early_retransmit(sk, flag); return false; } /* Detect loss in event "A" above by marking head of queue up as lost. * For FACK or non-SACK(Reno) senders, the first "packets" number of segments * are considered lost. For RFC3517 SACK, a segment is considered lost if it * has at least tp->reordering SACKed seqments above it; "packets" refers to * the maximum SACKed segments to pass before reaching this limit. */ static void tcp_mark_head_lost(struct sock *sk, int packets, int mark_head) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int cnt, oldcnt, lost; unsigned int mss; /* Use SACK to deduce losses of new sequences sent during recovery */ const u32 loss_high = tcp_is_sack(tp) ? tp->snd_nxt : tp->high_seq; WARN_ON(packets > tp->packets_out); if (tp->lost_skb_hint) { skb = tp->lost_skb_hint; cnt = tp->lost_cnt_hint; /* Head already handled? */ if (mark_head && skb != tcp_write_queue_head(sk)) return; } else { skb = tcp_write_queue_head(sk); cnt = 0; } tcp_for_write_queue_from(skb, sk) { if (skb == tcp_send_head(sk)) break; /* TODO: do this better */ /* this is not the most efficient way to do this... */ tp->lost_skb_hint = skb; tp->lost_cnt_hint = cnt; if (after(TCP_SKB_CB(skb)->end_seq, loss_high)) break; oldcnt = cnt; if (tcp_is_fack(tp) || tcp_is_reno(tp) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) cnt += tcp_skb_pcount(skb); if (cnt > packets) { if ((tcp_is_sack(tp) && !tcp_is_fack(tp)) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) || (oldcnt >= packets)) break; mss = tcp_skb_mss(skb); /* If needed, chop off the prefix to mark as lost. */ lost = (packets - oldcnt) * mss; if (lost < skb->len && tcp_fragment(sk, skb, lost, mss, GFP_ATOMIC) < 0) break; cnt = packets; } tcp_skb_mark_lost(tp, skb); if (mark_head) break; } tcp_verify_left_out(tp); } /* Account newly detected lost packet(s) */ static void tcp_update_scoreboard(struct sock *sk, int fast_rexmit) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_is_reno(tp)) { tcp_mark_head_lost(sk, 1, 1); } else if (tcp_is_fack(tp)) { int lost = tp->fackets_out - tp->reordering; if (lost <= 0) lost = 1; tcp_mark_head_lost(sk, lost, 0); } else { int sacked_upto = tp->sacked_out - tp->reordering; if (sacked_upto >= 0) tcp_mark_head_lost(sk, sacked_upto, 0); else if (fast_rexmit) tcp_mark_head_lost(sk, 1, 1); } } static bool tcp_tsopt_ecr_before(const struct tcp_sock *tp, u32 when) { return tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr && before(tp->rx_opt.rcv_tsecr, when); } /* skb is spurious retransmitted if the returned timestamp echo * reply is prior to the skb transmission time */ static bool tcp_skb_spurious_retrans(const struct tcp_sock *tp, const struct sk_buff *skb) { return (TCP_SKB_CB(skb)->sacked & TCPCB_RETRANS) && tcp_tsopt_ecr_before(tp, tcp_skb_timestamp(skb)); } /* Nothing was retransmitted or returned timestamp is less * than timestamp of the first retransmission. */ static inline bool tcp_packet_delayed(const struct tcp_sock *tp) { return !tp->retrans_stamp || tcp_tsopt_ecr_before(tp, tp->retrans_stamp); } /* Undo procedures. */ /* We can clear retrans_stamp when there are no retransmissions in the * window. It would seem that it is trivially available for us in * tp->retrans_out, however, that kind of assumptions doesn't consider * what will happen if errors occur when sending retransmission for the * second time. ...It could the that such segment has only * TCPCB_EVER_RETRANS set at the present time. It seems that checking * the head skb is enough except for some reneging corner cases that * are not worth the effort. * * Main reason for all this complexity is the fact that connection dying * time now depends on the validity of the retrans_stamp, in particular, * that successive retransmissions of a segment must not advance * retrans_stamp under any conditions. */ static bool tcp_any_retrans_done(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (tp->retrans_out) return true; skb = tcp_write_queue_head(sk); if (unlikely(skb && TCP_SKB_CB(skb)->sacked & TCPCB_EVER_RETRANS)) return true; return false; } #if FASTRETRANS_DEBUG > 1 static void DBGUNDO(struct sock *sk, const char *msg) { struct tcp_sock *tp = tcp_sk(sk); struct inet_sock *inet = inet_sk(sk); if (sk->sk_family == AF_INET) { pr_debug("Undo %s %pI4/%u c%u l%u ss%u/%u p%u\n", msg, &inet->inet_daddr, ntohs(inet->inet_dport), tp->snd_cwnd, tcp_left_out(tp), tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out); } #if IS_ENABLED(CONFIG_IPV6) else if (sk->sk_family == AF_INET6) { struct ipv6_pinfo *np = inet6_sk(sk); pr_debug("Undo %s %pI6/%u c%u l%u ss%u/%u p%u\n", msg, &np->daddr, ntohs(inet->inet_dport), tp->snd_cwnd, tcp_left_out(tp), tp->snd_ssthresh, tp->prior_ssthresh, tp->packets_out); } #endif } #else #define DBGUNDO(x...) do { } while (0) #endif static void tcp_undo_cwnd_reduction(struct sock *sk, bool unmark_loss) { struct tcp_sock *tp = tcp_sk(sk); if (unmark_loss) { struct sk_buff *skb; tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; TCP_SKB_CB(skb)->sacked &= ~TCPCB_LOST; } tp->lost_out = 0; tcp_clear_all_retrans_hints(tp); } if (tp->prior_ssthresh) { const struct inet_connection_sock *icsk = inet_csk(sk); if (icsk->icsk_ca_ops->undo_cwnd) tp->snd_cwnd = icsk->icsk_ca_ops->undo_cwnd(sk); else tp->snd_cwnd = max(tp->snd_cwnd, tp->snd_ssthresh << 1); if (tp->prior_ssthresh > tp->snd_ssthresh) { tp->snd_ssthresh = tp->prior_ssthresh; tcp_ecn_withdraw_cwr(tp); } } tp->snd_cwnd_stamp = tcp_time_stamp; tp->undo_marker = 0; } static inline bool tcp_may_undo(const struct tcp_sock *tp) { return tp->undo_marker && (!tp->undo_retrans || tcp_packet_delayed(tp)); } /* People celebrate: "We love our President!" */ static bool tcp_try_undo_recovery(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_may_undo(tp)) { int mib_idx; /* Happy end! We did not retransmit anything * or our original transmission succeeded. */ DBGUNDO(sk, inet_csk(sk)->icsk_ca_state == TCP_CA_Loss ? "loss" : "retrans"); tcp_undo_cwnd_reduction(sk, false); if (inet_csk(sk)->icsk_ca_state == TCP_CA_Loss) mib_idx = LINUX_MIB_TCPLOSSUNDO; else mib_idx = LINUX_MIB_TCPFULLUNDO; NET_INC_STATS(sock_net(sk), mib_idx); } if (tp->snd_una == tp->high_seq && tcp_is_reno(tp)) { /* Hold old state until something *above* high_seq * is ACKed. For Reno it is MUST to prevent false * fast retransmits (RFC2582). SACK TCP is safe. */ if (!tcp_any_retrans_done(sk)) tp->retrans_stamp = 0; return true; } tcp_set_ca_state(sk, TCP_CA_Open); return false; } /* Try to undo cwnd reduction, because D-SACKs acked all retransmitted data */ static bool tcp_try_undo_dsack(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tp->undo_marker && !tp->undo_retrans) { DBGUNDO(sk, "D-SACK"); tcp_undo_cwnd_reduction(sk, false); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPDSACKUNDO); return true; } return false; } /* Undo during loss recovery after partial ACK or using F-RTO. */ static bool tcp_try_undo_loss(struct sock *sk, bool frto_undo) { struct tcp_sock *tp = tcp_sk(sk); if (frto_undo || tcp_may_undo(tp)) { tcp_undo_cwnd_reduction(sk, true); DBGUNDO(sk, "partial loss"); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSUNDO); if (frto_undo) NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSPURIOUSRTOS); inet_csk(sk)->icsk_retransmits = 0; if (frto_undo || tcp_is_sack(tp)) tcp_set_ca_state(sk, TCP_CA_Open); return true; } return false; } /* The cwnd reduction in CWR and Recovery uses the PRR algorithm in RFC 6937. * It computes the number of packets to send (sndcnt) based on packets newly * delivered: * 1) If the packets in flight is larger than ssthresh, PRR spreads the * cwnd reductions across a full RTT. * 2) Otherwise PRR uses packet conservation to send as much as delivered. * But when the retransmits are acked without further losses, PRR * slow starts cwnd up to ssthresh to speed up the recovery. */ static void tcp_init_cwnd_reduction(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); tp->high_seq = tp->snd_nxt; tp->tlp_high_seq = 0; tp->snd_cwnd_cnt = 0; tp->prior_cwnd = tp->snd_cwnd; tp->prr_delivered = 0; tp->prr_out = 0; tp->snd_ssthresh = inet_csk(sk)->icsk_ca_ops->ssthresh(sk); tcp_ecn_queue_cwr(tp); } static void tcp_cwnd_reduction(struct sock *sk, int newly_acked_sacked, int flag) { struct tcp_sock *tp = tcp_sk(sk); int sndcnt = 0; int delta = tp->snd_ssthresh - tcp_packets_in_flight(tp); if (newly_acked_sacked <= 0 || WARN_ON_ONCE(!tp->prior_cwnd)) return; tp->prr_delivered += newly_acked_sacked; if (delta < 0) { u64 dividend = (u64)tp->snd_ssthresh * tp->prr_delivered + tp->prior_cwnd - 1; sndcnt = div_u64(dividend, tp->prior_cwnd) - tp->prr_out; } else if ((flag & FLAG_RETRANS_DATA_ACKED) && !(flag & FLAG_LOST_RETRANS)) { sndcnt = min_t(int, delta, max_t(int, tp->prr_delivered - tp->prr_out, newly_acked_sacked) + 1); } else { sndcnt = min(delta, newly_acked_sacked); } /* Force a fast retransmit upon entering fast recovery */ sndcnt = max(sndcnt, (tp->prr_out ? 0 : 1)); tp->snd_cwnd = tcp_packets_in_flight(tp) + sndcnt; } static inline void tcp_end_cwnd_reduction(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); /* Reset cwnd to ssthresh in CWR or Recovery (unless it's undone) */ if (inet_csk(sk)->icsk_ca_state == TCP_CA_CWR || (tp->undo_marker && tp->snd_ssthresh < TCP_INFINITE_SSTHRESH)) { tp->snd_cwnd = tp->snd_ssthresh; tp->snd_cwnd_stamp = tcp_time_stamp; } tcp_ca_event(sk, CA_EVENT_COMPLETE_CWR); } /* Enter CWR state. Disable cwnd undo since congestion is proven with ECN */ void tcp_enter_cwr(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); tp->prior_ssthresh = 0; if (inet_csk(sk)->icsk_ca_state < TCP_CA_CWR) { tp->undo_marker = 0; tcp_init_cwnd_reduction(sk); tcp_set_ca_state(sk, TCP_CA_CWR); } } EXPORT_SYMBOL(tcp_enter_cwr); static void tcp_try_keep_open(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); int state = TCP_CA_Open; if (tcp_left_out(tp) || tcp_any_retrans_done(sk)) state = TCP_CA_Disorder; if (inet_csk(sk)->icsk_ca_state != state) { tcp_set_ca_state(sk, state); tp->high_seq = tp->snd_nxt; } } static void tcp_try_to_open(struct sock *sk, int flag) { struct tcp_sock *tp = tcp_sk(sk); tcp_verify_left_out(tp); if (!tcp_any_retrans_done(sk)) tp->retrans_stamp = 0; if (flag & FLAG_ECE) tcp_enter_cwr(sk); if (inet_csk(sk)->icsk_ca_state != TCP_CA_CWR) { tcp_try_keep_open(sk); } } static void tcp_mtup_probe_failed(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_mtup.search_high = icsk->icsk_mtup.probe_size - 1; icsk->icsk_mtup.probe_size = 0; NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPFAIL); } static void tcp_mtup_probe_success(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); /* FIXME: breaks with very large cwnd */ tp->prior_ssthresh = tcp_current_ssthresh(sk); tp->snd_cwnd = tp->snd_cwnd * tcp_mss_to_mtu(sk, tp->mss_cache) / icsk->icsk_mtup.probe_size; tp->snd_cwnd_cnt = 0; tp->snd_cwnd_stamp = tcp_time_stamp; tp->snd_ssthresh = tcp_current_ssthresh(sk); icsk->icsk_mtup.search_low = icsk->icsk_mtup.probe_size; icsk->icsk_mtup.probe_size = 0; tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPMTUPSUCCESS); } /* Do a simple retransmit without using the backoff mechanisms in * tcp_timer. This is used for path mtu discovery. * The socket is already locked here. */ void tcp_simple_retransmit(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; unsigned int mss = tcp_current_mss(sk); u32 prior_lost = tp->lost_out; tcp_for_write_queue(skb, sk) { if (skb == tcp_send_head(sk)) break; if (tcp_skb_seglen(skb) > mss && !(TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) { if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) { TCP_SKB_CB(skb)->sacked &= ~TCPCB_SACKED_RETRANS; tp->retrans_out -= tcp_skb_pcount(skb); } tcp_skb_mark_lost_uncond_verify(tp, skb); } } tcp_clear_retrans_hints_partial(tp); if (prior_lost == tp->lost_out) return; if (tcp_is_reno(tp)) tcp_limit_reno_sacked(tp); tcp_verify_left_out(tp); /* Don't muck with the congestion window here. * Reason is that we do not increase amount of _data_ * in network, but units changed and effective * cwnd/ssthresh really reduced now. */ if (icsk->icsk_ca_state != TCP_CA_Loss) { tp->high_seq = tp->snd_nxt; tp->snd_ssthresh = tcp_current_ssthresh(sk); tp->prior_ssthresh = 0; tp->undo_marker = 0; tcp_set_ca_state(sk, TCP_CA_Loss); } tcp_xmit_retransmit_queue(sk); } EXPORT_SYMBOL(tcp_simple_retransmit); static void tcp_enter_recovery(struct sock *sk, bool ece_ack) { struct tcp_sock *tp = tcp_sk(sk); int mib_idx; if (tcp_is_reno(tp)) mib_idx = LINUX_MIB_TCPRENORECOVERY; else mib_idx = LINUX_MIB_TCPSACKRECOVERY; NET_INC_STATS(sock_net(sk), mib_idx); tp->prior_ssthresh = 0; tcp_init_undo(tp); if (!tcp_in_cwnd_reduction(sk)) { if (!ece_ack) tp->prior_ssthresh = tcp_current_ssthresh(sk); tcp_init_cwnd_reduction(sk); } tcp_set_ca_state(sk, TCP_CA_Recovery); } /* Process an ACK in CA_Loss state. Move to CA_Open if lost data are * recovered or spurious. Otherwise retransmits more on partial ACKs. */ static void tcp_process_loss(struct sock *sk, int flag, bool is_dupack, int *rexmit) { struct tcp_sock *tp = tcp_sk(sk); bool recovered = !before(tp->snd_una, tp->high_seq); if ((flag & FLAG_SND_UNA_ADVANCED) && tcp_try_undo_loss(sk, false)) return; if (tp->frto) { /* F-RTO RFC5682 sec 3.1 (sack enhanced version). */ /* Step 3.b. A timeout is spurious if not all data are * lost, i.e., never-retransmitted data are (s)acked. */ if ((flag & FLAG_ORIG_SACK_ACKED) && tcp_try_undo_loss(sk, true)) return; if (after(tp->snd_nxt, tp->high_seq)) { if (flag & FLAG_DATA_SACKED || is_dupack) tp->frto = 0; /* Step 3.a. loss was real */ } else if (flag & FLAG_SND_UNA_ADVANCED && !recovered) { tp->high_seq = tp->snd_nxt; /* Step 2.b. Try send new data (but deferred until cwnd * is updated in tcp_ack()). Otherwise fall back to * the conventional recovery. */ if (tcp_send_head(sk) && after(tcp_wnd_end(tp), tp->snd_nxt)) { *rexmit = REXMIT_NEW; return; } tp->frto = 0; } } if (recovered) { /* F-RTO RFC5682 sec 3.1 step 2.a and 1st part of step 3.a */ tcp_try_undo_recovery(sk); return; } if (tcp_is_reno(tp)) { /* A Reno DUPACK means new data in F-RTO step 2.b above are * delivered. Lower inflight to clock out (re)tranmissions. */ if (after(tp->snd_nxt, tp->high_seq) && is_dupack) tcp_add_reno_sack(sk); else if (flag & FLAG_SND_UNA_ADVANCED) tcp_reset_reno_sack(tp); } *rexmit = REXMIT_LOST; } /* Undo during fast recovery after partial ACK. */ static bool tcp_try_undo_partial(struct sock *sk, const int acked) { struct tcp_sock *tp = tcp_sk(sk); if (tp->undo_marker && tcp_packet_delayed(tp)) { /* Plain luck! Hole if filled with delayed * packet, rather than with a retransmit. */ tcp_update_reordering(sk, tcp_fackets_out(tp) + acked, 1); /* We are getting evidence that the reordering degree is higher * than we realized. If there are no retransmits out then we * can undo. Otherwise we clock out new packets but do not * mark more packets lost or retransmit more. */ if (tp->retrans_out) return true; if (!tcp_any_retrans_done(sk)) tp->retrans_stamp = 0; DBGUNDO(sk, "partial recovery"); tcp_undo_cwnd_reduction(sk, true); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPARTIALUNDO); tcp_try_keep_open(sk); return true; } return false; } /* Process an event, which can update packets-in-flight not trivially. * Main goal of this function is to calculate new estimate for left_out, * taking into account both packets sitting in receiver's buffer and * packets lost by network. * * Besides that it updates the congestion state when packet loss or ECN * is detected. But it does not reduce the cwnd, it is done by the * congestion control later. * * It does _not_ decide what to send, it is made in function * tcp_xmit_retransmit_queue(). */ static void tcp_fastretrans_alert(struct sock *sk, const int acked, bool is_dupack, int *ack_flag, int *rexmit) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int fast_rexmit = 0, flag = *ack_flag; bool do_lost = is_dupack || ((flag & FLAG_DATA_SACKED) && (tcp_fackets_out(tp) > tp->reordering)); if (WARN_ON(!tp->packets_out && tp->sacked_out)) tp->sacked_out = 0; if (WARN_ON(!tp->sacked_out && tp->fackets_out)) tp->fackets_out = 0; /* Now state machine starts. * A. ECE, hence prohibit cwnd undoing, the reduction is required. */ if (flag & FLAG_ECE) tp->prior_ssthresh = 0; /* B. In all the states check for reneging SACKs. */ if (tcp_check_sack_reneging(sk, flag)) return; /* C. Check consistency of the current state. */ tcp_verify_left_out(tp); /* D. Check state exit conditions. State can be terminated * when high_seq is ACKed. */ if (icsk->icsk_ca_state == TCP_CA_Open) { WARN_ON(tp->retrans_out != 0); tp->retrans_stamp = 0; } else if (!before(tp->snd_una, tp->high_seq)) { switch (icsk->icsk_ca_state) { case TCP_CA_CWR: /* CWR is to be held something *above* high_seq * is ACKed for CWR bit to reach receiver. */ if (tp->snd_una != tp->high_seq) { tcp_end_cwnd_reduction(sk); tcp_set_ca_state(sk, TCP_CA_Open); } break; case TCP_CA_Recovery: if (tcp_is_reno(tp)) tcp_reset_reno_sack(tp); if (tcp_try_undo_recovery(sk)) return; tcp_end_cwnd_reduction(sk); break; } } /* Use RACK to detect loss */ if (sysctl_tcp_recovery & TCP_RACK_LOST_RETRANS && tcp_rack_mark_lost(sk)) { flag |= FLAG_LOST_RETRANS; *ack_flag |= FLAG_LOST_RETRANS; } /* E. Process state. */ switch (icsk->icsk_ca_state) { case TCP_CA_Recovery: if (!(flag & FLAG_SND_UNA_ADVANCED)) { if (tcp_is_reno(tp) && is_dupack) tcp_add_reno_sack(sk); } else { if (tcp_try_undo_partial(sk, acked)) return; /* Partial ACK arrived. Force fast retransmit. */ do_lost = tcp_is_reno(tp) || tcp_fackets_out(tp) > tp->reordering; } if (tcp_try_undo_dsack(sk)) { tcp_try_keep_open(sk); return; } break; case TCP_CA_Loss: tcp_process_loss(sk, flag, is_dupack, rexmit); if (icsk->icsk_ca_state != TCP_CA_Open && !(flag & FLAG_LOST_RETRANS)) return; /* Change state if cwnd is undone or retransmits are lost */ default: if (tcp_is_reno(tp)) { if (flag & FLAG_SND_UNA_ADVANCED) tcp_reset_reno_sack(tp); if (is_dupack) tcp_add_reno_sack(sk); } if (icsk->icsk_ca_state <= TCP_CA_Disorder) tcp_try_undo_dsack(sk); if (!tcp_time_to_recover(sk, flag)) { tcp_try_to_open(sk, flag); return; } /* MTU probe failure: don't reduce cwnd */ if (icsk->icsk_ca_state < TCP_CA_CWR && icsk->icsk_mtup.probe_size && tp->snd_una == tp->mtu_probe.probe_seq_start) { tcp_mtup_probe_failed(sk); /* Restores the reduction we did in tcp_mtup_probe() */ tp->snd_cwnd++; tcp_simple_retransmit(sk); return; } /* Otherwise enter Recovery state */ tcp_enter_recovery(sk, (flag & FLAG_ECE)); fast_rexmit = 1; } if (do_lost) tcp_update_scoreboard(sk, fast_rexmit); *rexmit = REXMIT_LOST; } /* Kathleen Nichols' algorithm for tracking the minimum value of * a data stream over some fixed time interval. (E.g., the minimum * RTT over the past five minutes.) It uses constant space and constant * time per update yet almost always delivers the same minimum as an * implementation that has to keep all the data in the window. * * The algorithm keeps track of the best, 2nd best & 3rd best min * values, maintaining an invariant that the measurement time of the * n'th best >= n-1'th best. It also makes sure that the three values * are widely separated in the time window since that bounds the worse * case error when that data is monotonically increasing over the window. * * Upon getting a new min, we can forget everything earlier because it * has no value - the new min is <= everything else in the window by * definition and it's the most recent. So we restart fresh on every new min * and overwrites 2nd & 3rd choices. The same property holds for 2nd & 3rd * best. */ static void tcp_update_rtt_min(struct sock *sk, u32 rtt_us) { const u32 now = tcp_time_stamp, wlen = sysctl_tcp_min_rtt_wlen * HZ; struct rtt_meas *m = tcp_sk(sk)->rtt_min; struct rtt_meas rttm = { .rtt = likely(rtt_us) ? rtt_us : jiffies_to_usecs(1), .ts = now, }; u32 elapsed; /* Check if the new measurement updates the 1st, 2nd, or 3rd choices */ if (unlikely(rttm.rtt <= m[0].rtt)) m[0] = m[1] = m[2] = rttm; else if (rttm.rtt <= m[1].rtt) m[1] = m[2] = rttm; else if (rttm.rtt <= m[2].rtt) m[2] = rttm; elapsed = now - m[0].ts; if (unlikely(elapsed > wlen)) { /* Passed entire window without a new min so make 2nd choice * the new min & 3rd choice the new 2nd. So forth and so on. */ m[0] = m[1]; m[1] = m[2]; m[2] = rttm; if (now - m[0].ts > wlen) { m[0] = m[1]; m[1] = rttm; if (now - m[0].ts > wlen) m[0] = rttm; } } else if (m[1].ts == m[0].ts && elapsed > wlen / 4) { /* Passed a quarter of the window without a new min so * take 2nd choice from the 2nd quarter of the window. */ m[2] = m[1] = rttm; } else if (m[2].ts == m[1].ts && elapsed > wlen / 2) { /* Passed half the window without a new min so take the 3rd * choice from the last half of the window. */ m[2] = rttm; } } static inline bool tcp_ack_update_rtt(struct sock *sk, const int flag, long seq_rtt_us, long sack_rtt_us, long ca_rtt_us) { const struct tcp_sock *tp = tcp_sk(sk); /* Prefer RTT measured from ACK's timing to TS-ECR. This is because * broken middle-boxes or peers may corrupt TS-ECR fields. But * Karn's algorithm forbids taking RTT if some retransmitted data * is acked (RFC6298). */ if (seq_rtt_us < 0) seq_rtt_us = sack_rtt_us; /* RTTM Rule: A TSecr value received in a segment is used to * update the averaged RTT measurement only if the segment * acknowledges some new data, i.e., only if it advances the * left edge of the send window. * See draft-ietf-tcplw-high-performance-00, section 3.3. */ if (seq_rtt_us < 0 && tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr && flag & FLAG_ACKED) seq_rtt_us = ca_rtt_us = jiffies_to_usecs(tcp_time_stamp - tp->rx_opt.rcv_tsecr); if (seq_rtt_us < 0) return false; /* ca_rtt_us >= 0 is counting on the invariant that ca_rtt_us is * always taken together with ACK, SACK, or TS-opts. Any negative * values will be skipped with the seq_rtt_us < 0 check above. */ tcp_update_rtt_min(sk, ca_rtt_us); tcp_rtt_estimator(sk, seq_rtt_us); tcp_set_rto(sk); /* RFC6298: only reset backoff on valid RTT measurement. */ inet_csk(sk)->icsk_backoff = 0; return true; } /* Compute time elapsed between (last) SYNACK and the ACK completing 3WHS. */ void tcp_synack_rtt_meas(struct sock *sk, struct request_sock *req) { long rtt_us = -1L; if (req && !req->num_retrans && tcp_rsk(req)->snt_synack.v64) { struct skb_mstamp now; skb_mstamp_get(&now); rtt_us = skb_mstamp_us_delta(&now, &tcp_rsk(req)->snt_synack); } tcp_ack_update_rtt(sk, FLAG_SYN_ACKED, rtt_us, -1L, rtt_us); } static void tcp_cong_avoid(struct sock *sk, u32 ack, u32 acked) { const struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_ca_ops->cong_avoid(sk, ack, acked); tcp_sk(sk)->snd_cwnd_stamp = tcp_time_stamp; } /* Restart timer after forward progress on connection. * RFC2988 recommends to restart timer to now+rto. */ void tcp_rearm_rto(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); /* If the retrans timer is currently being used by Fast Open * for SYN-ACK retrans purpose, stay put. */ if (tp->fastopen_rsk) return; if (!tp->packets_out) { inet_csk_clear_xmit_timer(sk, ICSK_TIME_RETRANS); } else { u32 rto = inet_csk(sk)->icsk_rto; /* Offset the time elapsed after installing regular RTO */ if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) { struct sk_buff *skb = tcp_write_queue_head(sk); const u32 rto_time_stamp = tcp_skb_timestamp(skb) + rto; s32 delta = (s32)(rto_time_stamp - tcp_time_stamp); /* delta may not be positive if the socket is locked * when the retrans timer fires and is rescheduled. */ if (delta > 0) rto = delta; } inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, rto, TCP_RTO_MAX); } } /* This function is called when the delayed ER timer fires. TCP enters * fast recovery and performs fast-retransmit. */ void tcp_resume_early_retransmit(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); tcp_rearm_rto(sk); /* Stop if ER is disabled after the delayed ER timer is scheduled */ if (!tp->do_early_retrans) return; tcp_enter_recovery(sk, false); tcp_update_scoreboard(sk, 1); tcp_xmit_retransmit_queue(sk); } /* If we get here, the whole TSO packet has not been acked. */ static u32 tcp_tso_acked(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); u32 packets_acked; BUG_ON(!after(TCP_SKB_CB(skb)->end_seq, tp->snd_una)); packets_acked = tcp_skb_pcount(skb); if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) return 0; packets_acked -= tcp_skb_pcount(skb); if (packets_acked) { BUG_ON(tcp_skb_pcount(skb) == 0); BUG_ON(!before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)); } return packets_acked; } static void tcp_ack_tstamp(struct sock *sk, struct sk_buff *skb, u32 prior_snd_una) { const struct skb_shared_info *shinfo; /* Avoid cache line misses to get skb_shinfo() and shinfo->tx_flags */ if (likely(!TCP_SKB_CB(skb)->txstamp_ack)) return; shinfo = skb_shinfo(skb); if (!before(shinfo->tskey, prior_snd_una) && before(shinfo->tskey, tcp_sk(sk)->snd_una)) __skb_tstamp_tx(skb, NULL, sk, SCM_TSTAMP_ACK); } /* Remove acknowledged frames from the retransmission queue. If our packet * is before the ack sequence we can discard it as it's confirmed to have * arrived at the other end. */ static int tcp_clean_rtx_queue(struct sock *sk, int prior_fackets, u32 prior_snd_una, int *acked, struct tcp_sacktag_state *sack) { const struct inet_connection_sock *icsk = inet_csk(sk); struct skb_mstamp first_ackt, last_ackt, now; struct tcp_sock *tp = tcp_sk(sk); u32 prior_sacked = tp->sacked_out; u32 reord = tp->packets_out; bool fully_acked = true; long sack_rtt_us = -1L; long seq_rtt_us = -1L; long ca_rtt_us = -1L; struct sk_buff *skb; u32 pkts_acked = 0; bool rtt_update; int flag = 0; first_ackt.v64 = 0; while ((skb = tcp_write_queue_head(sk)) && skb != tcp_send_head(sk)) { struct tcp_skb_cb *scb = TCP_SKB_CB(skb); u8 sacked = scb->sacked; u32 acked_pcount; tcp_ack_tstamp(sk, skb, prior_snd_una); /* Determine how many packets and what bytes were acked, tso and else */ if (after(scb->end_seq, tp->snd_una)) { if (tcp_skb_pcount(skb) == 1 || !after(tp->snd_una, scb->seq)) break; acked_pcount = tcp_tso_acked(sk, skb); if (!acked_pcount) break; fully_acked = false; } else { /* Speedup tcp_unlink_write_queue() and next loop */ prefetchw(skb->next); acked_pcount = tcp_skb_pcount(skb); } if (unlikely(sacked & TCPCB_RETRANS)) { if (sacked & TCPCB_SACKED_RETRANS) tp->retrans_out -= acked_pcount; flag |= FLAG_RETRANS_DATA_ACKED; } else if (!(sacked & TCPCB_SACKED_ACKED)) { last_ackt = skb->skb_mstamp; WARN_ON_ONCE(last_ackt.v64 == 0); if (!first_ackt.v64) first_ackt = last_ackt; reord = min(pkts_acked, reord); if (!after(scb->end_seq, tp->high_seq)) flag |= FLAG_ORIG_SACK_ACKED; } if (sacked & TCPCB_SACKED_ACKED) { tp->sacked_out -= acked_pcount; } else if (tcp_is_sack(tp)) { tp->delivered += acked_pcount; if (!tcp_skb_spurious_retrans(tp, skb)) tcp_rack_advance(tp, &skb->skb_mstamp, sacked); } if (sacked & TCPCB_LOST) tp->lost_out -= acked_pcount; tp->packets_out -= acked_pcount; pkts_acked += acked_pcount; /* Initial outgoing SYN's get put onto the write_queue * just like anything else we transmit. It is not * true data, and if we misinform our callers that * this ACK acks real data, we will erroneously exit * connection startup slow start one packet too * quickly. This is severely frowned upon behavior. */ if (likely(!(scb->tcp_flags & TCPHDR_SYN))) { flag |= FLAG_DATA_ACKED; } else { flag |= FLAG_SYN_ACKED; tp->retrans_stamp = 0; } if (!fully_acked) break; tcp_unlink_write_queue(skb, sk); sk_wmem_free_skb(sk, skb); if (unlikely(skb == tp->retransmit_skb_hint)) tp->retransmit_skb_hint = NULL; if (unlikely(skb == tp->lost_skb_hint)) tp->lost_skb_hint = NULL; } if (likely(between(tp->snd_up, prior_snd_una, tp->snd_una))) tp->snd_up = tp->snd_una; if (skb && (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED)) flag |= FLAG_SACK_RENEGING; skb_mstamp_get(&now); if (likely(first_ackt.v64) && !(flag & FLAG_RETRANS_DATA_ACKED)) { seq_rtt_us = skb_mstamp_us_delta(&now, &first_ackt); ca_rtt_us = skb_mstamp_us_delta(&now, &last_ackt); } if (sack->first_sackt.v64) { sack_rtt_us = skb_mstamp_us_delta(&now, &sack->first_sackt); ca_rtt_us = skb_mstamp_us_delta(&now, &sack->last_sackt); } rtt_update = tcp_ack_update_rtt(sk, flag, seq_rtt_us, sack_rtt_us, ca_rtt_us); if (flag & FLAG_ACKED) { tcp_rearm_rto(sk); if (unlikely(icsk->icsk_mtup.probe_size && !after(tp->mtu_probe.probe_seq_end, tp->snd_una))) { tcp_mtup_probe_success(sk); } if (tcp_is_reno(tp)) { tcp_remove_reno_sacks(sk, pkts_acked); } else { int delta; /* Non-retransmitted hole got filled? That's reordering */ if (reord < prior_fackets) tcp_update_reordering(sk, tp->fackets_out - reord, 0); delta = tcp_is_fack(tp) ? pkts_acked : prior_sacked - tp->sacked_out; tp->lost_cnt_hint -= min(tp->lost_cnt_hint, delta); } tp->fackets_out -= min(pkts_acked, tp->fackets_out); } else if (skb && rtt_update && sack_rtt_us >= 0 && sack_rtt_us > skb_mstamp_us_delta(&now, &skb->skb_mstamp)) { /* Do not re-arm RTO if the sack RTT is measured from data sent * after when the head was last (re)transmitted. Otherwise the * timeout may continue to extend in loss recovery. */ tcp_rearm_rto(sk); } if (icsk->icsk_ca_ops->pkts_acked) { struct ack_sample sample = { .pkts_acked = pkts_acked, .rtt_us = ca_rtt_us }; icsk->icsk_ca_ops->pkts_acked(sk, &sample); } #if FASTRETRANS_DEBUG > 0 WARN_ON((int)tp->sacked_out < 0); WARN_ON((int)tp->lost_out < 0); WARN_ON((int)tp->retrans_out < 0); if (!tp->packets_out && tcp_is_sack(tp)) { icsk = inet_csk(sk); if (tp->lost_out) { pr_debug("Leak l=%u %d\n", tp->lost_out, icsk->icsk_ca_state); tp->lost_out = 0; } if (tp->sacked_out) { pr_debug("Leak s=%u %d\n", tp->sacked_out, icsk->icsk_ca_state); tp->sacked_out = 0; } if (tp->retrans_out) { pr_debug("Leak r=%u %d\n", tp->retrans_out, icsk->icsk_ca_state); tp->retrans_out = 0; } } #endif *acked = pkts_acked; return flag; } static void tcp_ack_probe(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); /* Was it a usable window open? */ if (!after(TCP_SKB_CB(tcp_send_head(sk))->end_seq, tcp_wnd_end(tp))) { icsk->icsk_backoff = 0; inet_csk_clear_xmit_timer(sk, ICSK_TIME_PROBE0); /* Socket must be waked up by subsequent tcp_data_snd_check(). * This function is not for random using! */ } else { unsigned long when = tcp_probe0_when(sk, TCP_RTO_MAX); inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0, when, TCP_RTO_MAX); } } static inline bool tcp_ack_is_dubious(const struct sock *sk, const int flag) { return !(flag & FLAG_NOT_DUP) || (flag & FLAG_CA_ALERT) || inet_csk(sk)->icsk_ca_state != TCP_CA_Open; } /* Decide wheather to run the increase function of congestion control. */ static inline bool tcp_may_raise_cwnd(const struct sock *sk, const int flag) { /* If reordering is high then always grow cwnd whenever data is * delivered regardless of its ordering. Otherwise stay conservative * and only grow cwnd on in-order delivery (RFC5681). A stretched ACK w/ * new SACK or ECE mark may first advance cwnd here and later reduce * cwnd in tcp_fastretrans_alert() based on more states. */ if (tcp_sk(sk)->reordering > sock_net(sk)->ipv4.sysctl_tcp_reordering) return flag & FLAG_FORWARD_PROGRESS; return flag & FLAG_DATA_ACKED; } /* The "ultimate" congestion control function that aims to replace the rigid * cwnd increase and decrease control (tcp_cong_avoid,tcp_*cwnd_reduction). * It's called toward the end of processing an ACK with precise rate * information. All transmission or retransmission are delayed afterwards. */ static void tcp_cong_control(struct sock *sk, u32 ack, u32 acked_sacked, int flag) { if (tcp_in_cwnd_reduction(sk)) { /* Reduce cwnd if state mandates */ tcp_cwnd_reduction(sk, acked_sacked, flag); } else if (tcp_may_raise_cwnd(sk, flag)) { /* Advance cwnd if state allows */ tcp_cong_avoid(sk, ack, acked_sacked); } tcp_update_pacing_rate(sk); } /* Check that window update is acceptable. * The function assumes that snd_una<=ack<=snd_next. */ static inline bool tcp_may_update_window(const struct tcp_sock *tp, const u32 ack, const u32 ack_seq, const u32 nwin) { return after(ack, tp->snd_una) || after(ack_seq, tp->snd_wl1) || (ack_seq == tp->snd_wl1 && nwin > tp->snd_wnd); } /* If we update tp->snd_una, also update tp->bytes_acked */ static void tcp_snd_una_update(struct tcp_sock *tp, u32 ack) { u32 delta = ack - tp->snd_una; sock_owned_by_me((struct sock *)tp); u64_stats_update_begin_raw(&tp->syncp); tp->bytes_acked += delta; u64_stats_update_end_raw(&tp->syncp); tp->snd_una = ack; } /* If we update tp->rcv_nxt, also update tp->bytes_received */ static void tcp_rcv_nxt_update(struct tcp_sock *tp, u32 seq) { u32 delta = seq - tp->rcv_nxt; sock_owned_by_me((struct sock *)tp); u64_stats_update_begin_raw(&tp->syncp); tp->bytes_received += delta; u64_stats_update_end_raw(&tp->syncp); tp->rcv_nxt = seq; } /* Update our send window. * * Window update algorithm, described in RFC793/RFC1122 (used in linux-2.2 * and in FreeBSD. NetBSD's one is even worse.) is wrong. */ static int tcp_ack_update_window(struct sock *sk, const struct sk_buff *skb, u32 ack, u32 ack_seq) { struct tcp_sock *tp = tcp_sk(sk); int flag = 0; u32 nwin = ntohs(tcp_hdr(skb)->window); if (likely(!tcp_hdr(skb)->syn)) nwin <<= tp->rx_opt.snd_wscale; if (tcp_may_update_window(tp, ack, ack_seq, nwin)) { flag |= FLAG_WIN_UPDATE; tcp_update_wl(tp, ack_seq); if (tp->snd_wnd != nwin) { tp->snd_wnd = nwin; /* Note, it is the only place, where * fast path is recovered for sending TCP. */ tp->pred_flags = 0; tcp_fast_path_check(sk); if (tcp_send_head(sk)) tcp_slow_start_after_idle_check(sk); if (nwin > tp->max_window) { tp->max_window = nwin; tcp_sync_mss(sk, inet_csk(sk)->icsk_pmtu_cookie); } } } tcp_snd_una_update(tp, ack); return flag; } /* Return true if we're currently rate-limiting out-of-window ACKs and * thus shouldn't send a dupack right now. We rate-limit dupacks in * response to out-of-window SYNs or ACKs to mitigate ACK loops or DoS * attacks that send repeated SYNs or ACKs for the same connection. To * do this, we do not send a duplicate SYNACK or ACK if the remote * endpoint is sending out-of-window SYNs or pure ACKs at a high rate. */ bool tcp_oow_rate_limited(struct net *net, const struct sk_buff *skb, int mib_idx, u32 *last_oow_ack_time) { /* Data packets without SYNs are not likely part of an ACK loop. */ if ((TCP_SKB_CB(skb)->seq != TCP_SKB_CB(skb)->end_seq) && !tcp_hdr(skb)->syn) goto not_rate_limited; if (*last_oow_ack_time) { s32 elapsed = (s32)(tcp_time_stamp - *last_oow_ack_time); if (0 <= elapsed && elapsed < sysctl_tcp_invalid_ratelimit) { NET_INC_STATS(net, mib_idx); return true; /* rate-limited: don't send yet! */ } } *last_oow_ack_time = tcp_time_stamp; not_rate_limited: return false; /* not rate-limited: go ahead, send dupack now! */ } /* RFC 5961 7 [ACK Throttling] */ static void tcp_send_challenge_ack(struct sock *sk, const struct sk_buff *skb) { /* unprotected vars, we dont care of overwrites */ static u32 challenge_timestamp; static unsigned int challenge_count; struct tcp_sock *tp = tcp_sk(sk); u32 count, now; /* First check our per-socket dupack rate limit. */ if (tcp_oow_rate_limited(sock_net(sk), skb, LINUX_MIB_TCPACKSKIPPEDCHALLENGE, &tp->last_oow_ack_time)) return; /* Then check host-wide RFC 5961 rate limit. */ now = jiffies / HZ; if (now != challenge_timestamp) { u32 half = (sysctl_tcp_challenge_ack_limit + 1) >> 1; challenge_timestamp = now; WRITE_ONCE(challenge_count, half + prandom_u32_max(sysctl_tcp_challenge_ack_limit)); } count = READ_ONCE(challenge_count); if (count > 0) { WRITE_ONCE(challenge_count, count - 1); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPCHALLENGEACK); tcp_send_ack(sk); } } static void tcp_store_ts_recent(struct tcp_sock *tp) { tp->rx_opt.ts_recent = tp->rx_opt.rcv_tsval; tp->rx_opt.ts_recent_stamp = get_seconds(); } static void tcp_replace_ts_recent(struct tcp_sock *tp, u32 seq) { if (tp->rx_opt.saw_tstamp && !after(seq, tp->rcv_wup)) { /* PAWS bug workaround wrt. ACK frames, the PAWS discard * extra check below makes sure this can only happen * for pure ACK frames. -DaveM * * Not only, also it occurs for expired timestamps. */ if (tcp_paws_check(&tp->rx_opt, 0)) tcp_store_ts_recent(tp); } } /* This routine deals with acks during a TLP episode. * We mark the end of a TLP episode on receiving TLP dupack or when * ack is after tlp_high_seq. * Ref: loss detection algorithm in draft-dukkipati-tcpm-tcp-loss-probe. */ static void tcp_process_tlp_ack(struct sock *sk, u32 ack, int flag) { struct tcp_sock *tp = tcp_sk(sk); if (before(ack, tp->tlp_high_seq)) return; if (flag & FLAG_DSACKING_ACK) { /* This DSACK means original and TLP probe arrived; no loss */ tp->tlp_high_seq = 0; } else if (after(ack, tp->tlp_high_seq)) { /* ACK advances: there was a loss, so reduce cwnd. Reset * tlp_high_seq in tcp_init_cwnd_reduction() */ tcp_init_cwnd_reduction(sk); tcp_set_ca_state(sk, TCP_CA_CWR); tcp_end_cwnd_reduction(sk); tcp_try_keep_open(sk); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPLOSSPROBERECOVERY); } else if (!(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP | FLAG_DATA_SACKED))) { /* Pure dupack: original and TLP probe arrived; no loss */ tp->tlp_high_seq = 0; } } static inline void tcp_in_ack_event(struct sock *sk, u32 flags) { const struct inet_connection_sock *icsk = inet_csk(sk); if (icsk->icsk_ca_ops->in_ack_event) icsk->icsk_ca_ops->in_ack_event(sk, flags); } /* Congestion control has updated the cwnd already. So if we're in * loss recovery then now we do any new sends (for FRTO) or * retransmits (for CA_Loss or CA_recovery) that make sense. */ static void tcp_xmit_recovery(struct sock *sk, int rexmit) { struct tcp_sock *tp = tcp_sk(sk); if (rexmit == REXMIT_NONE) return; if (unlikely(rexmit == 2)) { __tcp_push_pending_frames(sk, tcp_current_mss(sk), TCP_NAGLE_OFF); if (after(tp->snd_nxt, tp->high_seq)) return; tp->frto = 0; } tcp_xmit_retransmit_queue(sk); } /* This routine deals with incoming acks, but not outgoing ones. */ static int tcp_ack(struct sock *sk, const struct sk_buff *skb, int flag) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct tcp_sacktag_state sack_state; u32 prior_snd_una = tp->snd_una; u32 ack_seq = TCP_SKB_CB(skb)->seq; u32 ack = TCP_SKB_CB(skb)->ack_seq; bool is_dupack = false; u32 prior_fackets; int prior_packets = tp->packets_out; u32 prior_delivered = tp->delivered; int acked = 0; /* Number of packets newly acked */ int rexmit = REXMIT_NONE; /* Flag to (re)transmit to recover losses */ sack_state.first_sackt.v64 = 0; /* We very likely will need to access write queue head. */ prefetchw(sk->sk_write_queue.next); /* If the ack is older than previous acks * then we can probably ignore it. */ if (before(ack, prior_snd_una)) { /* RFC 5961 5.2 [Blind Data Injection Attack].[Mitigation] */ if (before(ack, prior_snd_una - tp->max_window)) { tcp_send_challenge_ack(sk, skb); return -1; } goto old_ack; } /* If the ack includes data we haven't sent yet, discard * this segment (RFC793 Section 3.9). */ if (after(ack, tp->snd_nxt)) goto invalid_ack; if (icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) tcp_rearm_rto(sk); if (after(ack, prior_snd_una)) { flag |= FLAG_SND_UNA_ADVANCED; icsk->icsk_retransmits = 0; } prior_fackets = tp->fackets_out; /* ts_recent update must be made after we are sure that the packet * is in window. */ if (flag & FLAG_UPDATE_TS_RECENT) tcp_replace_ts_recent(tp, TCP_SKB_CB(skb)->seq); if (!(flag & FLAG_SLOWPATH) && after(ack, prior_snd_una)) { /* Window is constant, pure forward advance. * No more checks are required. * Note, we use the fact that SND.UNA>=SND.WL2. */ tcp_update_wl(tp, ack_seq); tcp_snd_una_update(tp, ack); flag |= FLAG_WIN_UPDATE; tcp_in_ack_event(sk, CA_ACK_WIN_UPDATE); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPACKS); } else { u32 ack_ev_flags = CA_ACK_SLOWPATH; if (ack_seq != TCP_SKB_CB(skb)->end_seq) flag |= FLAG_DATA; else NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPPUREACKS); flag |= tcp_ack_update_window(sk, skb, ack, ack_seq); if (TCP_SKB_CB(skb)->sacked) flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una, &sack_state); if (tcp_ecn_rcv_ecn_echo(tp, tcp_hdr(skb))) { flag |= FLAG_ECE; ack_ev_flags |= CA_ACK_ECE; } if (flag & FLAG_WIN_UPDATE) ack_ev_flags |= CA_ACK_WIN_UPDATE; tcp_in_ack_event(sk, ack_ev_flags); } /* We passed data and got it acked, remove any soft error * log. Something worked... */ sk->sk_err_soft = 0; icsk->icsk_probes_out = 0; tp->rcv_tstamp = tcp_time_stamp; if (!prior_packets) goto no_queue; /* See if we can take anything off of the retransmit queue. */ flag |= tcp_clean_rtx_queue(sk, prior_fackets, prior_snd_una, &acked, &sack_state); if (tcp_ack_is_dubious(sk, flag)) { is_dupack = !(flag & (FLAG_SND_UNA_ADVANCED | FLAG_NOT_DUP)); tcp_fastretrans_alert(sk, acked, is_dupack, &flag, &rexmit); } if (tp->tlp_high_seq) tcp_process_tlp_ack(sk, ack, flag); if ((flag & FLAG_FORWARD_PROGRESS) || !(flag & FLAG_NOT_DUP)) { struct dst_entry *dst = __sk_dst_get(sk); if (dst) dst_confirm(dst); } if (icsk->icsk_pending == ICSK_TIME_RETRANS) tcp_schedule_loss_probe(sk); tcp_cong_control(sk, ack, tp->delivered - prior_delivered, flag); tcp_xmit_recovery(sk, rexmit); return 1; no_queue: /* If data was DSACKed, see if we can undo a cwnd reduction. */ if (flag & FLAG_DSACKING_ACK) tcp_fastretrans_alert(sk, acked, is_dupack, &flag, &rexmit); /* If this ack opens up a zero window, clear backoff. It was * being used to time the probes, and is probably far higher than * it needs to be for normal retransmission. */ if (tcp_send_head(sk)) tcp_ack_probe(sk); if (tp->tlp_high_seq) tcp_process_tlp_ack(sk, ack, flag); return 1; invalid_ack: SOCK_DEBUG(sk, "Ack %u after %u:%u\n", ack, tp->snd_una, tp->snd_nxt); return -1; old_ack: /* If data was SACKed, tag it and see if we should send more data. * If data was DSACKed, see if we can undo a cwnd reduction. */ if (TCP_SKB_CB(skb)->sacked) { flag |= tcp_sacktag_write_queue(sk, skb, prior_snd_una, &sack_state); tcp_fastretrans_alert(sk, acked, is_dupack, &flag, &rexmit); tcp_xmit_recovery(sk, rexmit); } SOCK_DEBUG(sk, "Ack %u before %u:%u\n", ack, tp->snd_una, tp->snd_nxt); return 0; } static void tcp_parse_fastopen_option(int len, const unsigned char *cookie, bool syn, struct tcp_fastopen_cookie *foc, bool exp_opt) { /* Valid only in SYN or SYN-ACK with an even length. */ if (!foc || !syn || len < 0 || (len & 1)) return; if (len >= TCP_FASTOPEN_COOKIE_MIN && len <= TCP_FASTOPEN_COOKIE_MAX) memcpy(foc->val, cookie, len); else if (len != 0) len = -1; foc->len = len; foc->exp = exp_opt; } /* Look for tcp options. Normally only called on SYN and SYNACK packets. * But, this can also be called on packets in the established flow when * the fast version below fails. */ void tcp_parse_options(const struct sk_buff *skb, struct tcp_options_received *opt_rx, int estab, struct tcp_fastopen_cookie *foc) { const unsigned char *ptr; const struct tcphdr *th = tcp_hdr(skb); int length = (th->doff * 4) - sizeof(struct tcphdr); ptr = (const unsigned char *)(th + 1); opt_rx->saw_tstamp = 0; while (length > 0) { int opcode = *ptr++; int opsize; switch (opcode) { case TCPOPT_EOL: return; case TCPOPT_NOP: /* Ref: RFC 793 section 3.1 */ length--; continue; default: opsize = *ptr++; if (opsize < 2) /* "silly options" */ return; if (opsize > length) return; /* don't parse partial options */ switch (opcode) { case TCPOPT_MSS: if (opsize == TCPOLEN_MSS && th->syn && !estab) { u16 in_mss = get_unaligned_be16(ptr); if (in_mss) { if (opt_rx->user_mss && opt_rx->user_mss < in_mss) in_mss = opt_rx->user_mss; opt_rx->mss_clamp = in_mss; } } break; case TCPOPT_WINDOW: if (opsize == TCPOLEN_WINDOW && th->syn && !estab && sysctl_tcp_window_scaling) { __u8 snd_wscale = *(__u8 *)ptr; opt_rx->wscale_ok = 1; if (snd_wscale > 14) { net_info_ratelimited("%s: Illegal window scaling value %d >14 received\n", __func__, snd_wscale); snd_wscale = 14; } opt_rx->snd_wscale = snd_wscale; } break; case TCPOPT_TIMESTAMP: if ((opsize == TCPOLEN_TIMESTAMP) && ((estab && opt_rx->tstamp_ok) || (!estab && sysctl_tcp_timestamps))) { opt_rx->saw_tstamp = 1; opt_rx->rcv_tsval = get_unaligned_be32(ptr); opt_rx->rcv_tsecr = get_unaligned_be32(ptr + 4); } break; case TCPOPT_SACK_PERM: if (opsize == TCPOLEN_SACK_PERM && th->syn && !estab && sysctl_tcp_sack) { opt_rx->sack_ok = TCP_SACK_SEEN; tcp_sack_reset(opt_rx); } break; case TCPOPT_SACK: if ((opsize >= (TCPOLEN_SACK_BASE + TCPOLEN_SACK_PERBLOCK)) && !((opsize - TCPOLEN_SACK_BASE) % TCPOLEN_SACK_PERBLOCK) && opt_rx->sack_ok) { TCP_SKB_CB(skb)->sacked = (ptr - 2) - (unsigned char *)th; } break; #ifdef CONFIG_TCP_MD5SIG case TCPOPT_MD5SIG: /* * The MD5 Hash has already been * checked (see tcp_v{4,6}_do_rcv()). */ break; #endif case TCPOPT_FASTOPEN: tcp_parse_fastopen_option( opsize - TCPOLEN_FASTOPEN_BASE, ptr, th->syn, foc, false); break; case TCPOPT_EXP: /* Fast Open option shares code 254 using a * 16 bits magic number. */ if (opsize >= TCPOLEN_EXP_FASTOPEN_BASE && get_unaligned_be16(ptr) == TCPOPT_FASTOPEN_MAGIC) tcp_parse_fastopen_option(opsize - TCPOLEN_EXP_FASTOPEN_BASE, ptr + 2, th->syn, foc, true); break; } ptr += opsize-2; length -= opsize; } } } EXPORT_SYMBOL(tcp_parse_options); static bool tcp_parse_aligned_timestamp(struct tcp_sock *tp, const struct tcphdr *th) { const __be32 *ptr = (const __be32 *)(th + 1); if (*ptr == htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP)) { tp->rx_opt.saw_tstamp = 1; ++ptr; tp->rx_opt.rcv_tsval = ntohl(*ptr); ++ptr; if (*ptr) tp->rx_opt.rcv_tsecr = ntohl(*ptr) - tp->tsoffset; else tp->rx_opt.rcv_tsecr = 0; return true; } return false; } /* Fast parse options. This hopes to only see timestamps. * If it is wrong it falls back on tcp_parse_options(). */ static bool tcp_fast_parse_options(const struct sk_buff *skb, const struct tcphdr *th, struct tcp_sock *tp) { /* In the spirit of fast parsing, compare doff directly to constant * values. Because equality is used, short doff can be ignored here. */ if (th->doff == (sizeof(*th) / 4)) { tp->rx_opt.saw_tstamp = 0; return false; } else if (tp->rx_opt.tstamp_ok && th->doff == ((sizeof(*th) + TCPOLEN_TSTAMP_ALIGNED) / 4)) { if (tcp_parse_aligned_timestamp(tp, th)) return true; } tcp_parse_options(skb, &tp->rx_opt, 1, NULL); if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tp->rx_opt.rcv_tsecr -= tp->tsoffset; return true; } #ifdef CONFIG_TCP_MD5SIG /* * Parse MD5 Signature option */ const u8 *tcp_parse_md5sig_option(const struct tcphdr *th) { int length = (th->doff << 2) - sizeof(*th); const u8 *ptr = (const u8 *)(th + 1); /* If the TCP option is too short, we can short cut */ if (length < TCPOLEN_MD5SIG) return NULL; while (length > 0) { int opcode = *ptr++; int opsize; switch (opcode) { case TCPOPT_EOL: return NULL; case TCPOPT_NOP: length--; continue; default: opsize = *ptr++; if (opsize < 2 || opsize > length) return NULL; if (opcode == TCPOPT_MD5SIG) return opsize == TCPOLEN_MD5SIG ? ptr : NULL; } ptr += opsize - 2; length -= opsize; } return NULL; } EXPORT_SYMBOL(tcp_parse_md5sig_option); #endif /* Sorry, PAWS as specified is broken wrt. pure-ACKs -DaveM * * It is not fatal. If this ACK does _not_ change critical state (seqs, window) * it can pass through stack. So, the following predicate verifies that * this segment is not used for anything but congestion avoidance or * fast retransmit. Moreover, we even are able to eliminate most of such * second order effects, if we apply some small "replay" window (~RTO) * to timestamp space. * * All these measures still do not guarantee that we reject wrapped ACKs * on networks with high bandwidth, when sequence space is recycled fastly, * but it guarantees that such events will be very rare and do not affect * connection seriously. This doesn't look nice, but alas, PAWS is really * buggy extension. * * [ Later note. Even worse! It is buggy for segments _with_ data. RFC * states that events when retransmit arrives after original data are rare. * It is a blatant lie. VJ forgot about fast retransmit! 8)8) It is * the biggest problem on large power networks even with minor reordering. * OK, let's give it small replay window. If peer clock is even 1hz, it is safe * up to bandwidth of 18Gigabit/sec. 8) ] */ static int tcp_disordered_ack(const struct sock *sk, const struct sk_buff *skb) { const struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); u32 seq = TCP_SKB_CB(skb)->seq; u32 ack = TCP_SKB_CB(skb)->ack_seq; return (/* 1. Pure ACK with correct sequence number. */ (th->ack && seq == TCP_SKB_CB(skb)->end_seq && seq == tp->rcv_nxt) && /* 2. ... and duplicate ACK. */ ack == tp->snd_una && /* 3. ... and does not update window. */ !tcp_may_update_window(tp, ack, seq, ntohs(th->window) << tp->rx_opt.snd_wscale) && /* 4. ... and sits in replay window. */ (s32)(tp->rx_opt.ts_recent - tp->rx_opt.rcv_tsval) <= (inet_csk(sk)->icsk_rto * 1024) / HZ); } static inline bool tcp_paws_discard(const struct sock *sk, const struct sk_buff *skb) { const struct tcp_sock *tp = tcp_sk(sk); return !tcp_paws_check(&tp->rx_opt, TCP_PAWS_WINDOW) && !tcp_disordered_ack(sk, skb); } /* Check segment sequence number for validity. * * Segment controls are considered valid, if the segment * fits to the window after truncation to the window. Acceptability * of data (and SYN, FIN, of course) is checked separately. * See tcp_data_queue(), for example. * * Also, controls (RST is main one) are accepted using RCV.WUP instead * of RCV.NXT. Peer still did not advance his SND.UNA when we * delayed ACK, so that hisSND.UNA<=ourRCV.WUP. * (borrowed from freebsd) */ static inline bool tcp_sequence(const struct tcp_sock *tp, u32 seq, u32 end_seq) { return !before(end_seq, tp->rcv_wup) && !after(seq, tp->rcv_nxt + tcp_receive_window(tp)); } /* When we get a reset we do this. */ void tcp_reset(struct sock *sk) { /* We want the right error as BSD sees it (and indeed as we do). */ switch (sk->sk_state) { case TCP_SYN_SENT: sk->sk_err = ECONNREFUSED; break; case TCP_CLOSE_WAIT: sk->sk_err = EPIPE; break; case TCP_CLOSE: return; default: sk->sk_err = ECONNRESET; } /* This barrier is coupled with smp_rmb() in tcp_poll() */ smp_wmb(); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_error_report(sk); tcp_done(sk); } /* * Process the FIN bit. This now behaves as it is supposed to work * and the FIN takes effect when it is validly part of sequence * space. Not before when we get holes. * * If we are ESTABLISHED, a received fin moves us to CLOSE-WAIT * (and thence onto LAST-ACK and finally, CLOSE, we never enter * TIME-WAIT) * * If we are in FINWAIT-1, a received FIN indicates simultaneous * close and we go into CLOSING (and later onto TIME-WAIT) * * If we are in FINWAIT-2, a received FIN moves us to TIME-WAIT. */ void tcp_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); inet_csk_schedule_ack(sk); sk->sk_shutdown |= RCV_SHUTDOWN; sock_set_flag(sk, SOCK_DONE); switch (sk->sk_state) { case TCP_SYN_RECV: case TCP_ESTABLISHED: /* Move to CLOSE_WAIT */ tcp_set_state(sk, TCP_CLOSE_WAIT); inet_csk(sk)->icsk_ack.pingpong = 1; break; case TCP_CLOSE_WAIT: case TCP_CLOSING: /* Received a retransmission of the FIN, do * nothing. */ break; case TCP_LAST_ACK: /* RFC793: Remain in the LAST-ACK state. */ break; case TCP_FIN_WAIT1: /* This case occurs when a simultaneous close * happens, we must ack the received FIN and * enter the CLOSING state. */ tcp_send_ack(sk); tcp_set_state(sk, TCP_CLOSING); break; case TCP_FIN_WAIT2: /* Received a FIN -- send ACK and enter TIME_WAIT. */ tcp_send_ack(sk); tcp_time_wait(sk, TCP_TIME_WAIT, 0); break; default: /* Only TCP_LISTEN and TCP_CLOSE are left, in these * cases we should never reach this piece of code. */ pr_err("%s: Impossible, sk->sk_state=%d\n", __func__, sk->sk_state); break; } /* It _is_ possible, that we have something out-of-order _after_ FIN. * Probably, we should reset in this case. For now drop them. */ __skb_queue_purge(&tp->out_of_order_queue); if (tcp_is_sack(tp)) tcp_sack_reset(&tp->rx_opt); sk_mem_reclaim(sk); if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); /* Do not send POLL_HUP for half duplex close. */ if (sk->sk_shutdown == SHUTDOWN_MASK || sk->sk_state == TCP_CLOSE) sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_HUP); else sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN); } } static inline bool tcp_sack_extend(struct tcp_sack_block *sp, u32 seq, u32 end_seq) { if (!after(seq, sp->end_seq) && !after(sp->start_seq, end_seq)) { if (before(seq, sp->start_seq)) sp->start_seq = seq; if (after(end_seq, sp->end_seq)) sp->end_seq = end_seq; return true; } return false; } static void tcp_dsack_set(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_is_sack(tp) && sysctl_tcp_dsack) { int mib_idx; if (before(seq, tp->rcv_nxt)) mib_idx = LINUX_MIB_TCPDSACKOLDSENT; else mib_idx = LINUX_MIB_TCPDSACKOFOSENT; NET_INC_STATS(sock_net(sk), mib_idx); tp->rx_opt.dsack = 1; tp->duplicate_sack[0].start_seq = seq; tp->duplicate_sack[0].end_seq = end_seq; } } static void tcp_dsack_extend(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); if (!tp->rx_opt.dsack) tcp_dsack_set(sk, seq, end_seq); else tcp_sack_extend(tp->duplicate_sack, seq, end_seq); } static void tcp_send_dupack(struct sock *sk, const struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST); tcp_enter_quickack_mode(sk); if (tcp_is_sack(tp) && sysctl_tcp_dsack) { u32 end_seq = TCP_SKB_CB(skb)->end_seq; if (after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) end_seq = tp->rcv_nxt; tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, end_seq); } } tcp_send_ack(sk); } /* These routines update the SACK block as out-of-order packets arrive or * in-order packets close up the sequence space. */ static void tcp_sack_maybe_coalesce(struct tcp_sock *tp) { int this_sack; struct tcp_sack_block *sp = &tp->selective_acks[0]; struct tcp_sack_block *swalk = sp + 1; /* See if the recent change to the first SACK eats into * or hits the sequence space of other SACK blocks, if so coalesce. */ for (this_sack = 1; this_sack < tp->rx_opt.num_sacks;) { if (tcp_sack_extend(sp, swalk->start_seq, swalk->end_seq)) { int i; /* Zap SWALK, by moving every further SACK up by one slot. * Decrease num_sacks. */ tp->rx_opt.num_sacks--; for (i = this_sack; i < tp->rx_opt.num_sacks; i++) sp[i] = sp[i + 1]; continue; } this_sack++, swalk++; } } static void tcp_sack_new_ofo_skb(struct sock *sk, u32 seq, u32 end_seq) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_sack_block *sp = &tp->selective_acks[0]; int cur_sacks = tp->rx_opt.num_sacks; int this_sack; if (!cur_sacks) goto new_sack; for (this_sack = 0; this_sack < cur_sacks; this_sack++, sp++) { if (tcp_sack_extend(sp, seq, end_seq)) { /* Rotate this_sack to the first one. */ for (; this_sack > 0; this_sack--, sp--) swap(*sp, *(sp - 1)); if (cur_sacks > 1) tcp_sack_maybe_coalesce(tp); return; } } /* Could not find an adjacent existing SACK, build a new one, * put it at the front, and shift everyone else down. We * always know there is at least one SACK present already here. * * If the sack array is full, forget about the last one. */ if (this_sack >= TCP_NUM_SACKS) { this_sack--; tp->rx_opt.num_sacks--; sp--; } for (; this_sack > 0; this_sack--, sp--) *sp = *(sp - 1); new_sack: /* Build the new head SACK, and we're done. */ sp->start_seq = seq; sp->end_seq = end_seq; tp->rx_opt.num_sacks++; } /* RCV.NXT advances, some SACKs should be eaten. */ static void tcp_sack_remove(struct tcp_sock *tp) { struct tcp_sack_block *sp = &tp->selective_acks[0]; int num_sacks = tp->rx_opt.num_sacks; int this_sack; /* Empty ofo queue, hence, all the SACKs are eaten. Clear. */ if (skb_queue_empty(&tp->out_of_order_queue)) { tp->rx_opt.num_sacks = 0; return; } for (this_sack = 0; this_sack < num_sacks;) { /* Check if the start of the sack is covered by RCV.NXT. */ if (!before(tp->rcv_nxt, sp->start_seq)) { int i; /* RCV.NXT must cover all the block! */ WARN_ON(before(tp->rcv_nxt, sp->end_seq)); /* Zap this SACK, by moving forward any other SACKS. */ for (i = this_sack+1; i < num_sacks; i++) tp->selective_acks[i-1] = tp->selective_acks[i]; num_sacks--; continue; } this_sack++; sp++; } tp->rx_opt.num_sacks = num_sacks; } /** * tcp_try_coalesce - try to merge skb to prior one * @sk: socket * @to: prior buffer * @from: buffer to add in queue * @fragstolen: pointer to boolean * * Before queueing skb @from after @to, try to merge them * to reduce overall memory use and queue lengths, if cost is small. * Packets in ofo or receive queues can stay a long time. * Better try to coalesce them right now to avoid future collapses. * Returns true if caller should free @from instead of queueing it */ static bool tcp_try_coalesce(struct sock *sk, struct sk_buff *to, struct sk_buff *from, bool *fragstolen) { int delta; *fragstolen = false; /* Its possible this segment overlaps with prior segment in queue */ if (TCP_SKB_CB(from)->seq != TCP_SKB_CB(to)->end_seq) return false; if (!skb_try_coalesce(to, from, fragstolen, &delta)) return false; atomic_add(delta, &sk->sk_rmem_alloc); sk_mem_charge(sk, delta); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOALESCE); TCP_SKB_CB(to)->end_seq = TCP_SKB_CB(from)->end_seq; TCP_SKB_CB(to)->ack_seq = TCP_SKB_CB(from)->ack_seq; TCP_SKB_CB(to)->tcp_flags |= TCP_SKB_CB(from)->tcp_flags; return true; } static void tcp_drop(struct sock *sk, struct sk_buff *skb) { sk_drops_add(sk, skb); __kfree_skb(skb); } /* This one checks to see if we can put data from the * out_of_order queue into the receive_queue. */ static void tcp_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); __u32 dsack_high = tp->rcv_nxt; struct sk_buff *skb, *tail; bool fragstolen, eaten; while ((skb = skb_peek(&tp->out_of_order_queue)) != NULL) { if (after(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; if (before(TCP_SKB_CB(skb)->seq, dsack_high)) { __u32 dsack = dsack_high; if (before(TCP_SKB_CB(skb)->end_seq, dsack_high)) dsack_high = TCP_SKB_CB(skb)->end_seq; tcp_dsack_extend(sk, TCP_SKB_CB(skb)->seq, dsack); } __skb_unlink(skb, &tp->out_of_order_queue); if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) { SOCK_DEBUG(sk, "ofo packet was already received\n"); tcp_drop(sk, skb); continue; } SOCK_DEBUG(sk, "ofo requeuing : rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); tail = skb_peek_tail(&sk->sk_receive_queue); eaten = tail && tcp_try_coalesce(sk, tail, skb, &fragstolen); tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq); if (!eaten) __skb_queue_tail(&sk->sk_receive_queue, skb); if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) tcp_fin(sk); if (eaten) kfree_skb_partial(skb, fragstolen); } } static bool tcp_prune_ofo_queue(struct sock *sk); static int tcp_prune_queue(struct sock *sk); static int tcp_try_rmem_schedule(struct sock *sk, struct sk_buff *skb, unsigned int size) { if (atomic_read(&sk->sk_rmem_alloc) > sk->sk_rcvbuf || !sk_rmem_schedule(sk, skb, size)) { if (tcp_prune_queue(sk) < 0) return -1; if (!sk_rmem_schedule(sk, skb, size)) { if (!tcp_prune_ofo_queue(sk)) return -1; if (!sk_rmem_schedule(sk, skb, size)) return -1; } } return 0; } static void tcp_data_queue_ofo(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb1; u32 seq, end_seq; tcp_ecn_check_ce(tp, skb); if (unlikely(tcp_try_rmem_schedule(sk, skb, skb->truesize))) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFODROP); tcp_drop(sk, skb); return; } /* Disable header prediction. */ tp->pred_flags = 0; inet_csk_schedule_ack(sk); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOQUEUE); SOCK_DEBUG(sk, "out of order segment: rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); skb1 = skb_peek_tail(&tp->out_of_order_queue); if (!skb1) { /* Initial out of order segment, build 1 SACK. */ if (tcp_is_sack(tp)) { tp->rx_opt.num_sacks = 1; tp->selective_acks[0].start_seq = TCP_SKB_CB(skb)->seq; tp->selective_acks[0].end_seq = TCP_SKB_CB(skb)->end_seq; } __skb_queue_head(&tp->out_of_order_queue, skb); goto end; } seq = TCP_SKB_CB(skb)->seq; end_seq = TCP_SKB_CB(skb)->end_seq; if (seq == TCP_SKB_CB(skb1)->end_seq) { bool fragstolen; if (!tcp_try_coalesce(sk, skb1, skb, &fragstolen)) { __skb_queue_after(&tp->out_of_order_queue, skb1, skb); } else { tcp_grow_window(sk, skb); kfree_skb_partial(skb, fragstolen); skb = NULL; } if (!tp->rx_opt.num_sacks || tp->selective_acks[0].end_seq != seq) goto add_sack; /* Common case: data arrive in order after hole. */ tp->selective_acks[0].end_seq = end_seq; goto end; } /* Find place to insert this segment. */ while (1) { if (!after(TCP_SKB_CB(skb1)->seq, seq)) break; if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) { skb1 = NULL; break; } skb1 = skb_queue_prev(&tp->out_of_order_queue, skb1); } /* Do skb overlap to previous one? */ if (skb1 && before(seq, TCP_SKB_CB(skb1)->end_seq)) { if (!after(end_seq, TCP_SKB_CB(skb1)->end_seq)) { /* All the bits are present. Drop. */ NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE); tcp_drop(sk, skb); skb = NULL; tcp_dsack_set(sk, seq, end_seq); goto add_sack; } if (after(seq, TCP_SKB_CB(skb1)->seq)) { /* Partial overlap. */ tcp_dsack_set(sk, seq, TCP_SKB_CB(skb1)->end_seq); } else { if (skb_queue_is_first(&tp->out_of_order_queue, skb1)) skb1 = NULL; else skb1 = skb_queue_prev( &tp->out_of_order_queue, skb1); } } if (!skb1) __skb_queue_head(&tp->out_of_order_queue, skb); else __skb_queue_after(&tp->out_of_order_queue, skb1, skb); /* And clean segments covered by new one as whole. */ while (!skb_queue_is_last(&tp->out_of_order_queue, skb)) { skb1 = skb_queue_next(&tp->out_of_order_queue, skb); if (!after(end_seq, TCP_SKB_CB(skb1)->seq)) break; if (before(end_seq, TCP_SKB_CB(skb1)->end_seq)) { tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, end_seq); break; } __skb_unlink(skb1, &tp->out_of_order_queue); tcp_dsack_extend(sk, TCP_SKB_CB(skb1)->seq, TCP_SKB_CB(skb1)->end_seq); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPOFOMERGE); tcp_drop(sk, skb1); } add_sack: if (tcp_is_sack(tp)) tcp_sack_new_ofo_skb(sk, seq, end_seq); end: if (skb) { tcp_grow_window(sk, skb); skb_set_owner_r(skb, sk); } } static int __must_check tcp_queue_rcv(struct sock *sk, struct sk_buff *skb, int hdrlen, bool *fragstolen) { int eaten; struct sk_buff *tail = skb_peek_tail(&sk->sk_receive_queue); __skb_pull(skb, hdrlen); eaten = (tail && tcp_try_coalesce(sk, tail, skb, fragstolen)) ? 1 : 0; tcp_rcv_nxt_update(tcp_sk(sk), TCP_SKB_CB(skb)->end_seq); if (!eaten) { __skb_queue_tail(&sk->sk_receive_queue, skb); skb_set_owner_r(skb, sk); } return eaten; } int tcp_send_rcvq(struct sock *sk, struct msghdr *msg, size_t size) { struct sk_buff *skb; int err = -ENOMEM; int data_len = 0; bool fragstolen; if (size == 0) return 0; if (size > PAGE_SIZE) { int npages = min_t(size_t, size >> PAGE_SHIFT, MAX_SKB_FRAGS); data_len = npages << PAGE_SHIFT; size = data_len + (size & ~PAGE_MASK); } skb = alloc_skb_with_frags(size - data_len, data_len, PAGE_ALLOC_COSTLY_ORDER, &err, sk->sk_allocation); if (!skb) goto err; skb_put(skb, size - data_len); skb->data_len = data_len; skb->len = size; if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) goto err_free; err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size); if (err) goto err_free; TCP_SKB_CB(skb)->seq = tcp_sk(sk)->rcv_nxt; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(skb)->seq + size; TCP_SKB_CB(skb)->ack_seq = tcp_sk(sk)->snd_una - 1; if (tcp_queue_rcv(sk, skb, 0, &fragstolen)) { WARN_ON_ONCE(fragstolen); /* should not happen */ __kfree_skb(skb); } return size; err_free: kfree_skb(skb); err: return err; } static void tcp_data_queue(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); bool fragstolen = false; int eaten = -1; if (TCP_SKB_CB(skb)->seq == TCP_SKB_CB(skb)->end_seq) { __kfree_skb(skb); return; } skb_dst_drop(skb); __skb_pull(skb, tcp_hdr(skb)->doff * 4); tcp_ecn_accept_cwr(tp, skb); tp->rx_opt.dsack = 0; /* Queue data for delivery to the user. * Packets in sequence go to the receive queue. * Out of sequence packets to the out_of_order_queue. */ if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) { if (tcp_receive_window(tp) == 0) goto out_of_window; /* Ok. In sequence. In window. */ if (tp->ucopy.task == current && tp->copied_seq == tp->rcv_nxt && tp->ucopy.len && sock_owned_by_user(sk) && !tp->urg_data) { int chunk = min_t(unsigned int, skb->len, tp->ucopy.len); __set_current_state(TASK_RUNNING); if (!skb_copy_datagram_msg(skb, 0, tp->ucopy.msg, chunk)) { tp->ucopy.len -= chunk; tp->copied_seq += chunk; eaten = (chunk == skb->len); tcp_rcv_space_adjust(sk); } } if (eaten <= 0) { queue_and_out: if (eaten < 0) { if (skb_queue_len(&sk->sk_receive_queue) == 0) sk_forced_mem_schedule(sk, skb->truesize); else if (tcp_try_rmem_schedule(sk, skb, skb->truesize)) goto drop; } eaten = tcp_queue_rcv(sk, skb, 0, &fragstolen); } tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq); if (skb->len) tcp_event_data_recv(sk, skb); if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) tcp_fin(sk); if (!skb_queue_empty(&tp->out_of_order_queue)) { tcp_ofo_queue(sk); /* RFC2581. 4.2. SHOULD send immediate ACK, when * gap in queue is filled. */ if (skb_queue_empty(&tp->out_of_order_queue)) inet_csk(sk)->icsk_ack.pingpong = 0; } if (tp->rx_opt.num_sacks) tcp_sack_remove(tp); tcp_fast_path_check(sk); if (eaten > 0) kfree_skb_partial(skb, fragstolen); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); return; } if (!after(TCP_SKB_CB(skb)->end_seq, tp->rcv_nxt)) { /* A retransmit, 2nd most common case. Force an immediate ack. */ NET_INC_STATS(sock_net(sk), LINUX_MIB_DELAYEDACKLOST); tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); out_of_window: tcp_enter_quickack_mode(sk); inet_csk_schedule_ack(sk); drop: tcp_drop(sk, skb); return; } /* Out of window. F.e. zero window probe. */ if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt + tcp_receive_window(tp))) goto out_of_window; tcp_enter_quickack_mode(sk); if (before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) { /* Partial packet, seq < rcv_next < end_seq */ SOCK_DEBUG(sk, "partial packet: rcv_next %X seq %X - %X\n", tp->rcv_nxt, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq); tcp_dsack_set(sk, TCP_SKB_CB(skb)->seq, tp->rcv_nxt); /* If window is closed, drop tail of packet. But after * remembering D-SACK for its head made in previous line. */ if (!tcp_receive_window(tp)) goto out_of_window; goto queue_and_out; } tcp_data_queue_ofo(sk, skb); } static struct sk_buff *tcp_collapse_one(struct sock *sk, struct sk_buff *skb, struct sk_buff_head *list) { struct sk_buff *next = NULL; if (!skb_queue_is_last(list, skb)) next = skb_queue_next(list, skb); __skb_unlink(skb, list); __kfree_skb(skb); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPRCVCOLLAPSED); return next; } /* Collapse contiguous sequence of skbs head..tail with * sequence numbers start..end. * * If tail is NULL, this means until the end of the list. * * Segments with FIN/SYN are not collapsed (only because this * simplifies code) */ static void tcp_collapse(struct sock *sk, struct sk_buff_head *list, struct sk_buff *head, struct sk_buff *tail, u32 start, u32 end) { struct sk_buff *skb, *n; bool end_of_skbs; /* First, check that queue is collapsible and find * the point where collapsing can be useful. */ skb = head; restart: end_of_skbs = true; skb_queue_walk_from_safe(list, skb, n) { if (skb == tail) break; /* No new bits? It is possible on ofo queue. */ if (!before(start, TCP_SKB_CB(skb)->end_seq)) { skb = tcp_collapse_one(sk, skb, list); if (!skb) break; goto restart; } /* The first skb to collapse is: * - not SYN/FIN and * - bloated or contains data before "start" or * overlaps to the next one. */ if (!(TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN)) && (tcp_win_from_space(skb->truesize) > skb->len || before(TCP_SKB_CB(skb)->seq, start))) { end_of_skbs = false; break; } if (!skb_queue_is_last(list, skb)) { struct sk_buff *next = skb_queue_next(list, skb); if (next != tail && TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(next)->seq) { end_of_skbs = false; break; } } /* Decided to skip this, advance start seq. */ start = TCP_SKB_CB(skb)->end_seq; } if (end_of_skbs || (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN))) return; while (before(start, end)) { int copy = min_t(int, SKB_MAX_ORDER(0, 0), end - start); struct sk_buff *nskb; nskb = alloc_skb(copy, GFP_ATOMIC); if (!nskb) return; memcpy(nskb->cb, skb->cb, sizeof(skb->cb)); TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(nskb)->end_seq = start; __skb_queue_before(list, skb, nskb); skb_set_owner_r(nskb, sk); /* Copy data, releasing collapsed skbs. */ while (copy > 0) { int offset = start - TCP_SKB_CB(skb)->seq; int size = TCP_SKB_CB(skb)->end_seq - start; BUG_ON(offset < 0); if (size > 0) { size = min(copy, size); if (skb_copy_bits(skb, offset, skb_put(nskb, size), size)) BUG(); TCP_SKB_CB(nskb)->end_seq += size; copy -= size; start += size; } if (!before(start, TCP_SKB_CB(skb)->end_seq)) { skb = tcp_collapse_one(sk, skb, list); if (!skb || skb == tail || (TCP_SKB_CB(skb)->tcp_flags & (TCPHDR_SYN | TCPHDR_FIN))) return; } } } } /* Collapse ofo queue. Algorithm: select contiguous sequence of skbs * and tcp_collapse() them until all the queue is collapsed. */ static void tcp_collapse_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = skb_peek(&tp->out_of_order_queue); struct sk_buff *head; u32 start, end; if (!skb) return; start = TCP_SKB_CB(skb)->seq; end = TCP_SKB_CB(skb)->end_seq; head = skb; for (;;) { struct sk_buff *next = NULL; if (!skb_queue_is_last(&tp->out_of_order_queue, skb)) next = skb_queue_next(&tp->out_of_order_queue, skb); skb = next; /* Segment is terminated when we see gap or when * we are at the end of all the queue. */ if (!skb || after(TCP_SKB_CB(skb)->seq, end) || before(TCP_SKB_CB(skb)->end_seq, start)) { tcp_collapse(sk, &tp->out_of_order_queue, head, skb, start, end); head = skb; if (!skb) break; /* Start new segment */ start = TCP_SKB_CB(skb)->seq; end = TCP_SKB_CB(skb)->end_seq; } else { if (before(TCP_SKB_CB(skb)->seq, start)) start = TCP_SKB_CB(skb)->seq; if (after(TCP_SKB_CB(skb)->end_seq, end)) end = TCP_SKB_CB(skb)->end_seq; } } } /* * Purge the out-of-order queue. * Return true if queue was pruned. */ static bool tcp_prune_ofo_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); bool res = false; if (!skb_queue_empty(&tp->out_of_order_queue)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_OFOPRUNED); __skb_queue_purge(&tp->out_of_order_queue); /* Reset SACK state. A conforming SACK implementation will * do the same at a timeout based retransmit. When a connection * is in a sad state like this, we care only about integrity * of the connection not performance. */ if (tp->rx_opt.sack_ok) tcp_sack_reset(&tp->rx_opt); sk_mem_reclaim(sk); res = true; } return res; } /* Reduce allocated memory if we can, trying to get * the socket within its memory limits again. * * Return less than zero if we should start dropping frames * until the socket owning process reads some of the data * to stabilize the situation. */ static int tcp_prune_queue(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); SOCK_DEBUG(sk, "prune_queue: c=%x\n", tp->copied_seq); NET_INC_STATS(sock_net(sk), LINUX_MIB_PRUNECALLED); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) tcp_clamp_window(sk); else if (tcp_under_memory_pressure(sk)) tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss); tcp_collapse_ofo_queue(sk); if (!skb_queue_empty(&sk->sk_receive_queue)) tcp_collapse(sk, &sk->sk_receive_queue, skb_peek(&sk->sk_receive_queue), NULL, tp->copied_seq, tp->rcv_nxt); sk_mem_reclaim(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* Collapsing did not help, destructive actions follow. * This must not ever occur. */ tcp_prune_ofo_queue(sk); if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf) return 0; /* If we are really being abused, tell the caller to silently * drop receive data on the floor. It will get retransmitted * and hopefully then we'll have sufficient space. */ NET_INC_STATS(sock_net(sk), LINUX_MIB_RCVPRUNED); /* Massive buffer overcommit. */ tp->pred_flags = 0; return -1; } static bool tcp_should_expand_sndbuf(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); /* If the user specified a specific send buffer setting, do * not modify it. */ if (sk->sk_userlocks & SOCK_SNDBUF_LOCK) return false; /* If we are under global TCP memory pressure, do not expand. */ if (tcp_under_memory_pressure(sk)) return false; /* If we are under soft global TCP memory pressure, do not expand. */ if (sk_memory_allocated(sk) >= sk_prot_mem_limits(sk, 0)) return false; /* If we filled the congestion window, do not expand. */ if (tcp_packets_in_flight(tp) >= tp->snd_cwnd) return false; return true; } /* When incoming ACK allowed to free some skb from write_queue, * we remember this event in flag SOCK_QUEUE_SHRUNK and wake up socket * on the exit from tcp input handler. * * PROBLEM: sndbuf expansion does not work well with largesend. */ static void tcp_new_space(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tcp_should_expand_sndbuf(sk)) { tcp_sndbuf_expand(sk); tp->snd_cwnd_stamp = tcp_time_stamp; } sk->sk_write_space(sk); } static void tcp_check_space(struct sock *sk) { if (sock_flag(sk, SOCK_QUEUE_SHRUNK)) { sock_reset_flag(sk, SOCK_QUEUE_SHRUNK); /* pairs with tcp_poll() */ smp_mb__after_atomic(); if (sk->sk_socket && test_bit(SOCK_NOSPACE, &sk->sk_socket->flags)) tcp_new_space(sk); } } static inline void tcp_data_snd_check(struct sock *sk) { tcp_push_pending_frames(sk); tcp_check_space(sk); } /* * Check if sending an ack is needed. */ static void __tcp_ack_snd_check(struct sock *sk, int ofo_possible) { struct tcp_sock *tp = tcp_sk(sk); /* More than one full frame received... */ if (((tp->rcv_nxt - tp->rcv_wup) > inet_csk(sk)->icsk_ack.rcv_mss && /* ... and right edge of window advances far enough. * (tcp_recvmsg() will send ACK otherwise). Or... */ __tcp_select_window(sk) >= tp->rcv_wnd) || /* We ACK each frame or... */ tcp_in_quickack_mode(sk) || /* We have out of order data. */ (ofo_possible && skb_peek(&tp->out_of_order_queue))) { /* Then ack it now */ tcp_send_ack(sk); } else { /* Else, send delayed ack. */ tcp_send_delayed_ack(sk); } } static inline void tcp_ack_snd_check(struct sock *sk) { if (!inet_csk_ack_scheduled(sk)) { /* We sent a data segment already. */ return; } __tcp_ack_snd_check(sk, 1); } /* * This routine is only called when we have urgent data * signaled. Its the 'slow' part of tcp_urg. It could be * moved inline now as tcp_urg is only called from one * place. We handle URGent data wrong. We have to - as * BSD still doesn't use the correction from RFC961. * For 1003.1g we should support a new option TCP_STDURG to permit * either form (or just set the sysctl tcp_stdurg). */ static void tcp_check_urg(struct sock *sk, const struct tcphdr *th) { struct tcp_sock *tp = tcp_sk(sk); u32 ptr = ntohs(th->urg_ptr); if (ptr && !sysctl_tcp_stdurg) ptr--; ptr += ntohl(th->seq); /* Ignore urgent data that we've already seen and read. */ if (after(tp->copied_seq, ptr)) return; /* Do not replay urg ptr. * * NOTE: interesting situation not covered by specs. * Misbehaving sender may send urg ptr, pointing to segment, * which we already have in ofo queue. We are not able to fetch * such data and will stay in TCP_URG_NOTYET until will be eaten * by recvmsg(). Seems, we are not obliged to handle such wicked * situations. But it is worth to think about possibility of some * DoSes using some hypothetical application level deadlock. */ if (before(ptr, tp->rcv_nxt)) return; /* Do we already have a newer (or duplicate) urgent pointer? */ if (tp->urg_data && !after(ptr, tp->urg_seq)) return; /* Tell the world about our new urgent pointer. */ sk_send_sigurg(sk); /* We may be adding urgent data when the last byte read was * urgent. To do this requires some care. We cannot just ignore * tp->copied_seq since we would read the last urgent byte again * as data, nor can we alter copied_seq until this data arrives * or we break the semantics of SIOCATMARK (and thus sockatmark()) * * NOTE. Double Dutch. Rendering to plain English: author of comment * above did something sort of send("A", MSG_OOB); send("B", MSG_OOB); * and expect that both A and B disappear from stream. This is _wrong_. * Though this happens in BSD with high probability, this is occasional. * Any application relying on this is buggy. Note also, that fix "works" * only in this artificial test. Insert some normal data between A and B and we will * decline of BSD again. Verdict: it is better to remove to trap * buggy users. */ if (tp->urg_seq == tp->copied_seq && tp->urg_data && !sock_flag(sk, SOCK_URGINLINE) && tp->copied_seq != tp->rcv_nxt) { struct sk_buff *skb = skb_peek(&sk->sk_receive_queue); tp->copied_seq++; if (skb && !before(tp->copied_seq, TCP_SKB_CB(skb)->end_seq)) { __skb_unlink(skb, &sk->sk_receive_queue); __kfree_skb(skb); } } tp->urg_data = TCP_URG_NOTYET; tp->urg_seq = ptr; /* Disable header prediction. */ tp->pred_flags = 0; } /* This is the 'fast' part of urgent handling. */ static void tcp_urg(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th) { struct tcp_sock *tp = tcp_sk(sk); /* Check if we get a new urgent pointer - normally not. */ if (th->urg) tcp_check_urg(sk, th); /* Do we wait for any urgent data? - normally not... */ if (tp->urg_data == TCP_URG_NOTYET) { u32 ptr = tp->urg_seq - ntohl(th->seq) + (th->doff * 4) - th->syn; /* Is the urgent pointer pointing into this packet? */ if (ptr < skb->len) { u8 tmp; if (skb_copy_bits(skb, ptr, &tmp, 1)) BUG(); tp->urg_data = TCP_URG_VALID | tmp; if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk); } } } static int tcp_copy_to_iovec(struct sock *sk, struct sk_buff *skb, int hlen) { struct tcp_sock *tp = tcp_sk(sk); int chunk = skb->len - hlen; int err; if (skb_csum_unnecessary(skb)) err = skb_copy_datagram_msg(skb, hlen, tp->ucopy.msg, chunk); else err = skb_copy_and_csum_datagram_msg(skb, hlen, tp->ucopy.msg); if (!err) { tp->ucopy.len -= chunk; tp->copied_seq += chunk; tcp_rcv_space_adjust(sk); } return err; } /* Does PAWS and seqno based validation of an incoming segment, flags will * play significant role here. */ static bool tcp_validate_incoming(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, int syn_inerr) { struct tcp_sock *tp = tcp_sk(sk); /* RFC1323: H1. Apply PAWS check first. */ if (tcp_fast_parse_options(skb, th, tp) && tp->rx_opt.saw_tstamp && tcp_paws_discard(sk, skb)) { if (!th->rst) { NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSESTABREJECTED); if (!tcp_oow_rate_limited(sock_net(sk), skb, LINUX_MIB_TCPACKSKIPPEDPAWS, &tp->last_oow_ack_time)) tcp_send_dupack(sk, skb); goto discard; } /* Reset is accepted even if it did not pass PAWS. */ } /* Step 1: check sequence number */ if (!tcp_sequence(tp, TCP_SKB_CB(skb)->seq, TCP_SKB_CB(skb)->end_seq)) { /* RFC793, page 37: "In all states except SYN-SENT, all reset * (RST) segments are validated by checking their SEQ-fields." * And page 69: "If an incoming segment is not acceptable, * an acknowledgment should be sent in reply (unless the RST * bit is set, if so drop the segment and return)". */ if (!th->rst) { if (th->syn) goto syn_challenge; if (!tcp_oow_rate_limited(sock_net(sk), skb, LINUX_MIB_TCPACKSKIPPEDSEQ, &tp->last_oow_ack_time)) tcp_send_dupack(sk, skb); } goto discard; } /* Step 2: check RST bit */ if (th->rst) { /* RFC 5961 3.2 : * If sequence number exactly matches RCV.NXT, then * RESET the connection * else * Send a challenge ACK */ if (TCP_SKB_CB(skb)->seq == tp->rcv_nxt) tcp_reset(sk); else tcp_send_challenge_ack(sk, skb); goto discard; } /* step 3: check security and precedence [ignored] */ /* step 4: Check for a SYN * RFC 5961 4.2 : Send a challenge ack */ if (th->syn) { syn_challenge: if (syn_inerr) TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPSYNCHALLENGE); tcp_send_challenge_ack(sk, skb); goto discard; } return true; discard: tcp_drop(sk, skb); return false; } /* * TCP receive function for the ESTABLISHED state. * * It is split into a fast path and a slow path. The fast path is * disabled when: * - A zero window was announced from us - zero window probing * is only handled properly in the slow path. * - Out of order segments arrived. * - Urgent data is expected. * - There is no buffer space left * - Unexpected TCP flags/window values/header lengths are received * (detected by checking the TCP header against pred_flags) * - Data is sent in both directions. Fast path only supports pure senders * or pure receivers (this means either the sequence number or the ack * value must stay constant) * - Unexpected TCP option. * * When these conditions are not satisfied it drops into a standard * receive procedure patterned after RFC793 to handle all cases. * The first three cases are guaranteed by proper pred_flags setting, * the rest is checked inline. Fast processing is turned on in * tcp_data_queue when everything is OK. */ void tcp_rcv_established(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th, unsigned int len) { struct tcp_sock *tp = tcp_sk(sk); if (unlikely(!sk->sk_rx_dst)) inet_csk(sk)->icsk_af_ops->sk_rx_dst_set(sk, skb); /* * Header prediction. * The code loosely follows the one in the famous * "30 instruction TCP receive" Van Jacobson mail. * * Van's trick is to deposit buffers into socket queue * on a device interrupt, to call tcp_recv function * on the receive process context and checksum and copy * the buffer to user space. smart... * * Our current scheme is not silly either but we take the * extra cost of the net_bh soft interrupt processing... * We do checksum and copy also but from device to kernel. */ tp->rx_opt.saw_tstamp = 0; /* pred_flags is 0xS?10 << 16 + snd_wnd * if header_prediction is to be made * 'S' will always be tp->tcp_header_len >> 2 * '?' will be 0 for the fast path, otherwise pred_flags is 0 to * turn it off (when there are holes in the receive * space for instance) * PSH flag is ignored. */ if ((tcp_flag_word(th) & TCP_HP_BITS) == tp->pred_flags && TCP_SKB_CB(skb)->seq == tp->rcv_nxt && !after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) { int tcp_header_len = tp->tcp_header_len; /* Timestamp header prediction: tcp_header_len * is automatically equal to th->doff*4 due to pred_flags * match. */ /* Check timestamp */ if (tcp_header_len == sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) { /* No? Slow path! */ if (!tcp_parse_aligned_timestamp(tp, th)) goto slow_path; /* If PAWS failed, check it more carefully in slow path */ if ((s32)(tp->rx_opt.rcv_tsval - tp->rx_opt.ts_recent) < 0) goto slow_path; /* DO NOT update ts_recent here, if checksum fails * and timestamp was corrupted part, it will result * in a hung connection since we will drop all * future packets due to the PAWS test. */ } if (len <= tcp_header_len) { /* Bulk data transfer: sender */ if (len == tcp_header_len) { /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); /* We know that such packets are checksummed * on entry. */ tcp_ack(sk, skb, 0); __kfree_skb(skb); tcp_data_snd_check(sk); return; } else { /* Header too small */ TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); goto discard; } } else { int eaten = 0; bool fragstolen = false; if (tp->ucopy.task == current && tp->copied_seq == tp->rcv_nxt && len - tcp_header_len <= tp->ucopy.len && sock_owned_by_user(sk)) { __set_current_state(TASK_RUNNING); if (!tcp_copy_to_iovec(sk, skb, tcp_header_len)) { /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); tcp_rcv_rtt_measure_ts(sk, skb); __skb_pull(skb, tcp_header_len); tcp_rcv_nxt_update(tp, TCP_SKB_CB(skb)->end_seq); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPHITSTOUSER); eaten = 1; } } if (!eaten) { if (tcp_checksum_complete(skb)) goto csum_error; if ((int)skb->truesize > sk->sk_forward_alloc) goto step5; /* Predicted packet is in window by definition. * seq == rcv_nxt and rcv_wup <= rcv_nxt. * Hence, check seq<=rcv_wup reduces to: */ if (tcp_header_len == (sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED) && tp->rcv_nxt == tp->rcv_wup) tcp_store_ts_recent(tp); tcp_rcv_rtt_measure_ts(sk, skb); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPHPHITS); /* Bulk data transfer: receiver */ eaten = tcp_queue_rcv(sk, skb, tcp_header_len, &fragstolen); } tcp_event_data_recv(sk, skb); if (TCP_SKB_CB(skb)->ack_seq != tp->snd_una) { /* Well, only one small jumplet in fast path... */ tcp_ack(sk, skb, FLAG_DATA); tcp_data_snd_check(sk); if (!inet_csk_ack_scheduled(sk)) goto no_ack; } __tcp_ack_snd_check(sk, 0); no_ack: if (eaten) kfree_skb_partial(skb, fragstolen); sk->sk_data_ready(sk); return; } } slow_path: if (len < (th->doff << 2) || tcp_checksum_complete(skb)) goto csum_error; if (!th->ack && !th->rst && !th->syn) goto discard; /* * Standard slow path. */ if (!tcp_validate_incoming(sk, skb, th, 1)) return; step5: if (tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) < 0) goto discard; tcp_rcv_rtt_measure_ts(sk, skb); /* Process urgent data. */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ tcp_data_queue(sk, skb); tcp_data_snd_check(sk); tcp_ack_snd_check(sk); return; csum_error: TCP_INC_STATS(sock_net(sk), TCP_MIB_CSUMERRORS); TCP_INC_STATS(sock_net(sk), TCP_MIB_INERRS); discard: tcp_drop(sk, skb); } EXPORT_SYMBOL(tcp_rcv_established); void tcp_finish_connect(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); tcp_set_state(sk, TCP_ESTABLISHED); if (skb) { icsk->icsk_af_ops->sk_rx_dst_set(sk, skb); security_inet_conn_established(sk, skb); } /* Make sure socket is routed, for correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); tcp_init_metrics(sk); tcp_init_congestion_control(sk); /* Prevent spurious tcp_cwnd_restart() on first data * packet. */ tp->lsndtime = tcp_time_stamp; tcp_init_buffer_space(sk); if (sock_flag(sk, SOCK_KEEPOPEN)) inet_csk_reset_keepalive_timer(sk, keepalive_time_when(tp)); if (!tp->rx_opt.snd_wscale) __tcp_fast_path_on(tp, tp->snd_wnd); else tp->pred_flags = 0; if (!sock_flag(sk, SOCK_DEAD)) { sk->sk_state_change(sk); sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); } } static bool tcp_rcv_fastopen_synack(struct sock *sk, struct sk_buff *synack, struct tcp_fastopen_cookie *cookie) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *data = tp->syn_data ? tcp_write_queue_head(sk) : NULL; u16 mss = tp->rx_opt.mss_clamp, try_exp = 0; bool syn_drop = false; if (mss == tp->rx_opt.user_mss) { struct tcp_options_received opt; /* Get original SYNACK MSS value if user MSS sets mss_clamp */ tcp_clear_options(&opt); opt.user_mss = opt.mss_clamp = 0; tcp_parse_options(synack, &opt, 0, NULL); mss = opt.mss_clamp; } if (!tp->syn_fastopen) { /* Ignore an unsolicited cookie */ cookie->len = -1; } else if (tp->total_retrans) { /* SYN timed out and the SYN-ACK neither has a cookie nor * acknowledges data. Presumably the remote received only * the retransmitted (regular) SYNs: either the original * SYN-data or the corresponding SYN-ACK was dropped. */ syn_drop = (cookie->len < 0 && data); } else if (cookie->len < 0 && !tp->syn_data) { /* We requested a cookie but didn't get it. If we did not use * the (old) exp opt format then try so next time (try_exp=1). * Otherwise we go back to use the RFC7413 opt (try_exp=2). */ try_exp = tp->syn_fastopen_exp ? 2 : 1; } tcp_fastopen_cache_set(sk, mss, cookie, syn_drop, try_exp); if (data) { /* Retransmit unacked data in SYN */ tcp_for_write_queue_from(data, sk) { if (data == tcp_send_head(sk) || __tcp_retransmit_skb(sk, data, 1)) break; } tcp_rearm_rto(sk); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVEFAIL); return true; } tp->syn_data_acked = tp->syn_data; if (tp->syn_data_acked) NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVE); tcp_fastopen_add_skb(sk, synack); return false; } static int tcp_rcv_synsent_state_process(struct sock *sk, struct sk_buff *skb, const struct tcphdr *th) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct tcp_fastopen_cookie foc = { .len = -1 }; int saved_clamp = tp->rx_opt.mss_clamp; tcp_parse_options(skb, &tp->rx_opt, 0, &foc); if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr) tp->rx_opt.rcv_tsecr -= tp->tsoffset; if (th->ack) { /* rfc793: * "If the state is SYN-SENT then * first check the ACK bit * If the ACK bit is set * If SEG.ACK =< ISS, or SEG.ACK > SND.NXT, send * a reset (unless the RST bit is set, if so drop * the segment and return)" */ if (!after(TCP_SKB_CB(skb)->ack_seq, tp->snd_una) || after(TCP_SKB_CB(skb)->ack_seq, tp->snd_nxt)) goto reset_and_undo; if (tp->rx_opt.saw_tstamp && tp->rx_opt.rcv_tsecr && !between(tp->rx_opt.rcv_tsecr, tp->retrans_stamp, tcp_time_stamp)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSACTIVEREJECTED); goto reset_and_undo; } /* Now ACK is acceptable. * * "If the RST bit is set * If the ACK was acceptable then signal the user "error: * connection reset", drop the segment, enter CLOSED state, * delete TCB, and return." */ if (th->rst) { tcp_reset(sk); goto discard; } /* rfc793: * "fifth, if neither of the SYN or RST bits is set then * drop the segment and return." * * See note below! * --ANK(990513) */ if (!th->syn) goto discard_and_undo; /* rfc793: * "If the SYN bit is on ... * are acceptable then ... * (our SYN has been ACKed), change the connection * state to ESTABLISHED..." */ tcp_ecn_rcv_synack(tp, th); tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); tcp_ack(sk, skb, FLAG_SLOWPATH); /* Ok.. it's good. Set up sequence numbers and * move to established. */ tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1; /* RFC1323: The window in SYN & SYN/ACK segments is * never scaled. */ tp->snd_wnd = ntohs(th->window); if (!tp->rx_opt.wscale_ok) { tp->rx_opt.snd_wscale = tp->rx_opt.rcv_wscale = 0; tp->window_clamp = min(tp->window_clamp, 65535U); } if (tp->rx_opt.saw_tstamp) { tp->rx_opt.tstamp_ok = 1; tp->tcp_header_len = sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED; tp->advmss -= TCPOLEN_TSTAMP_ALIGNED; tcp_store_ts_recent(tp); } else { tp->tcp_header_len = sizeof(struct tcphdr); } if (tcp_is_sack(tp) && sysctl_tcp_fack) tcp_enable_fack(tp); tcp_mtup_init(sk); tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); tcp_initialize_rcv_mss(sk); /* Remember, tcp_poll() does not lock socket! * Change state from SYN-SENT only after copied_seq * is initialized. */ tp->copied_seq = tp->rcv_nxt; smp_mb(); tcp_finish_connect(sk, skb); if ((tp->syn_fastopen || tp->syn_data) && tcp_rcv_fastopen_synack(sk, skb, &foc)) return -1; if (sk->sk_write_pending || icsk->icsk_accept_queue.rskq_defer_accept || icsk->icsk_ack.pingpong) { /* Save one ACK. Data will be ready after * several ticks, if write_pending is set. * * It may be deleted, but with this feature tcpdumps * look so _wonderfully_ clever, that I was not able * to stand against the temptation 8) --ANK */ inet_csk_schedule_ack(sk); icsk->icsk_ack.lrcvtime = tcp_time_stamp; tcp_enter_quickack_mode(sk); inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK, TCP_DELACK_MAX, TCP_RTO_MAX); discard: tcp_drop(sk, skb); return 0; } else { tcp_send_ack(sk); } return -1; } /* No ACK in the segment */ if (th->rst) { /* rfc793: * "If the RST bit is set * * Otherwise (no ACK) drop the segment and return." */ goto discard_and_undo; } /* PAWS check. */ if (tp->rx_opt.ts_recent_stamp && tp->rx_opt.saw_tstamp && tcp_paws_reject(&tp->rx_opt, 0)) goto discard_and_undo; if (th->syn) { /* We see SYN without ACK. It is attempt of * simultaneous connect with crossed SYNs. * Particularly, it can be connect to self. */ tcp_set_state(sk, TCP_SYN_RECV); if (tp->rx_opt.saw_tstamp) { tp->rx_opt.tstamp_ok = 1; tcp_store_ts_recent(tp); tp->tcp_header_len = sizeof(struct tcphdr) + TCPOLEN_TSTAMP_ALIGNED; } else { tp->tcp_header_len = sizeof(struct tcphdr); } tp->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; tp->copied_seq = tp->rcv_nxt; tp->rcv_wup = TCP_SKB_CB(skb)->seq + 1; /* RFC1323: The window in SYN & SYN/ACK segments is * never scaled. */ tp->snd_wnd = ntohs(th->window); tp->snd_wl1 = TCP_SKB_CB(skb)->seq; tp->max_window = tp->snd_wnd; tcp_ecn_rcv_syn(tp, th); tcp_mtup_init(sk); tcp_sync_mss(sk, icsk->icsk_pmtu_cookie); tcp_initialize_rcv_mss(sk); tcp_send_synack(sk); #if 0 /* Note, we could accept data and URG from this segment. * There are no obstacles to make this (except that we must * either change tcp_recvmsg() to prevent it from returning data * before 3WHS completes per RFC793, or employ TCP Fast Open). * * However, if we ignore data in ACKless segments sometimes, * we have no reasons to accept it sometimes. * Also, seems the code doing it in step6 of tcp_rcv_state_process * is not flawless. So, discard packet for sanity. * Uncomment this return to process the data. */ return -1; #else goto discard; #endif } /* "fifth, if neither of the SYN or RST bits is set then * drop the segment and return." */ discard_and_undo: tcp_clear_options(&tp->rx_opt); tp->rx_opt.mss_clamp = saved_clamp; goto discard; reset_and_undo: tcp_clear_options(&tp->rx_opt); tp->rx_opt.mss_clamp = saved_clamp; return 1; } /* * This function implements the receiving procedure of RFC 793 for * all states except ESTABLISHED and TIME_WAIT. * It's called from both tcp_v4_rcv and tcp_v6_rcv and should be * address independent. */ int tcp_rcv_state_process(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); const struct tcphdr *th = tcp_hdr(skb); struct request_sock *req; int queued = 0; bool acceptable; switch (sk->sk_state) { case TCP_CLOSE: goto discard; case TCP_LISTEN: if (th->ack) return 1; if (th->rst) goto discard; if (th->syn) { if (th->fin) goto discard; if (icsk->icsk_af_ops->conn_request(sk, skb) < 0) return 1; consume_skb(skb); return 0; } goto discard; case TCP_SYN_SENT: tp->rx_opt.saw_tstamp = 0; queued = tcp_rcv_synsent_state_process(sk, skb, th); if (queued >= 0) return queued; /* Do step6 onward by hand. */ tcp_urg(sk, skb, th); __kfree_skb(skb); tcp_data_snd_check(sk); return 0; } tp->rx_opt.saw_tstamp = 0; req = tp->fastopen_rsk; if (req) { WARN_ON_ONCE(sk->sk_state != TCP_SYN_RECV && sk->sk_state != TCP_FIN_WAIT1); if (!tcp_check_req(sk, skb, req, true)) goto discard; } if (!th->ack && !th->rst && !th->syn) goto discard; if (!tcp_validate_incoming(sk, skb, th, 0)) return 0; /* step 5: check the ACK field */ acceptable = tcp_ack(sk, skb, FLAG_SLOWPATH | FLAG_UPDATE_TS_RECENT) > 0; switch (sk->sk_state) { case TCP_SYN_RECV: if (!acceptable) return 1; if (!tp->srtt_us) tcp_synack_rtt_meas(sk, req); /* Once we leave TCP_SYN_RECV, we no longer need req * so release it. */ if (req) { tp->total_retrans = req->num_retrans; reqsk_fastopen_remove(sk, req, false); } else { /* Make sure socket is routed, for correct metrics. */ icsk->icsk_af_ops->rebuild_header(sk); tcp_init_congestion_control(sk); tcp_mtup_init(sk); tp->copied_seq = tp->rcv_nxt; tcp_init_buffer_space(sk); } smp_mb(); tcp_set_state(sk, TCP_ESTABLISHED); sk->sk_state_change(sk); /* Note, that this wakeup is only for marginal crossed SYN case. * Passively open sockets are not waked up, because * sk->sk_sleep == NULL and sk->sk_socket == NULL. */ if (sk->sk_socket) sk_wake_async(sk, SOCK_WAKE_IO, POLL_OUT); tp->snd_una = TCP_SKB_CB(skb)->ack_seq; tp->snd_wnd = ntohs(th->window) << tp->rx_opt.snd_wscale; tcp_init_wl(tp, TCP_SKB_CB(skb)->seq); if (tp->rx_opt.tstamp_ok) tp->advmss -= TCPOLEN_TSTAMP_ALIGNED; if (req) { /* Re-arm the timer because data may have been sent out. * This is similar to the regular data transmission case * when new data has just been ack'ed. * * (TFO) - we could try to be more aggressive and * retransmitting any data sooner based on when they * are sent out. */ tcp_rearm_rto(sk); } else tcp_init_metrics(sk); tcp_update_pacing_rate(sk); /* Prevent spurious tcp_cwnd_restart() on first data packet */ tp->lsndtime = tcp_time_stamp; tcp_initialize_rcv_mss(sk); tcp_fast_path_on(tp); break; case TCP_FIN_WAIT1: { struct dst_entry *dst; int tmo; /* If we enter the TCP_FIN_WAIT1 state and we are a * Fast Open socket and this is the first acceptable * ACK we have received, this would have acknowledged * our SYNACK so stop the SYNACK timer. */ if (req) { /* Return RST if ack_seq is invalid. * Note that RFC793 only says to generate a * DUPACK for it but for TCP Fast Open it seems * better to treat this case like TCP_SYN_RECV * above. */ if (!acceptable) return 1; /* We no longer need the request sock. */ reqsk_fastopen_remove(sk, req, false); tcp_rearm_rto(sk); } if (tp->snd_una != tp->write_seq) break; tcp_set_state(sk, TCP_FIN_WAIT2); sk->sk_shutdown |= SEND_SHUTDOWN; dst = __sk_dst_get(sk); if (dst) dst_confirm(dst); if (!sock_flag(sk, SOCK_DEAD)) { /* Wake up lingering close() */ sk->sk_state_change(sk); break; } if (tp->linger2 < 0 || (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt))) { tcp_done(sk); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA); return 1; } tmo = tcp_fin_time(sk); if (tmo > TCP_TIMEWAIT_LEN) { inet_csk_reset_keepalive_timer(sk, tmo - TCP_TIMEWAIT_LEN); } else if (th->fin || sock_owned_by_user(sk)) { /* Bad case. We could lose such FIN otherwise. * It is not a big problem, but it looks confusing * and not so rare event. We still can lose it now, * if it spins in bh_lock_sock(), but it is really * marginal case. */ inet_csk_reset_keepalive_timer(sk, tmo); } else { tcp_time_wait(sk, TCP_FIN_WAIT2, tmo); goto discard; } break; } case TCP_CLOSING: if (tp->snd_una == tp->write_seq) { tcp_time_wait(sk, TCP_TIME_WAIT, 0); goto discard; } break; case TCP_LAST_ACK: if (tp->snd_una == tp->write_seq) { tcp_update_metrics(sk); tcp_done(sk); goto discard; } break; } /* step 6: check the URG bit */ tcp_urg(sk, skb, th); /* step 7: process the segment text */ switch (sk->sk_state) { case TCP_CLOSE_WAIT: case TCP_CLOSING: case TCP_LAST_ACK: if (!before(TCP_SKB_CB(skb)->seq, tp->rcv_nxt)) break; case TCP_FIN_WAIT1: case TCP_FIN_WAIT2: /* RFC 793 says to queue data in these states, * RFC 1122 says we MUST send a reset. * BSD 4.4 also does reset. */ if (sk->sk_shutdown & RCV_SHUTDOWN) { if (TCP_SKB_CB(skb)->end_seq != TCP_SKB_CB(skb)->seq && after(TCP_SKB_CB(skb)->end_seq - th->fin, tp->rcv_nxt)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTONDATA); tcp_reset(sk); return 1; } } /* Fall through */ case TCP_ESTABLISHED: tcp_data_queue(sk, skb); queued = 1; break; } /* tcp_data could move socket to TIME-WAIT */ if (sk->sk_state != TCP_CLOSE) { tcp_data_snd_check(sk); tcp_ack_snd_check(sk); } if (!queued) { discard: tcp_drop(sk, skb); } return 0; } EXPORT_SYMBOL(tcp_rcv_state_process); static inline void pr_drop_req(struct request_sock *req, __u16 port, int family) { struct inet_request_sock *ireq = inet_rsk(req); if (family == AF_INET) net_dbg_ratelimited("drop open request from %pI4/%u\n", &ireq->ir_rmt_addr, port); #if IS_ENABLED(CONFIG_IPV6) else if (family == AF_INET6) net_dbg_ratelimited("drop open request from %pI6/%u\n", &ireq->ir_v6_rmt_addr, port); #endif } /* RFC3168 : 6.1.1 SYN packets must not have ECT/ECN bits set * * If we receive a SYN packet with these bits set, it means a * network is playing bad games with TOS bits. In order to * avoid possible false congestion notifications, we disable * TCP ECN negotiation. * * Exception: tcp_ca wants ECN. This is required for DCTCP * congestion control: Linux DCTCP asserts ECT on all packets, * including SYN, which is most optimal solution; however, * others, such as FreeBSD do not. */ static void tcp_ecn_create_request(struct request_sock *req, const struct sk_buff *skb, const struct sock *listen_sk, const struct dst_entry *dst) { const struct tcphdr *th = tcp_hdr(skb); const struct net *net = sock_net(listen_sk); bool th_ecn = th->ece && th->cwr; bool ect, ecn_ok; u32 ecn_ok_dst; if (!th_ecn) return; ect = !INET_ECN_is_not_ect(TCP_SKB_CB(skb)->ip_dsfield); ecn_ok_dst = dst_feature(dst, DST_FEATURE_ECN_MASK); ecn_ok = net->ipv4.sysctl_tcp_ecn || ecn_ok_dst; if ((!ect && ecn_ok) || tcp_ca_needs_ecn(listen_sk) || (ecn_ok_dst & DST_FEATURE_ECN_CA)) inet_rsk(req)->ecn_ok = 1; } static void tcp_openreq_init(struct request_sock *req, const struct tcp_options_received *rx_opt, struct sk_buff *skb, const struct sock *sk) { struct inet_request_sock *ireq = inet_rsk(req); req->rsk_rcv_wnd = 0; /* So that tcp_send_synack() knows! */ req->cookie_ts = 0; tcp_rsk(req)->rcv_isn = TCP_SKB_CB(skb)->seq; tcp_rsk(req)->rcv_nxt = TCP_SKB_CB(skb)->seq + 1; skb_mstamp_get(&tcp_rsk(req)->snt_synack); tcp_rsk(req)->last_oow_ack_time = 0; req->mss = rx_opt->mss_clamp; req->ts_recent = rx_opt->saw_tstamp ? rx_opt->rcv_tsval : 0; ireq->tstamp_ok = rx_opt->tstamp_ok; ireq->sack_ok = rx_opt->sack_ok; ireq->snd_wscale = rx_opt->snd_wscale; ireq->wscale_ok = rx_opt->wscale_ok; ireq->acked = 0; ireq->ecn_ok = 0; ireq->ir_rmt_port = tcp_hdr(skb)->source; ireq->ir_num = ntohs(tcp_hdr(skb)->dest); ireq->ir_mark = inet_request_mark(sk, skb); } struct request_sock *inet_reqsk_alloc(const struct request_sock_ops *ops, struct sock *sk_listener, bool attach_listener) { struct request_sock *req = reqsk_alloc(ops, sk_listener, attach_listener); if (req) { struct inet_request_sock *ireq = inet_rsk(req); kmemcheck_annotate_bitfield(ireq, flags); ireq->opt = NULL; atomic64_set(&ireq->ir_cookie, 0); ireq->ireq_state = TCP_NEW_SYN_RECV; write_pnet(&ireq->ireq_net, sock_net(sk_listener)); ireq->ireq_family = sk_listener->sk_family; } return req; } EXPORT_SYMBOL(inet_reqsk_alloc); /* * Return true if a syncookie should be sent */ static bool tcp_syn_flood_action(const struct sock *sk, const struct sk_buff *skb, const char *proto) { struct request_sock_queue *queue = &inet_csk(sk)->icsk_accept_queue; const char *msg = "Dropping request"; bool want_cookie = false; struct net *net = sock_net(sk); #ifdef CONFIG_SYN_COOKIES if (net->ipv4.sysctl_tcp_syncookies) { msg = "Sending cookies"; want_cookie = true; __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDOCOOKIES); } else #endif __NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPREQQFULLDROP); if (!queue->synflood_warned && net->ipv4.sysctl_tcp_syncookies != 2 && xchg(&queue->synflood_warned, 1) == 0) pr_info("%s: Possible SYN flooding on port %d. %s. Check SNMP counters.\n", proto, ntohs(tcp_hdr(skb)->dest), msg); return want_cookie; } static void tcp_reqsk_record_syn(const struct sock *sk, struct request_sock *req, const struct sk_buff *skb) { if (tcp_sk(sk)->save_syn) { u32 len = skb_network_header_len(skb) + tcp_hdrlen(skb); u32 *copy; copy = kmalloc(len + sizeof(u32), GFP_ATOMIC); if (copy) { copy[0] = len; memcpy(&copy[1], skb_network_header(skb), len); req->saved_syn = copy; } } } int tcp_conn_request(struct request_sock_ops *rsk_ops, const struct tcp_request_sock_ops *af_ops, struct sock *sk, struct sk_buff *skb) { struct tcp_fastopen_cookie foc = { .len = -1 }; __u32 isn = TCP_SKB_CB(skb)->tcp_tw_isn; struct tcp_options_received tmp_opt; struct tcp_sock *tp = tcp_sk(sk); struct net *net = sock_net(sk); struct sock *fastopen_sk = NULL; struct dst_entry *dst = NULL; struct request_sock *req; bool want_cookie = false; struct flowi fl; /* TW buckets are converted to open requests without * limitations, they conserve resources and peer is * evidently real one. */ if ((net->ipv4.sysctl_tcp_syncookies == 2 || inet_csk_reqsk_queue_is_full(sk)) && !isn) { want_cookie = tcp_syn_flood_action(sk, skb, rsk_ops->slab_name); if (!want_cookie) goto drop; } /* Accept backlog is full. If we have already queued enough * of warm entries in syn queue, drop request. It is better than * clogging syn queue with openreqs with exponentially increasing * timeout. */ if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1) { NET_INC_STATS(sock_net(sk), LINUX_MIB_LISTENOVERFLOWS); goto drop; } req = inet_reqsk_alloc(rsk_ops, sk, !want_cookie); if (!req) goto drop; tcp_rsk(req)->af_specific = af_ops; tcp_clear_options(&tmp_opt); tmp_opt.mss_clamp = af_ops->mss_clamp; tmp_opt.user_mss = tp->rx_opt.user_mss; tcp_parse_options(skb, &tmp_opt, 0, want_cookie ? NULL : &foc); if (want_cookie && !tmp_opt.saw_tstamp) tcp_clear_options(&tmp_opt); tmp_opt.tstamp_ok = tmp_opt.saw_tstamp; tcp_openreq_init(req, &tmp_opt, skb, sk); /* Note: tcp_v6_init_req() might override ir_iif for link locals */ inet_rsk(req)->ir_iif = inet_request_bound_dev_if(sk, skb); af_ops->init_req(req, sk, skb); if (security_inet_conn_request(sk, skb, req)) goto drop_and_free; if (!want_cookie && !isn) { /* VJ's idea. We save last timestamp seen * from the destination in peer table, when entering * state TIME-WAIT, and check against it before * accepting new connection request. * * If "isn" is not zero, this request hit alive * timewait bucket, so that all the necessary checks * are made in the function processing timewait state. */ if (tcp_death_row.sysctl_tw_recycle) { bool strict; dst = af_ops->route_req(sk, &fl, req, &strict); if (dst && strict && !tcp_peer_is_proven(req, dst, true, tmp_opt.saw_tstamp)) { NET_INC_STATS(sock_net(sk), LINUX_MIB_PAWSPASSIVEREJECTED); goto drop_and_release; } } /* Kill the following clause, if you dislike this way. */ else if (!net->ipv4.sysctl_tcp_syncookies && (sysctl_max_syn_backlog - inet_csk_reqsk_queue_len(sk) < (sysctl_max_syn_backlog >> 2)) && !tcp_peer_is_proven(req, dst, false, tmp_opt.saw_tstamp)) { /* Without syncookies last quarter of * backlog is filled with destinations, * proven to be alive. * It means that we continue to communicate * to destinations, already remembered * to the moment of synflood. */ pr_drop_req(req, ntohs(tcp_hdr(skb)->source), rsk_ops->family); goto drop_and_release; } isn = af_ops->init_seq(skb); } if (!dst) { dst = af_ops->route_req(sk, &fl, req, NULL); if (!dst) goto drop_and_free; } tcp_ecn_create_request(req, skb, sk, dst); if (want_cookie) { isn = cookie_init_sequence(af_ops, sk, skb, &req->mss); req->cookie_ts = tmp_opt.tstamp_ok; if (!tmp_opt.tstamp_ok) inet_rsk(req)->ecn_ok = 0; } tcp_rsk(req)->snt_isn = isn; tcp_rsk(req)->txhash = net_tx_rndhash(); tcp_openreq_init_rwin(req, sk, dst); if (!want_cookie) { tcp_reqsk_record_syn(sk, req, skb); fastopen_sk = tcp_try_fastopen(sk, skb, req, &foc, dst); } if (fastopen_sk) { af_ops->send_synack(fastopen_sk, dst, &fl, req, &foc, TCP_SYNACK_FASTOPEN); /* Add the child socket directly into the accept queue */ inet_csk_reqsk_queue_add(sk, req, fastopen_sk); sk->sk_data_ready(sk); bh_unlock_sock(fastopen_sk); sock_put(fastopen_sk); } else { tcp_rsk(req)->tfo_listener = false; if (!want_cookie) inet_csk_reqsk_queue_hash_add(sk, req, TCP_TIMEOUT_INIT); af_ops->send_synack(sk, dst, &fl, req, &foc, !want_cookie ? TCP_SYNACK_NORMAL : TCP_SYNACK_COOKIE); if (want_cookie) { reqsk_free(req); return 0; } } reqsk_put(req); return 0; drop_and_release: dst_release(dst); drop_and_free: reqsk_free(req); drop: tcp_listendrop(sk); return 0; } EXPORT_SYMBOL(tcp_conn_request);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5130_0
crossvul-cpp_data_bad_3833_0
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2000-2001 Qualcomm Incorporated Copyright (C) 2009-2010 Gustavo F. Padovan <gustavo@padovan.org> Copyright (C) 2010 Google Inc. Copyright (C) 2011 ProFUSION Embedded Systems Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth L2CAP sockets. */ #include <linux/export.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include <net/bluetooth/smp.h> static const struct proto_ops l2cap_sock_ops; static void l2cap_sock_init(struct sock *sk, struct sock *parent); static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio); static int l2cap_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid && la.l2_psm) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (la.l2_psm) { __u16 psm = __le16_to_cpu(la.l2_psm); /* PSM must be odd and lsb of upper byte must be 0 */ if ((psm & 0x0101) != 0x0001) { err = -EINVAL; goto done; } /* Restrict usage of well-known PSMs */ if (psm < 0x1001 && !capable(CAP_NET_BIND_SERVICE)) { err = -EACCES; goto done; } } if (la.l2_cid) err = l2cap_add_scid(chan, __le16_to_cpu(la.l2_cid)); else err = l2cap_add_psm(chan, &la.l2_bdaddr, la.l2_psm); if (err < 0) goto done; if (__le16_to_cpu(la.l2_psm) == L2CAP_PSM_SDP || __le16_to_cpu(la.l2_psm) == L2CAP_PSM_RFCOMM) chan->sec_level = BT_SECURITY_SDP; bacpy(&bt_sk(sk)->src, &la.l2_bdaddr); chan->state = BT_BOUND; sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || alen < sizeof(addr->sa_family) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid && la.l2_psm) return -EINVAL; err = l2cap_chan_connect(chan, la.l2_psm, __le16_to_cpu(la.l2_cid), &la.l2_bdaddr, la.l2_bdaddr_type); if (err) return err; lock_sock(sk); err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); release_sock(sk); return err; } static int l2cap_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET && sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } switch (chan->mode) { case L2CAP_MODE_BASIC: break; case L2CAP_MODE_ERTM: case L2CAP_MODE_STREAMING: if (!disable_ertm) break; /* fall through */ default: err = -ENOTSUPP; goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; chan->state = BT_LISTEN; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; } static int l2cap_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock_nested(sk, SINGLE_DEPTH_NESTING); timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } nsk = bt_accept_dequeue(sk, newsock); if (nsk) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", nsk); done: release_sock(sk); return err; } static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr; struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_l2); if (peer) { la->l2_psm = chan->psm; bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst); la->l2_cid = cpu_to_le16(chan->dcid); } else { la->l2_psm = chan->sport; bacpy(&la->l2_bdaddr, &bt_sk(sk)->src); la->l2_cid = cpu_to_le16(chan->scid); } return 0; } static int l2cap_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct l2cap_options opts; struct l2cap_conninfo cinfo; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case L2CAP_OPTIONS: memset(&opts, 0, sizeof(opts)); opts.imtu = chan->imtu; opts.omtu = chan->omtu; opts.flush_to = chan->flush_to; opts.mode = chan->mode; opts.fcs = chan->fcs; opts.max_tx = chan->max_tx; opts.txwin_size = chan->tx_win; len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *) &opts, len)) err = -EFAULT; break; case L2CAP_LM: switch (chan->sec_level) { case BT_SECURITY_LOW: opt = L2CAP_LM_AUTH; break; case BT_SECURITY_MEDIUM: opt = L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT; break; case BT_SECURITY_HIGH: opt = L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT | L2CAP_LM_SECURE; break; default: opt = 0; break; } if (test_bit(FLAG_ROLE_SWITCH, &chan->flags)) opt |= L2CAP_LM_MASTER; if (test_bit(FLAG_FORCE_RELIABLE, &chan->flags)) opt |= L2CAP_LM_RELIABLE; if (put_user(opt, (u32 __user *) optval)) err = -EFAULT; break; case L2CAP_CONNINFO: if (sk->sk_state != BT_CONNECTED && !(sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags))) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = chan->conn->hcon->handle; memcpy(cinfo.dev_class, chan->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *) &cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct bt_security sec; struct bt_power pwr; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_L2CAP) return l2cap_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && chan->chan_type != L2CAP_CHAN_RAW) { err = -EINVAL; break; } memset(&sec, 0, sizeof(sec)); if (chan->conn) sec.level = chan->conn->hcon->sec_level; else sec.level = chan->sec_level; if (sk->sk_state == BT_CONNECTED) sec.key_size = chan->conn->hcon->enc_key_size; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; case BT_FLUSHABLE: if (put_user(test_bit(FLAG_FLUSHABLE, &chan->flags), (u32 __user *) optval)) err = -EFAULT; break; case BT_POWER: if (sk->sk_type != SOCK_SEQPACKET && sk->sk_type != SOCK_STREAM && sk->sk_type != SOCK_RAW) { err = -EINVAL; break; } pwr.force_active = test_bit(FLAG_FORCE_ACTIVE, &chan->flags); len = min_t(unsigned int, len, sizeof(pwr)); if (copy_to_user(optval, (char *) &pwr, len)) err = -EFAULT; break; case BT_CHANNEL_POLICY: if (!enable_hs) { err = -ENOPROTOOPT; break; } if (put_user(chan->chan_policy, (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static bool l2cap_valid_mtu(struct l2cap_chan *chan, u16 mtu) { switch (chan->scid) { case L2CAP_CID_LE_DATA: if (mtu < L2CAP_LE_MIN_MTU) return false; break; default: if (mtu < L2CAP_DEFAULT_MIN_MTU) return false; } return true; } static int l2cap_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct l2cap_options opts; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case L2CAP_OPTIONS: if (sk->sk_state == BT_CONNECTED) { err = -EINVAL; break; } opts.imtu = chan->imtu; opts.omtu = chan->omtu; opts.flush_to = chan->flush_to; opts.mode = chan->mode; opts.fcs = chan->fcs; opts.max_tx = chan->max_tx; opts.txwin_size = chan->tx_win; len = min_t(unsigned int, sizeof(opts), optlen); if (copy_from_user((char *) &opts, optval, len)) { err = -EFAULT; break; } if (opts.txwin_size > L2CAP_DEFAULT_EXT_WINDOW) { err = -EINVAL; break; } if (!l2cap_valid_mtu(chan, opts.imtu)) { err = -EINVAL; break; } chan->mode = opts.mode; switch (chan->mode) { case L2CAP_MODE_BASIC: clear_bit(CONF_STATE2_DEVICE, &chan->conf_state); break; case L2CAP_MODE_ERTM: case L2CAP_MODE_STREAMING: if (!disable_ertm) break; /* fall through */ default: err = -EINVAL; break; } chan->imtu = opts.imtu; chan->omtu = opts.omtu; chan->fcs = opts.fcs; chan->max_tx = opts.max_tx; chan->tx_win = opts.txwin_size; break; case L2CAP_LM: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt & L2CAP_LM_AUTH) chan->sec_level = BT_SECURITY_LOW; if (opt & L2CAP_LM_ENCRYPT) chan->sec_level = BT_SECURITY_MEDIUM; if (opt & L2CAP_LM_SECURE) chan->sec_level = BT_SECURITY_HIGH; if (opt & L2CAP_LM_MASTER) set_bit(FLAG_ROLE_SWITCH, &chan->flags); else clear_bit(FLAG_ROLE_SWITCH, &chan->flags); if (opt & L2CAP_LM_RELIABLE) set_bit(FLAG_FORCE_RELIABLE, &chan->flags); else clear_bit(FLAG_FORCE_RELIABLE, &chan->flags); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct bt_security sec; struct bt_power pwr; struct l2cap_conn *conn; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (level == SOL_L2CAP) return l2cap_sock_setsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && chan->chan_type != L2CAP_CHAN_RAW) { err = -EINVAL; break; } sec.level = BT_SECURITY_LOW; len = min_t(unsigned int, sizeof(sec), optlen); if (copy_from_user((char *) &sec, optval, len)) { err = -EFAULT; break; } if (sec.level < BT_SECURITY_LOW || sec.level > BT_SECURITY_HIGH) { err = -EINVAL; break; } chan->sec_level = sec.level; if (!chan->conn) break; conn = chan->conn; /*change security for LE channels */ if (chan->scid == L2CAP_CID_LE_DATA) { if (!conn->hcon->out) { err = -EINVAL; break; } if (smp_conn_security(conn, sec.level)) break; sk->sk_state = BT_CONFIG; chan->state = BT_CONFIG; /* or for ACL link */ } else if ((sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) || sk->sk_state == BT_CONNECTED) { if (!l2cap_chan_check_security(chan)) set_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags); else sk->sk_state_change(sk); } else { err = -EINVAL; } break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; case BT_FLUSHABLE: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt > BT_FLUSHABLE_ON) { err = -EINVAL; break; } if (opt == BT_FLUSHABLE_OFF) { struct l2cap_conn *conn = chan->conn; /* proceed further only when we have l2cap_conn and No Flush support in the LM */ if (!conn || !lmp_no_flush_capable(conn->hcon->hdev)) { err = -EINVAL; break; } } if (opt) set_bit(FLAG_FLUSHABLE, &chan->flags); else clear_bit(FLAG_FLUSHABLE, &chan->flags); break; case BT_POWER: if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && chan->chan_type != L2CAP_CHAN_RAW) { err = -EINVAL; break; } pwr.force_active = BT_POWER_FORCE_ACTIVE_ON; len = min_t(unsigned int, sizeof(pwr), optlen); if (copy_from_user((char *) &pwr, optval, len)) { err = -EFAULT; break; } if (pwr.force_active) set_bit(FLAG_FORCE_ACTIVE, &chan->flags); else clear_bit(FLAG_FORCE_ACTIVE, &chan->flags); break; case BT_CHANNEL_POLICY: if (!enable_hs) { err = -ENOPROTOOPT; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt > BT_CHANNEL_POLICY_AMP_PREFERRED) { err = -EINVAL; break; } if (chan->mode != L2CAP_MODE_ERTM && chan->mode != L2CAP_MODE_STREAMING) { err = -EOPNOTSUPP; break; } chan->chan_policy = (u8) opt; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; int err; BT_DBG("sock %p, sk %p", sock, sk); err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; if (sk->sk_state != BT_CONNECTED) return -ENOTCONN; l2cap_chan_lock(chan); err = l2cap_chan_send(chan, msg, len, sk->sk_priority); l2cap_chan_unlock(chan); return err; } static int l2cap_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct l2cap_pinfo *pi = l2cap_pi(sk); int err; lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { sk->sk_state = BT_CONFIG; pi->chan->state = BT_CONFIG; __l2cap_connect_rsp_defer(pi->chan); release_sock(sk); return 0; } release_sock(sk); if (sock->type == SOCK_STREAM) err = bt_sock_stream_recvmsg(iocb, sock, msg, len, flags); else err = bt_sock_recvmsg(iocb, sock, msg, len, flags); if (pi->chan->mode != L2CAP_MODE_ERTM) return err; /* Attempt to put pending rx data in the socket buffer */ lock_sock(sk); if (!test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state)) goto done; if (pi->rx_busy_skb) { if (!sock_queue_rcv_skb(sk, pi->rx_busy_skb)) pi->rx_busy_skb = NULL; else goto done; } /* Restore data flow when half of the receive buffer is * available. This avoids resending large numbers of * frames. */ if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >> 1) l2cap_chan_busy(pi->chan, 0); done: release_sock(sk); return err; } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void l2cap_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %s", sk, state_to_string(sk->sk_state)); /* Kill poor orphan */ l2cap_chan_destroy(l2cap_pi(sk)->chan); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static int l2cap_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct l2cap_chan *chan; struct l2cap_conn *conn; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; chan = l2cap_pi(sk)->chan; conn = chan->conn; if (conn) mutex_lock(&conn->chan_lock); l2cap_chan_lock(chan); lock_sock(sk); if (!sk->sk_shutdown) { if (chan->mode == L2CAP_MODE_ERTM) err = __l2cap_wait_ack(sk); sk->sk_shutdown = SHUTDOWN_MASK; release_sock(sk); l2cap_chan_close(chan, 0); lock_sock(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } if (!err && sk->sk_err) err = -sk->sk_err; release_sock(sk); l2cap_chan_unlock(chan); if (conn) mutex_unlock(&conn->chan_lock); return err; } static int l2cap_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; err = l2cap_sock_shutdown(sock, 2); sock_orphan(sk); l2cap_sock_kill(sk); return err; } static void l2cap_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted channels */ while ((sk = bt_accept_dequeue(parent, NULL))) { struct l2cap_chan *chan = l2cap_pi(sk)->chan; l2cap_chan_lock(chan); __clear_chan_timer(chan); l2cap_chan_close(chan, ECONNRESET); l2cap_chan_unlock(chan); l2cap_sock_kill(sk); } } static struct l2cap_chan *l2cap_sock_new_connection_cb(struct l2cap_chan *chan) { struct sock *sk, *parent = chan->data; /* Check for backlog size */ if (sk_acceptq_is_full(parent)) { BT_DBG("backlog full %d", parent->sk_ack_backlog); return NULL; } sk = l2cap_sock_alloc(sock_net(parent), NULL, BTPROTO_L2CAP, GFP_ATOMIC); if (!sk) return NULL; bt_sock_reclassify_lock(sk, BTPROTO_L2CAP); l2cap_sock_init(sk, parent); return l2cap_pi(sk)->chan; } static int l2cap_sock_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb) { int err; struct sock *sk = chan->data; struct l2cap_pinfo *pi = l2cap_pi(sk); lock_sock(sk); if (pi->rx_busy_skb) { err = -ENOMEM; goto done; } err = sock_queue_rcv_skb(sk, skb); /* For ERTM, handle one skb that doesn't fit into the recv * buffer. This is important to do because the data frames * have already been acked, so the skb cannot be discarded. * * Notify the l2cap core that the buffer is full, so the * LOCAL_BUSY state is entered and no more frames are * acked and reassembled until there is buffer space * available. */ if (err < 0 && pi->chan->mode == L2CAP_MODE_ERTM) { pi->rx_busy_skb = skb; l2cap_chan_busy(pi->chan, 1); err = 0; } done: release_sock(sk); return err; } static void l2cap_sock_close_cb(struct l2cap_chan *chan) { struct sock *sk = chan->data; l2cap_sock_kill(sk); } static void l2cap_sock_teardown_cb(struct l2cap_chan *chan, int err) { struct sock *sk = chan->data; struct sock *parent; lock_sock(sk); parent = bt_sk(sk)->parent; sock_set_flag(sk, SOCK_ZAPPED); switch (chan->state) { case BT_OPEN: case BT_BOUND: case BT_CLOSED: break; case BT_LISTEN: l2cap_sock_cleanup_listen(sk); sk->sk_state = BT_CLOSED; chan->state = BT_CLOSED; break; default: sk->sk_state = BT_CLOSED; chan->state = BT_CLOSED; sk->sk_err = err; if (parent) { bt_accept_unlink(sk); parent->sk_data_ready(parent, 0); } else { sk->sk_state_change(sk); } break; } release_sock(sk); } static void l2cap_sock_state_change_cb(struct l2cap_chan *chan, int state) { struct sock *sk = chan->data; sk->sk_state = state; } static struct sk_buff *l2cap_sock_alloc_skb_cb(struct l2cap_chan *chan, unsigned long len, int nb) { struct sk_buff *skb; int err; l2cap_chan_unlock(chan); skb = bt_skb_send_alloc(chan->sk, len, nb, &err); l2cap_chan_lock(chan); if (!skb) return ERR_PTR(err); return skb; } static void l2cap_sock_ready_cb(struct l2cap_chan *chan) { struct sock *sk = chan->data; struct sock *parent; lock_sock(sk); parent = bt_sk(sk)->parent; BT_DBG("sk %p, parent %p", sk, parent); sk->sk_state = BT_CONNECTED; sk->sk_state_change(sk); if (parent) parent->sk_data_ready(parent, 0); release_sock(sk); } static struct l2cap_ops l2cap_chan_ops = { .name = "L2CAP Socket Interface", .new_connection = l2cap_sock_new_connection_cb, .recv = l2cap_sock_recv_cb, .close = l2cap_sock_close_cb, .teardown = l2cap_sock_teardown_cb, .state_change = l2cap_sock_state_change_cb, .ready = l2cap_sock_ready_cb, .alloc_skb = l2cap_sock_alloc_skb_cb, }; static void l2cap_sock_destruct(struct sock *sk) { BT_DBG("sk %p", sk); l2cap_chan_put(l2cap_pi(sk)->chan); if (l2cap_pi(sk)->rx_busy_skb) { kfree_skb(l2cap_pi(sk)->rx_busy_skb); l2cap_pi(sk)->rx_busy_skb = NULL; } skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); } static void l2cap_sock_init(struct sock *sk, struct sock *parent) { struct l2cap_pinfo *pi = l2cap_pi(sk); struct l2cap_chan *chan = pi->chan; BT_DBG("sk %p", sk); if (parent) { struct l2cap_chan *pchan = l2cap_pi(parent)->chan; sk->sk_type = parent->sk_type; bt_sk(sk)->flags = bt_sk(parent)->flags; chan->chan_type = pchan->chan_type; chan->imtu = pchan->imtu; chan->omtu = pchan->omtu; chan->conf_state = pchan->conf_state; chan->mode = pchan->mode; chan->fcs = pchan->fcs; chan->max_tx = pchan->max_tx; chan->tx_win = pchan->tx_win; chan->tx_win_max = pchan->tx_win_max; chan->sec_level = pchan->sec_level; chan->flags = pchan->flags; security_sk_clone(parent, sk); } else { switch (sk->sk_type) { case SOCK_RAW: chan->chan_type = L2CAP_CHAN_RAW; break; case SOCK_DGRAM: chan->chan_type = L2CAP_CHAN_CONN_LESS; break; case SOCK_SEQPACKET: case SOCK_STREAM: chan->chan_type = L2CAP_CHAN_CONN_ORIENTED; break; } chan->imtu = L2CAP_DEFAULT_MTU; chan->omtu = 0; if (!disable_ertm && sk->sk_type == SOCK_STREAM) { chan->mode = L2CAP_MODE_ERTM; set_bit(CONF_STATE2_DEVICE, &chan->conf_state); } else { chan->mode = L2CAP_MODE_BASIC; } l2cap_chan_set_defaults(chan); } /* Default config options */ chan->flush_to = L2CAP_DEFAULT_FLUSH_TO; chan->data = sk; chan->ops = &l2cap_chan_ops; } static struct proto l2cap_proto = { .name = "L2CAP", .owner = THIS_MODULE, .obj_size = sizeof(struct l2cap_pinfo) }; static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio) { struct sock *sk; struct l2cap_chan *chan; sk = sk_alloc(net, PF_BLUETOOTH, prio, &l2cap_proto); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); sk->sk_destruct = l2cap_sock_destruct; sk->sk_sndtimeo = L2CAP_CONN_TIMEOUT; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; chan = l2cap_chan_create(); if (!chan) { sk_free(sk); return NULL; } l2cap_chan_hold(chan); chan->sk = sk; l2cap_pi(sk)->chan = chan; return sk; } static int l2cap_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_SEQPACKET && sock->type != SOCK_STREAM && sock->type != SOCK_DGRAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (sock->type == SOCK_RAW && !kern && !capable(CAP_NET_RAW)) return -EPERM; sock->ops = &l2cap_sock_ops; sk = l2cap_sock_alloc(net, sock, protocol, GFP_ATOMIC); if (!sk) return -ENOMEM; l2cap_sock_init(sk, NULL); return 0; } static const struct proto_ops l2cap_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = l2cap_sock_release, .bind = l2cap_sock_bind, .connect = l2cap_sock_connect, .listen = l2cap_sock_listen, .accept = l2cap_sock_accept, .getname = l2cap_sock_getname, .sendmsg = l2cap_sock_sendmsg, .recvmsg = l2cap_sock_recvmsg, .poll = bt_sock_poll, .ioctl = bt_sock_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = l2cap_sock_shutdown, .setsockopt = l2cap_sock_setsockopt, .getsockopt = l2cap_sock_getsockopt }; static const struct net_proto_family l2cap_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = l2cap_sock_create, }; int __init l2cap_init_sockets(void) { int err; err = proto_register(&l2cap_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_L2CAP, &l2cap_sock_family_ops); if (err < 0) goto error; BT_INFO("L2CAP socket layer initialized"); return 0; error: BT_ERR("L2CAP socket registration failed"); proto_unregister(&l2cap_proto); return err; } void l2cap_cleanup_sockets(void) { if (bt_sock_unregister(BTPROTO_L2CAP) < 0) BT_ERR("L2CAP socket unregistration failed"); proto_unregister(&l2cap_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3833_0
crossvul-cpp_data_bad_760_3
/* * IPv6 library code, needed by static components when full IPv6 support is * not configured or static. These functions are needed by GSO/GRO implementation. */ #include <linux/export.h> #include <net/ip.h> #include <net/ipv6.h> #include <net/ip6_fib.h> #include <net/addrconf.h> #include <net/secure_seq.h> #include <linux/netfilter.h> static u32 __ipv6_select_ident(struct net *net, u32 hashrnd, const struct in6_addr *dst, const struct in6_addr *src) { u32 hash, id; hash = __ipv6_addr_jhash(dst, hashrnd); hash = __ipv6_addr_jhash(src, hash); hash ^= net_hash_mix(net); /* Treat id of 0 as unset and if we get 0 back from ip_idents_reserve, * set the hight order instead thus minimizing possible future * collisions. */ id = ip_idents_reserve(hash, 1); if (unlikely(!id)) id = 1 << 31; return id; } /* This function exists only for tap drivers that must support broken * clients requesting UFO without specifying an IPv6 fragment ID. * * This is similar to ipv6_select_ident() but we use an independent hash * seed to limit information leakage. * * The network header must be set before calling this. */ __be32 ipv6_proxy_select_ident(struct net *net, struct sk_buff *skb) { static u32 ip6_proxy_idents_hashrnd __read_mostly; struct in6_addr buf[2]; struct in6_addr *addrs; u32 id; addrs = skb_header_pointer(skb, skb_network_offset(skb) + offsetof(struct ipv6hdr, saddr), sizeof(buf), buf); if (!addrs) return 0; net_get_random_once(&ip6_proxy_idents_hashrnd, sizeof(ip6_proxy_idents_hashrnd)); id = __ipv6_select_ident(net, ip6_proxy_idents_hashrnd, &addrs[1], &addrs[0]); return htonl(id); } EXPORT_SYMBOL_GPL(ipv6_proxy_select_ident); __be32 ipv6_select_ident(struct net *net, const struct in6_addr *daddr, const struct in6_addr *saddr) { static u32 ip6_idents_hashrnd __read_mostly; u32 id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); id = __ipv6_select_ident(net, ip6_idents_hashrnd, daddr, saddr); return htonl(id); } EXPORT_SYMBOL(ipv6_select_ident); int ip6_find_1stfragopt(struct sk_buff *skb, u8 **nexthdr) { unsigned int offset = sizeof(struct ipv6hdr); unsigned int packet_len = skb_tail_pointer(skb) - skb_network_header(skb); int found_rhdr = 0; *nexthdr = &ipv6_hdr(skb)->nexthdr; while (offset <= packet_len) { struct ipv6_opt_hdr *exthdr; switch (**nexthdr) { case NEXTHDR_HOP: break; case NEXTHDR_ROUTING: found_rhdr = 1; break; case NEXTHDR_DEST: #if IS_ENABLED(CONFIG_IPV6_MIP6) if (ipv6_find_tlv(skb, offset, IPV6_TLV_HAO) >= 0) break; #endif if (found_rhdr) return offset; break; default: return offset; } if (offset + sizeof(struct ipv6_opt_hdr) > packet_len) return -EINVAL; exthdr = (struct ipv6_opt_hdr *)(skb_network_header(skb) + offset); offset += ipv6_optlen(exthdr); if (offset > IPV6_MAXPLEN) return -EINVAL; *nexthdr = &exthdr->nexthdr; } return -EINVAL; } EXPORT_SYMBOL(ip6_find_1stfragopt); #if IS_ENABLED(CONFIG_IPV6) int ip6_dst_hoplimit(struct dst_entry *dst) { int hoplimit = dst_metric_raw(dst, RTAX_HOPLIMIT); if (hoplimit == 0) { struct net_device *dev = dst->dev; struct inet6_dev *idev; rcu_read_lock(); idev = __in6_dev_get(dev); if (idev) hoplimit = idev->cnf.hop_limit; else hoplimit = dev_net(dev)->ipv6.devconf_all->hop_limit; rcu_read_unlock(); } return hoplimit; } EXPORT_SYMBOL(ip6_dst_hoplimit); #endif int __ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb) { int len; len = skb->len - sizeof(struct ipv6hdr); if (len > IPV6_MAXPLEN) len = 0; ipv6_hdr(skb)->payload_len = htons(len); IP6CB(skb)->nhoff = offsetof(struct ipv6hdr, nexthdr); /* if egress device is enslaved to an L3 master device pass the * skb to its handler for processing */ skb = l3mdev_ip6_out(sk, skb); if (unlikely(!skb)) return 0; skb->protocol = htons(ETH_P_IPV6); return nf_hook(NFPROTO_IPV6, NF_INET_LOCAL_OUT, net, sk, skb, NULL, skb_dst(skb)->dev, dst_output); } EXPORT_SYMBOL_GPL(__ip6_local_out); int ip6_local_out(struct net *net, struct sock *sk, struct sk_buff *skb) { int err; err = __ip6_local_out(net, sk, skb); if (likely(err == 1)) err = dst_output(net, sk, skb); return err; } EXPORT_SYMBOL_GPL(ip6_local_out);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_760_3
crossvul-cpp_data_good_1125_3
/* * Elliptic curve DSA * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ /* * References: * * SEC1 http://www.secg.org/index.php?action=secg,docs_secg */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_ECDSA_C) #include "mbedtls/ecdsa.h" #include "mbedtls/asn1write.h" #include <string.h> #if defined(MBEDTLS_ECDSA_DETERMINISTIC) #include "mbedtls/hmac_drbg.h" #endif #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/platform_util.h" /* Parameter validation macros based on platform_util.h */ #define ECDSA_VALIDATE_RET( cond ) \ MBEDTLS_INTERNAL_VALIDATE_RET( cond, MBEDTLS_ERR_ECP_BAD_INPUT_DATA ) #define ECDSA_VALIDATE( cond ) \ MBEDTLS_INTERNAL_VALIDATE( cond ) #if defined(MBEDTLS_ECP_RESTARTABLE) /* * Sub-context for ecdsa_verify() */ struct mbedtls_ecdsa_restart_ver { mbedtls_mpi u1, u2; /* intermediate values */ enum { /* what to do next? */ ecdsa_ver_init = 0, /* getting started */ ecdsa_ver_muladd, /* muladd step */ } state; }; /* * Init verify restart sub-context */ static void ecdsa_restart_ver_init( mbedtls_ecdsa_restart_ver_ctx *ctx ) { mbedtls_mpi_init( &ctx->u1 ); mbedtls_mpi_init( &ctx->u2 ); ctx->state = ecdsa_ver_init; } /* * Free the components of a verify restart sub-context */ static void ecdsa_restart_ver_free( mbedtls_ecdsa_restart_ver_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_mpi_free( &ctx->u1 ); mbedtls_mpi_free( &ctx->u2 ); ecdsa_restart_ver_init( ctx ); } /* * Sub-context for ecdsa_sign() */ struct mbedtls_ecdsa_restart_sig { int sign_tries; int key_tries; mbedtls_mpi k; /* per-signature random */ mbedtls_mpi r; /* r value */ enum { /* what to do next? */ ecdsa_sig_init = 0, /* getting started */ ecdsa_sig_mul, /* doing ecp_mul() */ ecdsa_sig_modn, /* mod N computations */ } state; }; /* * Init verify sign sub-context */ static void ecdsa_restart_sig_init( mbedtls_ecdsa_restart_sig_ctx *ctx ) { ctx->sign_tries = 0; ctx->key_tries = 0; mbedtls_mpi_init( &ctx->k ); mbedtls_mpi_init( &ctx->r ); ctx->state = ecdsa_sig_init; } /* * Free the components of a sign restart sub-context */ static void ecdsa_restart_sig_free( mbedtls_ecdsa_restart_sig_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_mpi_free( &ctx->k ); mbedtls_mpi_free( &ctx->r ); } #if defined(MBEDTLS_ECDSA_DETERMINISTIC) /* * Sub-context for ecdsa_sign_det() */ struct mbedtls_ecdsa_restart_det { mbedtls_hmac_drbg_context rng_ctx; /* DRBG state */ enum { /* what to do next? */ ecdsa_det_init = 0, /* getting started */ ecdsa_det_sign, /* make signature */ } state; }; /* * Init verify sign_det sub-context */ static void ecdsa_restart_det_init( mbedtls_ecdsa_restart_det_ctx *ctx ) { mbedtls_hmac_drbg_init( &ctx->rng_ctx ); ctx->state = ecdsa_det_init; } /* * Free the components of a sign_det restart sub-context */ static void ecdsa_restart_det_free( mbedtls_ecdsa_restart_det_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_hmac_drbg_free( &ctx->rng_ctx ); ecdsa_restart_det_init( ctx ); } #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #define ECDSA_RS_ECP &rs_ctx->ecp /* Utility macro for checking and updating ops budget */ #define ECDSA_BUDGET( ops ) \ MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, &rs_ctx->ecp, ops ) ); /* Call this when entering a function that needs its own sub-context */ #define ECDSA_RS_ENTER( SUB ) do { \ /* reset ops count for this call if top-level */ \ if( rs_ctx != NULL && rs_ctx->ecp.depth++ == 0 ) \ rs_ctx->ecp.ops_done = 0; \ \ /* set up our own sub-context if needed */ \ if( mbedtls_ecp_restart_is_enabled() && \ rs_ctx != NULL && rs_ctx->SUB == NULL ) \ { \ rs_ctx->SUB = mbedtls_calloc( 1, sizeof( *rs_ctx->SUB ) ); \ if( rs_ctx->SUB == NULL ) \ return( MBEDTLS_ERR_ECP_ALLOC_FAILED ); \ \ ecdsa_restart_## SUB ##_init( rs_ctx->SUB ); \ } \ } while( 0 ) /* Call this when leaving a function that needs its own sub-context */ #define ECDSA_RS_LEAVE( SUB ) do { \ /* clear our sub-context when not in progress (done or error) */ \ if( rs_ctx != NULL && rs_ctx->SUB != NULL && \ ret != MBEDTLS_ERR_ECP_IN_PROGRESS ) \ { \ ecdsa_restart_## SUB ##_free( rs_ctx->SUB ); \ mbedtls_free( rs_ctx->SUB ); \ rs_ctx->SUB = NULL; \ } \ \ if( rs_ctx != NULL ) \ rs_ctx->ecp.depth--; \ } while( 0 ) #else /* MBEDTLS_ECP_RESTARTABLE */ #define ECDSA_RS_ECP NULL #define ECDSA_BUDGET( ops ) /* no-op; for compatibility */ #define ECDSA_RS_ENTER( SUB ) (void) rs_ctx #define ECDSA_RS_LEAVE( SUB ) (void) rs_ctx #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Derive a suitable integer for group grp from a buffer of length len * SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3 */ static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x, const unsigned char *buf, size_t blen ) { int ret; size_t n_size = ( grp->nbits + 7 ) / 8; size_t use_size = blen > n_size ? n_size : blen; MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( x, buf, use_size ) ); if( use_size * 8 > grp->nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( x, use_size * 8 - grp->nbits ) ); /* While at it, reduce modulo N */ if( mbedtls_mpi_cmp_mpi( x, &grp->N ) >= 0 ) MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( x, x, &grp->N ) ); cleanup: return( ret ); } #if !defined(MBEDTLS_ECDSA_SIGN_ALT) /* * Compute ECDSA signature of a hashed message (SEC1 4.1.3) * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message) */ static int ecdsa_sign_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret, key_tries, sign_tries; int *p_sign_tries = &sign_tries, *p_key_tries = &key_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; mbedtls_mpi *pk = &k, *pr = r; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* Make sure d is in range 1..n-1 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); ECDSA_RS_ENTER( sig ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) { /* redirect to our context */ p_sign_tries = &rs_ctx->sig->sign_tries; p_key_tries = &rs_ctx->sig->key_tries; pk = &rs_ctx->sig->k; pr = &rs_ctx->sig->r; /* jump to current step */ if( rs_ctx->sig->state == ecdsa_sig_mul ) goto mul; if( rs_ctx->sig->state == ecdsa_sig_modn ) goto modn; } #endif /* MBEDTLS_ECP_RESTARTABLE */ *p_sign_tries = 0; do { if( *p_sign_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ *p_key_tries = 0; do { if( *p_key_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, pk, f_rng, p_rng ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_mul; mul: #endif MBEDTLS_MPI_CHK( mbedtls_ecp_mul_restartable( grp, &R, pk, &grp->G, f_rng_blind, p_rng_blind, ECDSA_RS_ECP ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pr, &R.X, &grp->N ) ); } while( mbedtls_mpi_cmp_int( pr, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) rs_ctx->sig->state = ecdsa_sig_modn; modn: #endif /* * Accounting for everything up to the end of the loop * (step 6, but checking now avoids saving e and t) */ ECDSA_BUDGET( MBEDTLS_ECP_OPS_INV + 4 ); /* * Step 5: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. */ MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &t, f_rng_blind, p_rng_blind ) ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, pr, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pk, pk, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, pk, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->sig != NULL ) mbedtls_mpi_copy( r, pr ); #endif cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); ECDSA_RS_LEAVE( sig ); return( ret ); } /* * Compute ECDSA signature of a hashed message */ int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( f_rng != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); /* Use the same RNG for both blinding and ephemeral key generation */ return( ecdsa_sign_restartable( grp, r, s, d, buf, blen, f_rng, p_rng, f_rng, p_rng, NULL ) ); } #endif /* !MBEDTLS_ECDSA_SIGN_ALT */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) /* * Deterministic signature wrapper */ static int ecdsa_sign_det_restartable( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_hmac_drbg_context rng_ctx; mbedtls_hmac_drbg_context *p_rng = &rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); ECDSA_RS_ENTER( det ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) { /* redirect to our context */ p_rng = &rs_ctx->det->rng_ctx; /* jump to current step */ if( rs_ctx->det->state == ecdsa_det_sign ) goto sign; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( p_rng, md_info, data, 2 * grp_len ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->det != NULL ) rs_ctx->det->state = ecdsa_det_sign; sign: #endif #if defined(MBEDTLS_ECDSA_SIGN_ALT) ret = mbedtls_ecdsa_sign( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng ); #else if( f_rng_blind != NULL ) ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, f_rng_blind, p_rng_blind, rs_ctx ); else { mbedtls_hmac_drbg_context *p_rng_blind_det; #if !defined(MBEDTLS_ECP_RESTARTABLE) /* * To avoid reusing rng_ctx and risking incorrect behavior we seed a * second HMAC-DRBG with the same seed. We also apply a label to avoid * reusing the bits of the ephemeral key for blinding and eliminate the * risk that they leak this way. */ const char* blind_label = "BLINDING CONTEXT"; mbedtls_hmac_drbg_context rng_ctx_blind; mbedtls_hmac_drbg_init( &rng_ctx_blind ); p_rng_blind_det = &rng_ctx_blind; mbedtls_hmac_drbg_seed_buf( p_rng_blind_det, md_info, data, 2 * grp_len ); ret = mbedtls_hmac_drbg_update_ret( p_rng_blind_det, (const unsigned char*) blind_label, strlen( blind_label ) ); if( ret != 0 ) { mbedtls_hmac_drbg_free( &rng_ctx_blind ); goto cleanup; } #else /* * In the case of restartable computations we would either need to store * the second RNG in the restart context too or set it up at every * restart. The first option would penalize the correct application of * the function and the second would defeat the purpose of the * restartable feature. * * Therefore in this case we reuse the original RNG. This comes with the * price that the resulting signature might not be a valid deterministic * ECDSA signature with a very low probability (same magnitude as * successfully guessing the private key). However even then it is still * a valid ECDSA signature. */ p_rng_blind_det = p_rng; #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Since the output of the RNGs is always the same for the same key and * message, this limits the efficiency of blinding and leaks information * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL * won't be a valid value for f_rng_blind anymore. Therefore it should * be checked by the caller and this branch and check can be removed. */ ret = ecdsa_sign_restartable( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, p_rng, mbedtls_hmac_drbg_random, p_rng_blind_det, rs_ctx ); #if !defined(MBEDTLS_ECP_RESTARTABLE) mbedtls_hmac_drbg_free( &rng_ctx_blind ); #endif } #endif /* MBEDTLS_ECDSA_SIGN_ALT */ cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_mpi_free( &h ); ECDSA_RS_LEAVE( det ); return( ret ); } /* * Deterministic signature wrappers */ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, NULL, NULL, NULL ) ); } int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( d != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); ECDSA_VALIDATE_RET( f_rng_blind != NULL ); return( ecdsa_sign_det_restartable( grp, r, s, d, buf, blen, md_alg, f_rng_blind, p_rng_blind, NULL ) ); } #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #if !defined(MBEDTLS_ECDSA_VERIFY_ALT) /* * Verify ECDSA signature of hashed message (SEC1 4.1.4) * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message) */ static int ecdsa_verify_restartable( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_mpi e, s_inv, u1, u2; mbedtls_ecp_point R; mbedtls_mpi *pu1 = &u1, *pu2 = &u2; mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv ); mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 ); /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); ECDSA_RS_ENTER( ver ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->ver != NULL ) { /* redirect to our context */ pu1 = &rs_ctx->ver->u1; pu2 = &rs_ctx->ver->u2; /* jump to current step */ if( rs_ctx->ver->state == ecdsa_ver_muladd ) goto muladd; } #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Step 1: make sure r and s are in range 1..n-1 */ if( mbedtls_mpi_cmp_int( r, 1 ) < 0 || mbedtls_mpi_cmp_mpi( r, &grp->N ) >= 0 || mbedtls_mpi_cmp_int( s, 1 ) < 0 || mbedtls_mpi_cmp_mpi( s, &grp->N ) >= 0 ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } /* * Step 3: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Step 4: u1 = e / s mod n, u2 = r / s mod n */ ECDSA_BUDGET( MBEDTLS_ECP_OPS_CHK + MBEDTLS_ECP_OPS_INV + 2 ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu1, &e, &s_inv ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu1, pu1, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( pu2, r, &s_inv ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( pu2, pu2, &grp->N ) ); #if defined(MBEDTLS_ECP_RESTARTABLE) if( rs_ctx != NULL && rs_ctx->ver != NULL ) rs_ctx->ver->state = ecdsa_ver_muladd; muladd: #endif /* * Step 5: R = u1 G + u2 Q */ MBEDTLS_MPI_CHK( mbedtls_ecp_muladd_restartable( grp, &R, pu1, &grp->G, pu2, Q, ECDSA_RS_ECP ) ); if( mbedtls_ecp_is_zero( &R ) ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } /* * Step 6: convert xR to an integer (no-op) * Step 7: reduce xR mod n (gives v) */ MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &R.X, &R.X, &grp->N ) ); /* * Step 8: check if v (that is, R.X) is equal to r */ if( mbedtls_mpi_cmp_mpi( &R.X, r ) != 0 ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv ); mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 ); ECDSA_RS_LEAVE( ver ); return( ret ); } /* * Verify ECDSA signature of hashed message */ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s) { ECDSA_VALIDATE_RET( grp != NULL ); ECDSA_VALIDATE_RET( Q != NULL ); ECDSA_VALIDATE_RET( r != NULL ); ECDSA_VALIDATE_RET( s != NULL ); ECDSA_VALIDATE_RET( buf != NULL || blen == 0 ); return( ecdsa_verify_restartable( grp, buf, blen, Q, r, s, NULL ) ); } #endif /* !MBEDTLS_ECDSA_VERIFY_ALT */ /* * Convert a signature (given by context) to ASN.1 */ static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s, unsigned char *sig, size_t *slen ) { int ret; unsigned char buf[MBEDTLS_ECDSA_MAX_LEN]; unsigned char *p = buf + sizeof( buf ); size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, s ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, r ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); memcpy( sig, p, len ); *slen = len; return( 0 ); } /* * Compute and write signature */ int mbedtls_ecdsa_write_signature_restartable( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; mbedtls_mpi r, s; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); ECDSA_VALIDATE_RET( slen != NULL ); mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); #if defined(MBEDTLS_ECDSA_DETERMINISTIC) MBEDTLS_MPI_CHK( ecdsa_sign_det_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, md_alg, f_rng, p_rng, rs_ctx ) ); #else (void) md_alg; #if defined(MBEDTLS_ECDSA_SIGN_ALT) MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng ) ); #else /* Use the same RNG for both blinding and ephemeral key generation */ MBEDTLS_MPI_CHK( ecdsa_sign_restartable( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng, f_rng, p_rng, rs_ctx ) ); #endif /* MBEDTLS_ECDSA_SIGN_ALT */ #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) ); cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } /* * Compute and write signature */ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); ECDSA_VALIDATE_RET( slen != NULL ); return( mbedtls_ecdsa_write_signature_restartable( ctx, md_alg, hash, hlen, sig, slen, f_rng, p_rng, NULL ) ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) && \ defined(MBEDTLS_ECDSA_DETERMINISTIC) int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, mbedtls_md_type_t md_alg ) { ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); ECDSA_VALIDATE_RET( slen != NULL ); return( mbedtls_ecdsa_write_signature( ctx, md_alg, hash, hlen, sig, slen, NULL, NULL ) ); } #endif /* * Read and check signature */ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen ) { ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); return( mbedtls_ecdsa_read_signature_restartable( ctx, hash, hlen, sig, slen, NULL ) ); } /* * Restartable read and check signature */ int mbedtls_ecdsa_read_signature_restartable( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen, mbedtls_ecdsa_restart_ctx *rs_ctx ) { int ret; unsigned char *p = (unsigned char *) sig; const unsigned char *end = sig + slen; size_t len; mbedtls_mpi r, s; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( hash != NULL ); ECDSA_VALIDATE_RET( sig != NULL ); mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } if( p + len != end ) { ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH; goto cleanup; } if( ( ret = mbedtls_asn1_get_mpi( &p, end, &r ) ) != 0 || ( ret = mbedtls_asn1_get_mpi( &p, end, &s ) ) != 0 ) { ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } #if defined(MBEDTLS_ECDSA_VERIFY_ALT) if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen, &ctx->Q, &r, &s ) ) != 0 ) goto cleanup; #else if( ( ret = ecdsa_verify_restartable( &ctx->grp, hash, hlen, &ctx->Q, &r, &s, rs_ctx ) ) != 0 ) goto cleanup; #endif /* MBEDTLS_ECDSA_VERIFY_ALT */ /* At this point we know that the buffer starts with a valid signature. * Return 0 if the buffer just contains the signature, and a specific * error code if the valid signature is followed by more data. */ if( p != end ) ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH; cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } #if !defined(MBEDTLS_ECDSA_GENKEY_ALT) /* * Generate key pair */ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = 0; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( f_rng != NULL ); ret = mbedtls_ecp_group_load( &ctx->grp, gid ); if( ret != 0 ) return( ret ); return( mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ); } #endif /* !MBEDTLS_ECDSA_GENKEY_ALT */ /* * Set context from an mbedtls_ecp_keypair */ int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key ) { int ret; ECDSA_VALIDATE_RET( ctx != NULL ); ECDSA_VALIDATE_RET( key != NULL ); if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 || ( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 || ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 ) { mbedtls_ecdsa_free( ctx ); } return( ret ); } /* * Initialize context */ void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx ) { ECDSA_VALIDATE( ctx != NULL ); mbedtls_ecp_keypair_init( ctx ); } /* * Free context */ void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ) { if( ctx == NULL ) return; mbedtls_ecp_keypair_free( ctx ); } #if defined(MBEDTLS_ECP_RESTARTABLE) /* * Initialize a restart context */ void mbedtls_ecdsa_restart_init( mbedtls_ecdsa_restart_ctx *ctx ) { ECDSA_VALIDATE( ctx != NULL ); mbedtls_ecp_restart_init( &ctx->ecp ); ctx->ver = NULL; ctx->sig = NULL; #if defined(MBEDTLS_ECDSA_DETERMINISTIC) ctx->det = NULL; #endif } /* * Free the components of a restart context */ void mbedtls_ecdsa_restart_free( mbedtls_ecdsa_restart_ctx *ctx ) { if( ctx == NULL ) return; mbedtls_ecp_restart_free( &ctx->ecp ); ecdsa_restart_ver_free( ctx->ver ); mbedtls_free( ctx->ver ); ctx->ver = NULL; ecdsa_restart_sig_free( ctx->sig ); mbedtls_free( ctx->sig ); ctx->sig = NULL; #if defined(MBEDTLS_ECDSA_DETERMINISTIC) ecdsa_restart_det_free( ctx->det ); mbedtls_free( ctx->det ); ctx->det = NULL; #endif } #endif /* MBEDTLS_ECP_RESTARTABLE */ #endif /* MBEDTLS_ECDSA_C */
./CrossVul/dataset_final_sorted/CWE-200/c/good_1125_3
crossvul-cpp_data_bad_2425_0
/* * Media device * * Copyright (C) 2010 Nokia Corporation * * Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com> * Sakari Ailus <sakari.ailus@iki.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/compat.h> #include <linux/export.h> #include <linux/ioctl.h> #include <linux/media.h> #include <linux/types.h> #include <media/media-device.h> #include <media/media-devnode.h> #include <media/media-entity.h> /* ----------------------------------------------------------------------------- * Userspace API */ static int media_device_open(struct file *filp) { return 0; } static int media_device_close(struct file *filp) { return 0; } static int media_device_get_info(struct media_device *dev, struct media_device_info __user *__info) { struct media_device_info info; memset(&info, 0, sizeof(info)); strlcpy(info.driver, dev->dev->driver->name, sizeof(info.driver)); strlcpy(info.model, dev->model, sizeof(info.model)); strlcpy(info.serial, dev->serial, sizeof(info.serial)); strlcpy(info.bus_info, dev->bus_info, sizeof(info.bus_info)); info.media_version = MEDIA_API_VERSION; info.hw_revision = dev->hw_revision; info.driver_version = dev->driver_version; if (copy_to_user(__info, &info, sizeof(*__info))) return -EFAULT; return 0; } static struct media_entity *find_entity(struct media_device *mdev, u32 id) { struct media_entity *entity; int next = id & MEDIA_ENT_ID_FLAG_NEXT; id &= ~MEDIA_ENT_ID_FLAG_NEXT; spin_lock(&mdev->lock); media_device_for_each_entity(entity, mdev) { if ((entity->id == id && !next) || (entity->id > id && next)) { spin_unlock(&mdev->lock); return entity; } } spin_unlock(&mdev->lock); return NULL; } static long media_device_enum_entities(struct media_device *mdev, struct media_entity_desc __user *uent) { struct media_entity *ent; struct media_entity_desc u_ent; if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id))) return -EFAULT; ent = find_entity(mdev, u_ent.id); if (ent == NULL) return -EINVAL; u_ent.id = ent->id; if (ent->name) { strncpy(u_ent.name, ent->name, sizeof(u_ent.name)); u_ent.name[sizeof(u_ent.name) - 1] = '\0'; } else { memset(u_ent.name, 0, sizeof(u_ent.name)); } u_ent.type = ent->type; u_ent.revision = ent->revision; u_ent.flags = ent->flags; u_ent.group_id = ent->group_id; u_ent.pads = ent->num_pads; u_ent.links = ent->num_links - ent->num_backlinks; memcpy(&u_ent.raw, &ent->info, sizeof(ent->info)); if (copy_to_user(uent, &u_ent, sizeof(u_ent))) return -EFAULT; return 0; } static void media_device_kpad_to_upad(const struct media_pad *kpad, struct media_pad_desc *upad) { upad->entity = kpad->entity->id; upad->index = kpad->index; upad->flags = kpad->flags; } static long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; } static long media_device_enum_links(struct media_device *mdev, struct media_links_enum __user *ulinks) { struct media_links_enum links; int rval; if (copy_from_user(&links, ulinks, sizeof(links))) return -EFAULT; rval = __media_device_enum_links(mdev, &links); if (rval < 0) return rval; if (copy_to_user(ulinks, &links, sizeof(*ulinks))) return -EFAULT; return 0; } static long media_device_setup_link(struct media_device *mdev, struct media_link_desc __user *_ulink) { struct media_link *link = NULL; struct media_link_desc ulink; struct media_entity *source; struct media_entity *sink; int ret; if (copy_from_user(&ulink, _ulink, sizeof(ulink))) return -EFAULT; /* Find the source and sink entities and link. */ source = find_entity(mdev, ulink.source.entity); sink = find_entity(mdev, ulink.sink.entity); if (source == NULL || sink == NULL) return -EINVAL; if (ulink.source.index >= source->num_pads || ulink.sink.index >= sink->num_pads) return -EINVAL; link = media_entity_find_link(&source->pads[ulink.source.index], &sink->pads[ulink.sink.index]); if (link == NULL) return -EINVAL; /* Setup the link on both entities. */ ret = __media_entity_setup_link(link, ulink.flags); if (copy_to_user(_ulink, &ulink, sizeof(ulink))) return -EFAULT; return ret; } static long media_device_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: ret = media_device_get_info(dev, (struct media_device_info __user *)arg); break; case MEDIA_IOC_ENUM_ENTITIES: ret = media_device_enum_entities(dev, (struct media_entity_desc __user *)arg); break; case MEDIA_IOC_ENUM_LINKS: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links(dev, (struct media_links_enum __user *)arg); mutex_unlock(&dev->graph_mutex); break; case MEDIA_IOC_SETUP_LINK: mutex_lock(&dev->graph_mutex); ret = media_device_setup_link(dev, (struct media_link_desc __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #ifdef CONFIG_COMPAT struct media_links_enum32 { __u32 entity; compat_uptr_t pads; /* struct media_pad_desc * */ compat_uptr_t links; /* struct media_link_desc * */ __u32 reserved[4]; }; static long media_device_enum_links32(struct media_device *mdev, struct media_links_enum32 __user *ulinks) { struct media_links_enum links; compat_uptr_t pads_ptr, links_ptr; memset(&links, 0, sizeof(links)); if (get_user(links.entity, &ulinks->entity) || get_user(pads_ptr, &ulinks->pads) || get_user(links_ptr, &ulinks->links)) return -EFAULT; links.pads = compat_ptr(pads_ptr); links.links = compat_ptr(links_ptr); return __media_device_enum_links(mdev, &links); } #define MEDIA_IOC_ENUM_LINKS32 _IOWR('|', 0x02, struct media_links_enum32) static long media_device_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: case MEDIA_IOC_ENUM_ENTITIES: case MEDIA_IOC_SETUP_LINK: return media_device_ioctl(filp, cmd, arg); case MEDIA_IOC_ENUM_LINKS32: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links32(dev, (struct media_links_enum32 __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #endif /* CONFIG_COMPAT */ static const struct media_file_operations media_device_fops = { .owner = THIS_MODULE, .open = media_device_open, .ioctl = media_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = media_device_compat_ioctl, #endif /* CONFIG_COMPAT */ .release = media_device_close, }; /* ----------------------------------------------------------------------------- * sysfs */ static ssize_t show_model(struct device *cd, struct device_attribute *attr, char *buf) { struct media_device *mdev = to_media_device(to_media_devnode(cd)); return sprintf(buf, "%.*s\n", (int)sizeof(mdev->model), mdev->model); } static DEVICE_ATTR(model, S_IRUGO, show_model, NULL); /* ----------------------------------------------------------------------------- * Registration/unregistration */ static void media_device_release(struct media_devnode *mdev) { } /** * media_device_register - register a media device * @mdev: The media device * * The caller is responsible for initializing the media device before * registration. The following fields must be set: * * - dev must point to the parent device * - model must be filled with the device model name */ int __must_check media_device_register(struct media_device *mdev) { int ret; if (WARN_ON(mdev->dev == NULL || mdev->model[0] == 0)) return -EINVAL; mdev->entity_id = 1; INIT_LIST_HEAD(&mdev->entities); spin_lock_init(&mdev->lock); mutex_init(&mdev->graph_mutex); /* Register the device node. */ mdev->devnode.fops = &media_device_fops; mdev->devnode.parent = mdev->dev; mdev->devnode.release = media_device_release; ret = media_devnode_register(&mdev->devnode); if (ret < 0) return ret; ret = device_create_file(&mdev->devnode.dev, &dev_attr_model); if (ret < 0) { media_devnode_unregister(&mdev->devnode); return ret; } return 0; } EXPORT_SYMBOL_GPL(media_device_register); /** * media_device_unregister - unregister a media device * @mdev: The media device * */ void media_device_unregister(struct media_device *mdev) { struct media_entity *entity; struct media_entity *next; list_for_each_entry_safe(entity, next, &mdev->entities, list) media_device_unregister_entity(entity); device_remove_file(&mdev->devnode.dev, &dev_attr_model); media_devnode_unregister(&mdev->devnode); } EXPORT_SYMBOL_GPL(media_device_unregister); /** * media_device_register_entity - Register an entity with a media device * @mdev: The media device * @entity: The entity */ int __must_check media_device_register_entity(struct media_device *mdev, struct media_entity *entity) { /* Warn if we apparently re-register an entity */ WARN_ON(entity->parent != NULL); entity->parent = mdev; spin_lock(&mdev->lock); if (entity->id == 0) entity->id = mdev->entity_id++; else mdev->entity_id = max(entity->id + 1, mdev->entity_id); list_add_tail(&entity->list, &mdev->entities); spin_unlock(&mdev->lock); return 0; } EXPORT_SYMBOL_GPL(media_device_register_entity); /** * media_device_unregister_entity - Unregister an entity * @entity: The entity * * If the entity has never been registered this function will return * immediately. */ void media_device_unregister_entity(struct media_entity *entity) { struct media_device *mdev = entity->parent; if (mdev == NULL) return; spin_lock(&mdev->lock); list_del(&entity->list); spin_unlock(&mdev->lock); entity->parent = NULL; } EXPORT_SYMBOL_GPL(media_device_unregister_entity);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2425_0
crossvul-cpp_data_good_2330_0
/* * Copyright 2002-2005, Instant802 Networks, Inc. * Copyright 2005-2006, Devicescape Software, Inc. * Copyright 2006-2007 Jiri Benc <jbenc@suse.cz> * Copyright 2007 Johannes Berg <johannes@sipsolutions.net> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * * Transmit and frame generation functions. */ #include <linux/kernel.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/etherdevice.h> #include <linux/bitmap.h> #include <linux/rcupdate.h> #include <linux/export.h> #include <linux/time.h> #include <net/net_namespace.h> #include <net/ieee80211_radiotap.h> #include <net/cfg80211.h> #include <net/mac80211.h> #include <asm/unaligned.h> #include "ieee80211_i.h" #include "driver-ops.h" #include "led.h" #include "mesh.h" #include "wep.h" #include "wpa.h" #include "wme.h" #include "rate.h" /* misc utils */ static __le16 ieee80211_duration(struct ieee80211_tx_data *tx, struct sk_buff *skb, int group_addr, int next_frag_len) { int rate, mrate, erp, dur, i, shift = 0; struct ieee80211_rate *txrate; struct ieee80211_local *local = tx->local; struct ieee80211_supported_band *sband; struct ieee80211_hdr *hdr; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_chanctx_conf *chanctx_conf; u32 rate_flags = 0; rcu_read_lock(); chanctx_conf = rcu_dereference(tx->sdata->vif.chanctx_conf); if (chanctx_conf) { shift = ieee80211_chandef_get_shift(&chanctx_conf->def); rate_flags = ieee80211_chandef_rate_flags(&chanctx_conf->def); } rcu_read_unlock(); /* assume HW handles this */ if (tx->rate.flags & IEEE80211_TX_RC_MCS) return 0; /* uh huh? */ if (WARN_ON_ONCE(tx->rate.idx < 0)) return 0; sband = local->hw.wiphy->bands[info->band]; txrate = &sband->bitrates[tx->rate.idx]; erp = txrate->flags & IEEE80211_RATE_ERP_G; /* * data and mgmt (except PS Poll): * - during CFP: 32768 * - during contention period: * if addr1 is group address: 0 * if more fragments = 0 and addr1 is individual address: time to * transmit one ACK plus SIFS * if more fragments = 1 and addr1 is individual address: time to * transmit next fragment plus 2 x ACK plus 3 x SIFS * * IEEE 802.11, 9.6: * - control response frame (CTS or ACK) shall be transmitted using the * same rate as the immediately previous frame in the frame exchange * sequence, if this rate belongs to the PHY mandatory rates, or else * at the highest possible rate belonging to the PHY rates in the * BSSBasicRateSet */ hdr = (struct ieee80211_hdr *)skb->data; if (ieee80211_is_ctl(hdr->frame_control)) { /* TODO: These control frames are not currently sent by * mac80211, but should they be implemented, this function * needs to be updated to support duration field calculation. * * RTS: time needed to transmit pending data/mgmt frame plus * one CTS frame plus one ACK frame plus 3 x SIFS * CTS: duration of immediately previous RTS minus time * required to transmit CTS and its SIFS * ACK: 0 if immediately previous directed data/mgmt had * more=0, with more=1 duration in ACK frame is duration * from previous frame minus time needed to transmit ACK * and its SIFS * PS Poll: BIT(15) | BIT(14) | aid */ return 0; } /* data/mgmt */ if (0 /* FIX: data/mgmt during CFP */) return cpu_to_le16(32768); if (group_addr) /* Group address as the destination - no ACK */ return 0; /* Individual destination address: * IEEE 802.11, Ch. 9.6 (after IEEE 802.11g changes) * CTS and ACK frames shall be transmitted using the highest rate in * basic rate set that is less than or equal to the rate of the * immediately previous frame and that is using the same modulation * (CCK or OFDM). If no basic rate set matches with these requirements, * the highest mandatory rate of the PHY that is less than or equal to * the rate of the previous frame is used. * Mandatory rates for IEEE 802.11g PHY: 1, 2, 5.5, 11, 6, 12, 24 Mbps */ rate = -1; /* use lowest available if everything fails */ mrate = sband->bitrates[0].bitrate; for (i = 0; i < sband->n_bitrates; i++) { struct ieee80211_rate *r = &sband->bitrates[i]; if (r->bitrate > txrate->bitrate) break; if ((rate_flags & r->flags) != rate_flags) continue; if (tx->sdata->vif.bss_conf.basic_rates & BIT(i)) rate = DIV_ROUND_UP(r->bitrate, 1 << shift); switch (sband->band) { case IEEE80211_BAND_2GHZ: { u32 flag; if (tx->sdata->flags & IEEE80211_SDATA_OPERATING_GMODE) flag = IEEE80211_RATE_MANDATORY_G; else flag = IEEE80211_RATE_MANDATORY_B; if (r->flags & flag) mrate = r->bitrate; break; } case IEEE80211_BAND_5GHZ: if (r->flags & IEEE80211_RATE_MANDATORY_A) mrate = r->bitrate; break; case IEEE80211_BAND_60GHZ: /* TODO, for now fall through */ case IEEE80211_NUM_BANDS: WARN_ON(1); break; } } if (rate == -1) { /* No matching basic rate found; use highest suitable mandatory * PHY rate */ rate = DIV_ROUND_UP(mrate, 1 << shift); } /* Don't calculate ACKs for QoS Frames with NoAck Policy set */ if (ieee80211_is_data_qos(hdr->frame_control) && *(ieee80211_get_qos_ctl(hdr)) & IEEE80211_QOS_CTL_ACK_POLICY_NOACK) dur = 0; else /* Time needed to transmit ACK * (10 bytes + 4-byte FCS = 112 bits) plus SIFS; rounded up * to closest integer */ dur = ieee80211_frame_duration(sband->band, 10, rate, erp, tx->sdata->vif.bss_conf.use_short_preamble, shift); if (next_frag_len) { /* Frame is fragmented: duration increases with time needed to * transmit next fragment plus ACK and 2 x SIFS. */ dur *= 2; /* ACK + SIFS */ /* next fragment */ dur += ieee80211_frame_duration(sband->band, next_frag_len, txrate->bitrate, erp, tx->sdata->vif.bss_conf.use_short_preamble, shift); } return cpu_to_le16(dur); } /* tx handlers */ static ieee80211_tx_result debug_noinline ieee80211_tx_h_dynamic_ps(struct ieee80211_tx_data *tx) { struct ieee80211_local *local = tx->local; struct ieee80211_if_managed *ifmgd; /* driver doesn't support power save */ if (!(local->hw.flags & IEEE80211_HW_SUPPORTS_PS)) return TX_CONTINUE; /* hardware does dynamic power save */ if (local->hw.flags & IEEE80211_HW_SUPPORTS_DYNAMIC_PS) return TX_CONTINUE; /* dynamic power save disabled */ if (local->hw.conf.dynamic_ps_timeout <= 0) return TX_CONTINUE; /* we are scanning, don't enable power save */ if (local->scanning) return TX_CONTINUE; if (!local->ps_sdata) return TX_CONTINUE; /* No point if we're going to suspend */ if (local->quiescing) return TX_CONTINUE; /* dynamic ps is supported only in managed mode */ if (tx->sdata->vif.type != NL80211_IFTYPE_STATION) return TX_CONTINUE; ifmgd = &tx->sdata->u.mgd; /* * Don't wakeup from power save if u-apsd is enabled, voip ac has * u-apsd enabled and the frame is in voip class. This effectively * means that even if all access categories have u-apsd enabled, in * practise u-apsd is only used with the voip ac. This is a * workaround for the case when received voip class packets do not * have correct qos tag for some reason, due the network or the * peer application. * * Note: ifmgd->uapsd_queues access is racy here. If the value is * changed via debugfs, user needs to reassociate manually to have * everything in sync. */ if ((ifmgd->flags & IEEE80211_STA_UAPSD_ENABLED) && (ifmgd->uapsd_queues & IEEE80211_WMM_IE_STA_QOSINFO_AC_VO) && skb_get_queue_mapping(tx->skb) == IEEE80211_AC_VO) return TX_CONTINUE; if (local->hw.conf.flags & IEEE80211_CONF_PS) { ieee80211_stop_queues_by_reason(&local->hw, IEEE80211_MAX_QUEUE_MAP, IEEE80211_QUEUE_STOP_REASON_PS); ifmgd->flags &= ~IEEE80211_STA_NULLFUNC_ACKED; ieee80211_queue_work(&local->hw, &local->dynamic_ps_disable_work); } /* Don't restart the timer if we're not disassociated */ if (!ifmgd->associated) return TX_CONTINUE; mod_timer(&local->dynamic_ps_timer, jiffies + msecs_to_jiffies(local->hw.conf.dynamic_ps_timeout)); return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_check_assoc(struct ieee80211_tx_data *tx) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); bool assoc = false; if (unlikely(info->flags & IEEE80211_TX_CTL_INJECTED)) return TX_CONTINUE; if (unlikely(test_bit(SCAN_SW_SCANNING, &tx->local->scanning)) && test_bit(SDATA_STATE_OFFCHANNEL, &tx->sdata->state) && !ieee80211_is_probe_req(hdr->frame_control) && !ieee80211_is_nullfunc(hdr->frame_control)) /* * When software scanning only nullfunc frames (to notify * the sleep state to the AP) and probe requests (for the * active scan) are allowed, all other frames should not be * sent and we should not get here, but if we do * nonetheless, drop them to avoid sending them * off-channel. See the link below and * ieee80211_start_scan() for more. * * http://article.gmane.org/gmane.linux.kernel.wireless.general/30089 */ return TX_DROP; if (tx->sdata->vif.type == NL80211_IFTYPE_WDS) return TX_CONTINUE; if (tx->sdata->vif.type == NL80211_IFTYPE_MESH_POINT) return TX_CONTINUE; if (tx->flags & IEEE80211_TX_PS_BUFFERED) return TX_CONTINUE; if (tx->sta) assoc = test_sta_flag(tx->sta, WLAN_STA_ASSOC); if (likely(tx->flags & IEEE80211_TX_UNICAST)) { if (unlikely(!assoc && ieee80211_is_data(hdr->frame_control))) { #ifdef CONFIG_MAC80211_VERBOSE_DEBUG sdata_info(tx->sdata, "dropped data frame to not associated station %pM\n", hdr->addr1); #endif I802_DEBUG_INC(tx->local->tx_handlers_drop_not_assoc); return TX_DROP; } } else if (unlikely(tx->sdata->vif.type == NL80211_IFTYPE_AP && ieee80211_is_data(hdr->frame_control) && !atomic_read(&tx->sdata->u.ap.num_mcast_sta))) { /* * No associated STAs - no need to send multicast * frames. */ return TX_DROP; } return TX_CONTINUE; } /* This function is called whenever the AP is about to exceed the maximum limit * of buffered frames for power saving STAs. This situation should not really * happen often during normal operation, so dropping the oldest buffered packet * from each queue should be OK to make some room for new frames. */ static void purge_old_ps_buffers(struct ieee80211_local *local) { int total = 0, purged = 0; struct sk_buff *skb; struct ieee80211_sub_if_data *sdata; struct sta_info *sta; list_for_each_entry_rcu(sdata, &local->interfaces, list) { struct ps_data *ps; if (sdata->vif.type == NL80211_IFTYPE_AP) ps = &sdata->u.ap.ps; else if (ieee80211_vif_is_mesh(&sdata->vif)) ps = &sdata->u.mesh.ps; else continue; skb = skb_dequeue(&ps->bc_buf); if (skb) { purged++; dev_kfree_skb(skb); } total += skb_queue_len(&ps->bc_buf); } /* * Drop one frame from each station from the lowest-priority * AC that has frames at all. */ list_for_each_entry_rcu(sta, &local->sta_list, list) { int ac; for (ac = IEEE80211_AC_BK; ac >= IEEE80211_AC_VO; ac--) { skb = skb_dequeue(&sta->ps_tx_buf[ac]); total += skb_queue_len(&sta->ps_tx_buf[ac]); if (skb) { purged++; ieee80211_free_txskb(&local->hw, skb); break; } } } local->total_ps_buffered = total; ps_dbg_hw(&local->hw, "PS buffers full - purged %d frames\n", purged); } static ieee80211_tx_result ieee80211_tx_h_multicast_ps_buf(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; struct ps_data *ps; /* * broadcast/multicast frame * * If any of the associated/peer stations is in power save mode, * the frame is buffered to be sent after DTIM beacon frame. * This is done either by the hardware or us. */ /* powersaving STAs currently only in AP/VLAN/mesh mode */ if (tx->sdata->vif.type == NL80211_IFTYPE_AP || tx->sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { if (!tx->sdata->bss) return TX_CONTINUE; ps = &tx->sdata->bss->ps; } else if (ieee80211_vif_is_mesh(&tx->sdata->vif)) { ps = &tx->sdata->u.mesh.ps; } else { return TX_CONTINUE; } /* no buffering for ordered frames */ if (ieee80211_has_order(hdr->frame_control)) return TX_CONTINUE; if (tx->local->hw.flags & IEEE80211_HW_QUEUE_CONTROL) info->hw_queue = tx->sdata->vif.cab_queue; /* no stations in PS mode */ if (!atomic_read(&ps->num_sta_ps)) return TX_CONTINUE; info->flags |= IEEE80211_TX_CTL_SEND_AFTER_DTIM; /* device releases frame after DTIM beacon */ if (!(tx->local->hw.flags & IEEE80211_HW_HOST_BROADCAST_PS_BUFFERING)) return TX_CONTINUE; /* buffered in mac80211 */ if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER) purge_old_ps_buffers(tx->local); if (skb_queue_len(&ps->bc_buf) >= AP_MAX_BC_BUFFER) { ps_dbg(tx->sdata, "BC TX buffer full - dropping the oldest frame\n"); dev_kfree_skb(skb_dequeue(&ps->bc_buf)); } else tx->local->total_ps_buffered++; skb_queue_tail(&ps->bc_buf, tx->skb); return TX_QUEUED; } static int ieee80211_use_mfp(__le16 fc, struct sta_info *sta, struct sk_buff *skb) { if (!ieee80211_is_mgmt(fc)) return 0; if (sta == NULL || !test_sta_flag(sta, WLAN_STA_MFP)) return 0; if (!ieee80211_is_robust_mgmt_frame((struct ieee80211_hdr *) skb->data)) return 0; return 1; } static ieee80211_tx_result ieee80211_tx_h_unicast_ps_buf(struct ieee80211_tx_data *tx) { struct sta_info *sta = tx->sta; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_local *local = tx->local; if (unlikely(!sta)) return TX_CONTINUE; if (unlikely((test_sta_flag(sta, WLAN_STA_PS_STA) || test_sta_flag(sta, WLAN_STA_PS_DRIVER)) && !(info->flags & IEEE80211_TX_CTL_NO_PS_BUFFER))) { int ac = skb_get_queue_mapping(tx->skb); ps_dbg(sta->sdata, "STA %pM aid %d: PS buffer for AC %d\n", sta->sta.addr, sta->sta.aid, ac); if (tx->local->total_ps_buffered >= TOTAL_MAX_TX_BUFFER) purge_old_ps_buffers(tx->local); if (skb_queue_len(&sta->ps_tx_buf[ac]) >= STA_MAX_TX_BUFFER) { struct sk_buff *old = skb_dequeue(&sta->ps_tx_buf[ac]); ps_dbg(tx->sdata, "STA %pM TX buffer for AC %d full - dropping oldest frame\n", sta->sta.addr, ac); ieee80211_free_txskb(&local->hw, old); } else tx->local->total_ps_buffered++; info->control.jiffies = jiffies; info->control.vif = &tx->sdata->vif; info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING; info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS; skb_queue_tail(&sta->ps_tx_buf[ac], tx->skb); if (!timer_pending(&local->sta_cleanup)) mod_timer(&local->sta_cleanup, round_jiffies(jiffies + STA_INFO_CLEANUP_INTERVAL)); /* * We queued up some frames, so the TIM bit might * need to be set, recalculate it. */ sta_info_recalc_tim(sta); return TX_QUEUED; } else if (unlikely(test_sta_flag(sta, WLAN_STA_PS_STA))) { ps_dbg(tx->sdata, "STA %pM in PS mode, but polling/in SP -> send frame\n", sta->sta.addr); } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_ps_buf(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; if (unlikely(tx->flags & IEEE80211_TX_PS_BUFFERED)) return TX_CONTINUE; /* only deauth, disassoc and action are bufferable MMPDUs */ if (ieee80211_is_mgmt(hdr->frame_control) && !ieee80211_is_deauth(hdr->frame_control) && !ieee80211_is_disassoc(hdr->frame_control) && !ieee80211_is_action(hdr->frame_control)) { if (tx->flags & IEEE80211_TX_UNICAST) info->flags |= IEEE80211_TX_CTL_NO_PS_BUFFER; return TX_CONTINUE; } if (tx->flags & IEEE80211_TX_UNICAST) return ieee80211_tx_h_unicast_ps_buf(tx); else return ieee80211_tx_h_multicast_ps_buf(tx); } static ieee80211_tx_result debug_noinline ieee80211_tx_h_check_control_port_protocol(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); if (unlikely(tx->sdata->control_port_protocol == tx->skb->protocol)) { if (tx->sdata->control_port_no_encrypt) info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; info->control.flags |= IEEE80211_TX_CTRL_PORT_CTRL_PROTO; } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_select_key(struct ieee80211_tx_data *tx) { struct ieee80211_key *key; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; if (unlikely(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT)) tx->key = NULL; else if (tx->sta && (key = rcu_dereference(tx->sta->ptk[tx->sta->ptk_idx]))) tx->key = key; else if (ieee80211_is_mgmt(hdr->frame_control) && is_multicast_ether_addr(hdr->addr1) && ieee80211_is_robust_mgmt_frame(hdr) && (key = rcu_dereference(tx->sdata->default_mgmt_key))) tx->key = key; else if (is_multicast_ether_addr(hdr->addr1) && (key = rcu_dereference(tx->sdata->default_multicast_key))) tx->key = key; else if (!is_multicast_ether_addr(hdr->addr1) && (key = rcu_dereference(tx->sdata->default_unicast_key))) tx->key = key; else if (info->flags & IEEE80211_TX_CTL_INJECTED) tx->key = NULL; else if (!tx->sdata->drop_unencrypted) tx->key = NULL; else if (tx->skb->protocol == tx->sdata->control_port_protocol) tx->key = NULL; else if (ieee80211_is_robust_mgmt_frame(hdr) && !(ieee80211_is_action(hdr->frame_control) && tx->sta && test_sta_flag(tx->sta, WLAN_STA_MFP))) tx->key = NULL; else if (ieee80211_is_mgmt(hdr->frame_control) && !ieee80211_is_robust_mgmt_frame(hdr)) tx->key = NULL; else { I802_DEBUG_INC(tx->local->tx_handlers_drop_unencrypted); return TX_DROP; } if (tx->key) { bool skip_hw = false; tx->key->tx_rx_count++; /* TODO: add threshold stuff again */ switch (tx->key->conf.cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: case WLAN_CIPHER_SUITE_TKIP: if (!ieee80211_is_data_present(hdr->frame_control)) tx->key = NULL; break; case WLAN_CIPHER_SUITE_CCMP: if (!ieee80211_is_data_present(hdr->frame_control) && !ieee80211_use_mfp(hdr->frame_control, tx->sta, tx->skb)) tx->key = NULL; else skip_hw = (tx->key->conf.flags & IEEE80211_KEY_FLAG_SW_MGMT_TX) && ieee80211_is_mgmt(hdr->frame_control); break; case WLAN_CIPHER_SUITE_AES_CMAC: if (!ieee80211_is_mgmt(hdr->frame_control)) tx->key = NULL; break; } if (unlikely(tx->key && tx->key->flags & KEY_FLAG_TAINTED && !ieee80211_is_deauth(hdr->frame_control))) return TX_DROP; if (!skip_hw && tx->key && tx->key->flags & KEY_FLAG_UPLOADED_TO_HARDWARE) info->control.hw_key = &tx->key->conf; } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_rate_ctrl(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (void *)tx->skb->data; struct ieee80211_supported_band *sband; u32 len; struct ieee80211_tx_rate_control txrc; struct ieee80211_sta_rates *ratetbl = NULL; bool assoc = false; memset(&txrc, 0, sizeof(txrc)); sband = tx->local->hw.wiphy->bands[info->band]; len = min_t(u32, tx->skb->len + FCS_LEN, tx->local->hw.wiphy->frag_threshold); /* set up the tx rate control struct we give the RC algo */ txrc.hw = &tx->local->hw; txrc.sband = sband; txrc.bss_conf = &tx->sdata->vif.bss_conf; txrc.skb = tx->skb; txrc.reported_rate.idx = -1; txrc.rate_idx_mask = tx->sdata->rc_rateidx_mask[info->band]; if (txrc.rate_idx_mask == (1 << sband->n_bitrates) - 1) txrc.max_rate_idx = -1; else txrc.max_rate_idx = fls(txrc.rate_idx_mask) - 1; if (tx->sdata->rc_has_mcs_mask[info->band]) txrc.rate_idx_mcs_mask = tx->sdata->rc_rateidx_mcs_mask[info->band]; txrc.bss = (tx->sdata->vif.type == NL80211_IFTYPE_AP || tx->sdata->vif.type == NL80211_IFTYPE_MESH_POINT || tx->sdata->vif.type == NL80211_IFTYPE_ADHOC); /* set up RTS protection if desired */ if (len > tx->local->hw.wiphy->rts_threshold) { txrc.rts = true; } info->control.use_rts = txrc.rts; info->control.use_cts_prot = tx->sdata->vif.bss_conf.use_cts_prot; /* * Use short preamble if the BSS can handle it, but not for * management frames unless we know the receiver can handle * that -- the management frame might be to a station that * just wants a probe response. */ if (tx->sdata->vif.bss_conf.use_short_preamble && (ieee80211_is_data(hdr->frame_control) || (tx->sta && test_sta_flag(tx->sta, WLAN_STA_SHORT_PREAMBLE)))) txrc.short_preamble = true; info->control.short_preamble = txrc.short_preamble; if (tx->sta) assoc = test_sta_flag(tx->sta, WLAN_STA_ASSOC); /* * Lets not bother rate control if we're associated and cannot * talk to the sta. This should not happen. */ if (WARN(test_bit(SCAN_SW_SCANNING, &tx->local->scanning) && assoc && !rate_usable_index_exists(sband, &tx->sta->sta), "%s: Dropped data frame as no usable bitrate found while " "scanning and associated. Target station: " "%pM on %d GHz band\n", tx->sdata->name, hdr->addr1, info->band ? 5 : 2)) return TX_DROP; /* * If we're associated with the sta at this point we know we can at * least send the frame at the lowest bit rate. */ rate_control_get_rate(tx->sdata, tx->sta, &txrc); if (tx->sta && !info->control.skip_table) ratetbl = rcu_dereference(tx->sta->sta.rates); if (unlikely(info->control.rates[0].idx < 0)) { if (ratetbl) { struct ieee80211_tx_rate rate = { .idx = ratetbl->rate[0].idx, .flags = ratetbl->rate[0].flags, .count = ratetbl->rate[0].count }; if (ratetbl->rate[0].idx < 0) return TX_DROP; tx->rate = rate; } else { return TX_DROP; } } else { tx->rate = info->control.rates[0]; } if (txrc.reported_rate.idx < 0) { txrc.reported_rate = tx->rate; if (tx->sta && ieee80211_is_data(hdr->frame_control)) tx->sta->last_tx_rate = txrc.reported_rate; } else if (tx->sta) tx->sta->last_tx_rate = txrc.reported_rate; if (ratetbl) return TX_CONTINUE; if (unlikely(!info->control.rates[0].count)) info->control.rates[0].count = 1; if (WARN_ON_ONCE((info->control.rates[0].count > 1) && (info->flags & IEEE80211_TX_CTL_NO_ACK))) info->control.rates[0].count = 1; return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_sequence(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *)tx->skb->data; u16 *seq; u8 *qc; int tid; /* * Packet injection may want to control the sequence * number, if we have no matching interface then we * neither assign one ourselves nor ask the driver to. */ if (unlikely(info->control.vif->type == NL80211_IFTYPE_MONITOR)) return TX_CONTINUE; if (unlikely(ieee80211_is_ctl(hdr->frame_control))) return TX_CONTINUE; if (ieee80211_hdrlen(hdr->frame_control) < 24) return TX_CONTINUE; if (ieee80211_is_qos_nullfunc(hdr->frame_control)) return TX_CONTINUE; /* * Anything but QoS data that has a sequence number field * (is long enough) gets a sequence number from the global * counter. QoS data frames with a multicast destination * also use the global counter (802.11-2012 9.3.2.10). */ if (!ieee80211_is_data_qos(hdr->frame_control) || is_multicast_ether_addr(hdr->addr1)) { /* driver should assign sequence number */ info->flags |= IEEE80211_TX_CTL_ASSIGN_SEQ; /* for pure STA mode without beacons, we can do it */ hdr->seq_ctrl = cpu_to_le16(tx->sdata->sequence_number); tx->sdata->sequence_number += 0x10; return TX_CONTINUE; } /* * This should be true for injected/management frames only, for * management frames we have set the IEEE80211_TX_CTL_ASSIGN_SEQ * above since they are not QoS-data frames. */ if (!tx->sta) return TX_CONTINUE; /* include per-STA, per-TID sequence counter */ qc = ieee80211_get_qos_ctl(hdr); tid = *qc & IEEE80211_QOS_CTL_TID_MASK; seq = &tx->sta->tid_seq[tid]; hdr->seq_ctrl = cpu_to_le16(*seq); /* Increase the sequence number. */ *seq = (*seq + 0x10) & IEEE80211_SCTL_SEQ; return TX_CONTINUE; } static int ieee80211_fragment(struct ieee80211_tx_data *tx, struct sk_buff *skb, int hdrlen, int frag_threshold) { struct ieee80211_local *local = tx->local; struct ieee80211_tx_info *info; struct sk_buff *tmp; int per_fragm = frag_threshold - hdrlen - FCS_LEN; int pos = hdrlen + per_fragm; int rem = skb->len - hdrlen - per_fragm; if (WARN_ON(rem < 0)) return -EINVAL; /* first fragment was already added to queue by caller */ while (rem) { int fraglen = per_fragm; if (fraglen > rem) fraglen = rem; rem -= fraglen; tmp = dev_alloc_skb(local->tx_headroom + frag_threshold + tx->sdata->encrypt_headroom + IEEE80211_ENCRYPT_TAILROOM); if (!tmp) return -ENOMEM; __skb_queue_tail(&tx->skbs, tmp); skb_reserve(tmp, local->tx_headroom + tx->sdata->encrypt_headroom); /* copy control information */ memcpy(tmp->cb, skb->cb, sizeof(tmp->cb)); info = IEEE80211_SKB_CB(tmp); info->flags &= ~(IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_FIRST_FRAGMENT); if (rem) info->flags |= IEEE80211_TX_CTL_MORE_FRAMES; skb_copy_queue_mapping(tmp, skb); tmp->priority = skb->priority; tmp->dev = skb->dev; /* copy header and data */ memcpy(skb_put(tmp, hdrlen), skb->data, hdrlen); memcpy(skb_put(tmp, fraglen), skb->data + pos, fraglen); pos += fraglen; } /* adjust first fragment's length */ skb_trim(skb, hdrlen + per_fragm); return 0; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_fragment(struct ieee80211_tx_data *tx) { struct sk_buff *skb = tx->skb; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_hdr *hdr = (void *)skb->data; int frag_threshold = tx->local->hw.wiphy->frag_threshold; int hdrlen; int fragnum; /* no matter what happens, tx->skb moves to tx->skbs */ __skb_queue_tail(&tx->skbs, skb); tx->skb = NULL; if (info->flags & IEEE80211_TX_CTL_DONTFRAG) return TX_CONTINUE; if (tx->local->ops->set_frag_threshold) return TX_CONTINUE; /* * Warn when submitting a fragmented A-MPDU frame and drop it. * This scenario is handled in ieee80211_tx_prepare but extra * caution taken here as fragmented ampdu may cause Tx stop. */ if (WARN_ON(info->flags & IEEE80211_TX_CTL_AMPDU)) return TX_DROP; hdrlen = ieee80211_hdrlen(hdr->frame_control); /* internal error, why isn't DONTFRAG set? */ if (WARN_ON(skb->len + FCS_LEN <= frag_threshold)) return TX_DROP; /* * Now fragment the frame. This will allocate all the fragments and * chain them (using skb as the first fragment) to skb->next. * During transmission, we will remove the successfully transmitted * fragments from this list. When the low-level driver rejects one * of the fragments then we will simply pretend to accept the skb * but store it away as pending. */ if (ieee80211_fragment(tx, skb, hdrlen, frag_threshold)) return TX_DROP; /* update duration/seq/flags of fragments */ fragnum = 0; skb_queue_walk(&tx->skbs, skb) { const __le16 morefrags = cpu_to_le16(IEEE80211_FCTL_MOREFRAGS); hdr = (void *)skb->data; info = IEEE80211_SKB_CB(skb); if (!skb_queue_is_last(&tx->skbs, skb)) { hdr->frame_control |= morefrags; /* * No multi-rate retries for fragmented frames, that * would completely throw off the NAV at other STAs. */ info->control.rates[1].idx = -1; info->control.rates[2].idx = -1; info->control.rates[3].idx = -1; BUILD_BUG_ON(IEEE80211_TX_MAX_RATES != 4); info->flags &= ~IEEE80211_TX_CTL_RATE_CTRL_PROBE; } else { hdr->frame_control &= ~morefrags; } hdr->seq_ctrl |= cpu_to_le16(fragnum & IEEE80211_SCTL_FRAG); fragnum++; } return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_stats(struct ieee80211_tx_data *tx) { struct sk_buff *skb; int ac = -1; if (!tx->sta) return TX_CONTINUE; skb_queue_walk(&tx->skbs, skb) { ac = skb_get_queue_mapping(skb); tx->sta->tx_fragments++; tx->sta->tx_bytes[ac] += skb->len; } if (ac >= 0) tx->sta->tx_packets[ac]++; return TX_CONTINUE; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_encrypt(struct ieee80211_tx_data *tx) { if (!tx->key) return TX_CONTINUE; switch (tx->key->conf.cipher) { case WLAN_CIPHER_SUITE_WEP40: case WLAN_CIPHER_SUITE_WEP104: return ieee80211_crypto_wep_encrypt(tx); case WLAN_CIPHER_SUITE_TKIP: return ieee80211_crypto_tkip_encrypt(tx); case WLAN_CIPHER_SUITE_CCMP: return ieee80211_crypto_ccmp_encrypt(tx); case WLAN_CIPHER_SUITE_AES_CMAC: return ieee80211_crypto_aes_cmac_encrypt(tx); default: return ieee80211_crypto_hw_encrypt(tx); } return TX_DROP; } static ieee80211_tx_result debug_noinline ieee80211_tx_h_calculate_duration(struct ieee80211_tx_data *tx) { struct sk_buff *skb; struct ieee80211_hdr *hdr; int next_len; bool group_addr; skb_queue_walk(&tx->skbs, skb) { hdr = (void *) skb->data; if (unlikely(ieee80211_is_pspoll(hdr->frame_control))) break; /* must not overwrite AID */ if (!skb_queue_is_last(&tx->skbs, skb)) { struct sk_buff *next = skb_queue_next(&tx->skbs, skb); next_len = next->len; } else next_len = 0; group_addr = is_multicast_ether_addr(hdr->addr1); hdr->duration_id = ieee80211_duration(tx, skb, group_addr, next_len); } return TX_CONTINUE; } /* actual transmit path */ static bool ieee80211_tx_prep_agg(struct ieee80211_tx_data *tx, struct sk_buff *skb, struct ieee80211_tx_info *info, struct tid_ampdu_tx *tid_tx, int tid) { bool queued = false; bool reset_agg_timer = false; struct sk_buff *purge_skb = NULL; if (test_bit(HT_AGG_STATE_OPERATIONAL, &tid_tx->state)) { info->flags |= IEEE80211_TX_CTL_AMPDU; reset_agg_timer = true; } else if (test_bit(HT_AGG_STATE_WANT_START, &tid_tx->state)) { /* * nothing -- this aggregation session is being started * but that might still fail with the driver */ } else { spin_lock(&tx->sta->lock); /* * Need to re-check now, because we may get here * * 1) in the window during which the setup is actually * already done, but not marked yet because not all * packets are spliced over to the driver pending * queue yet -- if this happened we acquire the lock * either before or after the splice happens, but * need to recheck which of these cases happened. * * 2) during session teardown, if the OPERATIONAL bit * was cleared due to the teardown but the pointer * hasn't been assigned NULL yet (or we loaded it * before it was assigned) -- in this case it may * now be NULL which means we should just let the * packet pass through because splicing the frames * back is already done. */ tid_tx = rcu_dereference_protected_tid_tx(tx->sta, tid); if (!tid_tx) { /* do nothing, let packet pass through */ } else if (test_bit(HT_AGG_STATE_OPERATIONAL, &tid_tx->state)) { info->flags |= IEEE80211_TX_CTL_AMPDU; reset_agg_timer = true; } else { queued = true; info->control.vif = &tx->sdata->vif; info->flags |= IEEE80211_TX_INTFL_NEED_TXPROCESSING; info->flags &= ~IEEE80211_TX_TEMPORARY_FLAGS; __skb_queue_tail(&tid_tx->pending, skb); if (skb_queue_len(&tid_tx->pending) > STA_MAX_TX_BUFFER) purge_skb = __skb_dequeue(&tid_tx->pending); } spin_unlock(&tx->sta->lock); if (purge_skb) ieee80211_free_txskb(&tx->local->hw, purge_skb); } /* reset session timer */ if (reset_agg_timer && tid_tx->timeout) tid_tx->last_tx = jiffies; return queued; } /* * initialises @tx */ static ieee80211_tx_result ieee80211_tx_prepare(struct ieee80211_sub_if_data *sdata, struct ieee80211_tx_data *tx, struct sk_buff *skb) { struct ieee80211_local *local = sdata->local; struct ieee80211_hdr *hdr; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int tid; u8 *qc; memset(tx, 0, sizeof(*tx)); tx->skb = skb; tx->local = local; tx->sdata = sdata; __skb_queue_head_init(&tx->skbs); /* * If this flag is set to true anywhere, and we get here, * we are doing the needed processing, so remove the flag * now. */ info->flags &= ~IEEE80211_TX_INTFL_NEED_TXPROCESSING; hdr = (struct ieee80211_hdr *) skb->data; if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) { tx->sta = rcu_dereference(sdata->u.vlan.sta); if (!tx->sta && sdata->dev->ieee80211_ptr->use_4addr) return TX_DROP; } else if (info->flags & (IEEE80211_TX_CTL_INJECTED | IEEE80211_TX_INTFL_NL80211_FRAME_TX) || tx->sdata->control_port_protocol == tx->skb->protocol) { tx->sta = sta_info_get_bss(sdata, hdr->addr1); } if (!tx->sta) tx->sta = sta_info_get(sdata, hdr->addr1); if (tx->sta && ieee80211_is_data_qos(hdr->frame_control) && !ieee80211_is_qos_nullfunc(hdr->frame_control) && (local->hw.flags & IEEE80211_HW_AMPDU_AGGREGATION) && !(local->hw.flags & IEEE80211_HW_TX_AMPDU_SETUP_IN_HW)) { struct tid_ampdu_tx *tid_tx; qc = ieee80211_get_qos_ctl(hdr); tid = *qc & IEEE80211_QOS_CTL_TID_MASK; tid_tx = rcu_dereference(tx->sta->ampdu_mlme.tid_tx[tid]); if (tid_tx) { bool queued; queued = ieee80211_tx_prep_agg(tx, skb, info, tid_tx, tid); if (unlikely(queued)) return TX_QUEUED; } } if (is_multicast_ether_addr(hdr->addr1)) { tx->flags &= ~IEEE80211_TX_UNICAST; info->flags |= IEEE80211_TX_CTL_NO_ACK; } else tx->flags |= IEEE80211_TX_UNICAST; if (!(info->flags & IEEE80211_TX_CTL_DONTFRAG)) { if (!(tx->flags & IEEE80211_TX_UNICAST) || skb->len + FCS_LEN <= local->hw.wiphy->frag_threshold || info->flags & IEEE80211_TX_CTL_AMPDU) info->flags |= IEEE80211_TX_CTL_DONTFRAG; } if (!tx->sta) info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT; else if (test_and_clear_sta_flag(tx->sta, WLAN_STA_CLEAR_PS_FILT)) info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT; info->flags |= IEEE80211_TX_CTL_FIRST_FRAGMENT; return TX_CONTINUE; } static bool ieee80211_tx_frags(struct ieee80211_local *local, struct ieee80211_vif *vif, struct ieee80211_sta *sta, struct sk_buff_head *skbs, bool txpending) { struct ieee80211_tx_control control; struct sk_buff *skb, *tmp; unsigned long flags; skb_queue_walk_safe(skbs, skb, tmp) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int q = info->hw_queue; #ifdef CONFIG_MAC80211_VERBOSE_DEBUG if (WARN_ON_ONCE(q >= local->hw.queues)) { __skb_unlink(skb, skbs); ieee80211_free_txskb(&local->hw, skb); continue; } #endif spin_lock_irqsave(&local->queue_stop_reason_lock, flags); if (local->queue_stop_reasons[q] || (!txpending && !skb_queue_empty(&local->pending[q]))) { if (unlikely(info->flags & IEEE80211_TX_INTFL_OFFCHAN_TX_OK)) { if (local->queue_stop_reasons[q] & ~BIT(IEEE80211_QUEUE_STOP_REASON_OFFCHANNEL)) { /* * Drop off-channel frames if queues * are stopped for any reason other * than off-channel operation. Never * queue them. */ spin_unlock_irqrestore( &local->queue_stop_reason_lock, flags); ieee80211_purge_tx_queue(&local->hw, skbs); return true; } } else { /* * Since queue is stopped, queue up frames for * later transmission from the tx-pending * tasklet when the queue is woken again. */ if (txpending) skb_queue_splice_init(skbs, &local->pending[q]); else skb_queue_splice_tail_init(skbs, &local->pending[q]); spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); return false; } } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); info->control.vif = vif; control.sta = sta; __skb_unlink(skb, skbs); drv_tx(local, &control, skb); } return true; } /* * Returns false if the frame couldn't be transmitted but was queued instead. */ static bool __ieee80211_tx(struct ieee80211_local *local, struct sk_buff_head *skbs, int led_len, struct sta_info *sta, bool txpending) { struct ieee80211_tx_info *info; struct ieee80211_sub_if_data *sdata; struct ieee80211_vif *vif; struct ieee80211_sta *pubsta; struct sk_buff *skb; bool result = true; __le16 fc; if (WARN_ON(skb_queue_empty(skbs))) return true; skb = skb_peek(skbs); fc = ((struct ieee80211_hdr *)skb->data)->frame_control; info = IEEE80211_SKB_CB(skb); sdata = vif_to_sdata(info->control.vif); if (sta && !sta->uploaded) sta = NULL; if (sta) pubsta = &sta->sta; else pubsta = NULL; switch (sdata->vif.type) { case NL80211_IFTYPE_MONITOR: if (sdata->u.mntr_flags & MONITOR_FLAG_ACTIVE) { vif = &sdata->vif; break; } sdata = rcu_dereference(local->monitor_sdata); if (sdata) { vif = &sdata->vif; info->hw_queue = vif->hw_queue[skb_get_queue_mapping(skb)]; } else if (local->hw.flags & IEEE80211_HW_QUEUE_CONTROL) { dev_kfree_skb(skb); return true; } else vif = NULL; break; case NL80211_IFTYPE_AP_VLAN: sdata = container_of(sdata->bss, struct ieee80211_sub_if_data, u.ap); /* fall through */ default: vif = &sdata->vif; break; } result = ieee80211_tx_frags(local, vif, pubsta, skbs, txpending); ieee80211_tpt_led_trig_tx(local, fc, led_len); WARN_ON_ONCE(!skb_queue_empty(skbs)); return result; } /* * Invoke TX handlers, return 0 on success and non-zero if the * frame was dropped or queued. */ static int invoke_tx_handlers(struct ieee80211_tx_data *tx) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(tx->skb); ieee80211_tx_result res = TX_DROP; #define CALL_TXH(txh) \ do { \ res = txh(tx); \ if (res != TX_CONTINUE) \ goto txh_done; \ } while (0) CALL_TXH(ieee80211_tx_h_dynamic_ps); CALL_TXH(ieee80211_tx_h_check_assoc); CALL_TXH(ieee80211_tx_h_ps_buf); CALL_TXH(ieee80211_tx_h_check_control_port_protocol); CALL_TXH(ieee80211_tx_h_select_key); if (!(tx->local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL)) CALL_TXH(ieee80211_tx_h_rate_ctrl); if (unlikely(info->flags & IEEE80211_TX_INTFL_RETRANSMISSION)) { __skb_queue_tail(&tx->skbs, tx->skb); tx->skb = NULL; goto txh_done; } CALL_TXH(ieee80211_tx_h_michael_mic_add); CALL_TXH(ieee80211_tx_h_sequence); CALL_TXH(ieee80211_tx_h_fragment); /* handlers after fragment must be aware of tx info fragmentation! */ CALL_TXH(ieee80211_tx_h_stats); CALL_TXH(ieee80211_tx_h_encrypt); if (!(tx->local->hw.flags & IEEE80211_HW_HAS_RATE_CONTROL)) CALL_TXH(ieee80211_tx_h_calculate_duration); #undef CALL_TXH txh_done: if (unlikely(res == TX_DROP)) { I802_DEBUG_INC(tx->local->tx_handlers_drop); if (tx->skb) ieee80211_free_txskb(&tx->local->hw, tx->skb); else ieee80211_purge_tx_queue(&tx->local->hw, &tx->skbs); return -1; } else if (unlikely(res == TX_QUEUED)) { I802_DEBUG_INC(tx->local->tx_handlers_queued); return -1; } return 0; } bool ieee80211_tx_prepare_skb(struct ieee80211_hw *hw, struct ieee80211_vif *vif, struct sk_buff *skb, int band, struct ieee80211_sta **sta) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_tx_data tx; if (ieee80211_tx_prepare(sdata, &tx, skb) == TX_DROP) return false; info->band = band; info->control.vif = vif; info->hw_queue = vif->hw_queue[skb_get_queue_mapping(skb)]; if (invoke_tx_handlers(&tx)) return false; if (sta) { if (tx.sta) *sta = &tx.sta->sta; else *sta = NULL; } return true; } EXPORT_SYMBOL(ieee80211_tx_prepare_skb); /* * Returns false if the frame couldn't be transmitted but was queued instead. */ static bool ieee80211_tx(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, bool txpending, enum ieee80211_band band) { struct ieee80211_local *local = sdata->local; struct ieee80211_tx_data tx; ieee80211_tx_result res_prepare; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); bool result = true; int led_len; if (unlikely(skb->len < 10)) { dev_kfree_skb(skb); return true; } /* initialises tx */ led_len = skb->len; res_prepare = ieee80211_tx_prepare(sdata, &tx, skb); if (unlikely(res_prepare == TX_DROP)) { ieee80211_free_txskb(&local->hw, skb); return true; } else if (unlikely(res_prepare == TX_QUEUED)) { return true; } info->band = band; /* set up hw_queue value early */ if (!(info->flags & IEEE80211_TX_CTL_TX_OFFCHAN) || !(local->hw.flags & IEEE80211_HW_QUEUE_CONTROL)) info->hw_queue = sdata->vif.hw_queue[skb_get_queue_mapping(skb)]; if (!invoke_tx_handlers(&tx)) result = __ieee80211_tx(local, &tx.skbs, led_len, tx.sta, txpending); return result; } /* device xmit handlers */ static int ieee80211_skb_resize(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, int head_need, bool may_encrypt) { struct ieee80211_local *local = sdata->local; int tail_need = 0; if (may_encrypt && sdata->crypto_tx_tailroom_needed_cnt) { tail_need = IEEE80211_ENCRYPT_TAILROOM; tail_need -= skb_tailroom(skb); tail_need = max_t(int, tail_need, 0); } if (skb_cloned(skb)) I802_DEBUG_INC(local->tx_expand_skb_head_cloned); else if (head_need || tail_need) I802_DEBUG_INC(local->tx_expand_skb_head); else return 0; if (pskb_expand_head(skb, head_need, tail_need, GFP_ATOMIC)) { wiphy_debug(local->hw.wiphy, "failed to reallocate TX buffer\n"); return -ENOMEM; } return 0; } void ieee80211_xmit(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, enum ieee80211_band band) { struct ieee80211_local *local = sdata->local; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; int headroom; bool may_encrypt; may_encrypt = !(info->flags & IEEE80211_TX_INTFL_DONT_ENCRYPT); headroom = local->tx_headroom; if (may_encrypt) headroom += sdata->encrypt_headroom; headroom -= skb_headroom(skb); headroom = max_t(int, 0, headroom); if (ieee80211_skb_resize(sdata, skb, headroom, may_encrypt)) { ieee80211_free_txskb(&local->hw, skb); return; } hdr = (struct ieee80211_hdr *) skb->data; info->control.vif = &sdata->vif; if (ieee80211_vif_is_mesh(&sdata->vif)) { if (ieee80211_is_data(hdr->frame_control) && is_unicast_ether_addr(hdr->addr1)) { if (mesh_nexthop_resolve(sdata, skb)) return; /* skb queued: don't free */ } else { ieee80211_mps_set_frame_flags(sdata, NULL, hdr); } } ieee80211_set_qos_hdr(sdata, skb); ieee80211_tx(sdata, skb, false, band); } static bool ieee80211_parse_tx_radiotap(struct sk_buff *skb) { struct ieee80211_radiotap_iterator iterator; struct ieee80211_radiotap_header *rthdr = (struct ieee80211_radiotap_header *) skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); int ret = ieee80211_radiotap_iterator_init(&iterator, rthdr, skb->len, NULL); u16 txflags; info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT | IEEE80211_TX_CTL_DONTFRAG; /* * for every radiotap entry that is present * (ieee80211_radiotap_iterator_next returns -ENOENT when no more * entries present, or -EINVAL on error) */ while (!ret) { ret = ieee80211_radiotap_iterator_next(&iterator); if (ret) continue; /* see if this argument is something we can use */ switch (iterator.this_arg_index) { /* * You must take care when dereferencing iterator.this_arg * for multibyte types... the pointer is not aligned. Use * get_unaligned((type *)iterator.this_arg) to dereference * iterator.this_arg for type "type" safely on all arches. */ case IEEE80211_RADIOTAP_FLAGS: if (*iterator.this_arg & IEEE80211_RADIOTAP_F_FCS) { /* * this indicates that the skb we have been * handed has the 32-bit FCS CRC at the end... * we should react to that by snipping it off * because it will be recomputed and added * on transmission */ if (skb->len < (iterator._max_length + FCS_LEN)) return false; skb_trim(skb, skb->len - FCS_LEN); } if (*iterator.this_arg & IEEE80211_RADIOTAP_F_WEP) info->flags &= ~IEEE80211_TX_INTFL_DONT_ENCRYPT; if (*iterator.this_arg & IEEE80211_RADIOTAP_F_FRAG) info->flags &= ~IEEE80211_TX_CTL_DONTFRAG; break; case IEEE80211_RADIOTAP_TX_FLAGS: txflags = get_unaligned_le16(iterator.this_arg); if (txflags & IEEE80211_RADIOTAP_F_TX_NOACK) info->flags |= IEEE80211_TX_CTL_NO_ACK; break; /* * Please update the file * Documentation/networking/mac80211-injection.txt * when parsing new fields here. */ default: break; } } if (ret != -ENOENT) /* ie, if we didn't simply run out of fields */ return false; /* * remove the radiotap header * iterator->_max_length was sanity-checked against * skb->len by iterator init */ skb_pull(skb, iterator._max_length); return true; } netdev_tx_t ieee80211_monitor_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct ieee80211_local *local = wdev_priv(dev->ieee80211_ptr); struct ieee80211_chanctx_conf *chanctx_conf; struct ieee80211_channel *chan; struct ieee80211_radiotap_header *prthdr = (struct ieee80211_radiotap_header *)skb->data; struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_hdr *hdr; struct ieee80211_sub_if_data *tmp_sdata, *sdata; u16 len_rthdr; int hdrlen; /* check for not even having the fixed radiotap header part */ if (unlikely(skb->len < sizeof(struct ieee80211_radiotap_header))) goto fail; /* too short to be possibly valid */ /* is it a header version we can trust to find length from? */ if (unlikely(prthdr->it_version)) goto fail; /* only version 0 is supported */ /* then there must be a radiotap header with a length we can use */ len_rthdr = ieee80211_get_radiotap_len(skb->data); /* does the skb contain enough to deliver on the alleged length? */ if (unlikely(skb->len < len_rthdr)) goto fail; /* skb too short for claimed rt header extent */ /* * fix up the pointers accounting for the radiotap * header still being in there. We are being given * a precooked IEEE80211 header so no need for * normal processing */ skb_set_mac_header(skb, len_rthdr); /* * these are just fixed to the end of the rt area since we * don't have any better information and at this point, nobody cares */ skb_set_network_header(skb, len_rthdr); skb_set_transport_header(skb, len_rthdr); if (skb->len < len_rthdr + 2) goto fail; hdr = (struct ieee80211_hdr *)(skb->data + len_rthdr); hdrlen = ieee80211_hdrlen(hdr->frame_control); if (skb->len < len_rthdr + hdrlen) goto fail; /* * Initialize skb->protocol if the injected frame is a data frame * carrying a rfc1042 header */ if (ieee80211_is_data(hdr->frame_control) && skb->len >= len_rthdr + hdrlen + sizeof(rfc1042_header) + 2) { u8 *payload = (u8 *)hdr + hdrlen; if (ether_addr_equal(payload, rfc1042_header)) skb->protocol = cpu_to_be16((payload[6] << 8) | payload[7]); } memset(info, 0, sizeof(*info)); info->flags = IEEE80211_TX_CTL_REQ_TX_STATUS | IEEE80211_TX_CTL_INJECTED; /* process and remove the injection radiotap header */ if (!ieee80211_parse_tx_radiotap(skb)) goto fail; rcu_read_lock(); /* * We process outgoing injected frames that have a local address * we handle as though they are non-injected frames. * This code here isn't entirely correct, the local MAC address * isn't always enough to find the interface to use; for proper * VLAN/WDS support we will need a different mechanism (which * likely isn't going to be monitor interfaces). */ sdata = IEEE80211_DEV_TO_SUB_IF(dev); list_for_each_entry_rcu(tmp_sdata, &local->interfaces, list) { if (!ieee80211_sdata_running(tmp_sdata)) continue; if (tmp_sdata->vif.type == NL80211_IFTYPE_MONITOR || tmp_sdata->vif.type == NL80211_IFTYPE_AP_VLAN || tmp_sdata->vif.type == NL80211_IFTYPE_WDS) continue; if (ether_addr_equal(tmp_sdata->vif.addr, hdr->addr2)) { sdata = tmp_sdata; break; } } chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) { tmp_sdata = rcu_dereference(local->monitor_sdata); if (tmp_sdata) chanctx_conf = rcu_dereference(tmp_sdata->vif.chanctx_conf); } if (chanctx_conf) chan = chanctx_conf->def.chan; else if (!local->use_chanctx) chan = local->_oper_chandef.chan; else goto fail_rcu; /* * Frame injection is not allowed if beaconing is not allowed * or if we need radar detection. Beaconing is usually not allowed when * the mode or operation (Adhoc, AP, Mesh) does not support DFS. * Passive scan is also used in world regulatory domains where * your country is not known and as such it should be treated as * NO TX unless the channel is explicitly allowed in which case * your current regulatory domain would not have the passive scan * flag. * * Since AP mode uses monitor interfaces to inject/TX management * frames we can make AP mode the exception to this rule once it * supports radar detection as its implementation can deal with * radar detection by itself. We can do that later by adding a * monitor flag interfaces used for AP support. */ if ((chan->flags & (IEEE80211_CHAN_NO_IR | IEEE80211_CHAN_RADAR))) goto fail_rcu; ieee80211_xmit(sdata, skb, chan->band); rcu_read_unlock(); return NETDEV_TX_OK; fail_rcu: rcu_read_unlock(); fail: dev_kfree_skb(skb); return NETDEV_TX_OK; /* meaning, we dealt with the skb */ } /* * Measure Tx frame arrival time for Tx latency statistics calculation * A single Tx frame latency should be measured from when it is entering the * Kernel until we receive Tx complete confirmation indication and the skb is * freed. */ static void ieee80211_tx_latency_start_msrmnt(struct ieee80211_local *local, struct sk_buff *skb) { struct timespec skb_arv; struct ieee80211_tx_latency_bin_ranges *tx_latency; tx_latency = rcu_dereference(local->tx_latency); if (!tx_latency) return; ktime_get_ts(&skb_arv); skb->tstamp = ktime_set(skb_arv.tv_sec, skb_arv.tv_nsec); } /** * ieee80211_subif_start_xmit - netif start_xmit function for Ethernet-type * subinterfaces (wlan#, WDS, and VLAN interfaces) * @skb: packet to be sent * @dev: incoming interface * * Returns: 0 on success (and frees skb in this case) or 1 on failure (skb will * not be freed, and caller is responsible for either retrying later or freeing * skb). * * This function takes in an Ethernet header and encapsulates it with suitable * IEEE 802.11 header based on which interface the packet is coming in. The * encapsulated packet will then be passed to master interface, wlan#.11, for * transmission (through low-level driver). */ netdev_tx_t ieee80211_subif_start_xmit(struct sk_buff *skb, struct net_device *dev) { struct ieee80211_sub_if_data *sdata = IEEE80211_DEV_TO_SUB_IF(dev); struct ieee80211_local *local = sdata->local; struct ieee80211_tx_info *info; int head_need; u16 ethertype, hdrlen, meshhdrlen = 0; __le16 fc; struct ieee80211_hdr hdr; struct ieee80211s_hdr mesh_hdr __maybe_unused; struct mesh_path __maybe_unused *mppath = NULL, *mpath = NULL; const u8 *encaps_data; int encaps_len, skip_header_bytes; int nh_pos, h_pos; struct sta_info *sta = NULL; bool wme_sta = false, authorized = false, tdls_auth = false; bool tdls_direct = false; bool multicast; u32 info_flags = 0; u16 info_id = 0; struct ieee80211_chanctx_conf *chanctx_conf; struct ieee80211_sub_if_data *ap_sdata; enum ieee80211_band band; if (unlikely(skb->len < ETH_HLEN)) goto fail; /* convert Ethernet header to proper 802.11 header (based on * operation mode) */ ethertype = (skb->data[12] << 8) | skb->data[13]; fc = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_DATA); rcu_read_lock(); /* Measure frame arrival for Tx latency statistics calculation */ ieee80211_tx_latency_start_msrmnt(local, skb); switch (sdata->vif.type) { case NL80211_IFTYPE_AP_VLAN: sta = rcu_dereference(sdata->u.vlan.sta); if (sta) { fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr.addr1, sta->sta.addr, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 30; authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED); wme_sta = test_sta_flag(sta, WLAN_STA_WME); } ap_sdata = container_of(sdata->bss, struct ieee80211_sub_if_data, u.ap); chanctx_conf = rcu_dereference(ap_sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; if (sta) break; /* fall through */ case NL80211_IFTYPE_AP: if (sdata->vif.type == NL80211_IFTYPE_AP) chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS); /* DA BSSID SA */ memcpy(hdr.addr1, skb->data, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 24; band = chanctx_conf->def.chan->band; break; case NL80211_IFTYPE_WDS: fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr.addr1, sdata->u.wds.remote_addr, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 30; /* * This is the exception! WDS style interfaces are prohibited * when channel contexts are in used so this must be valid */ band = local->hw.conf.chandef.chan->band; break; #ifdef CONFIG_MAC80211_MESH case NL80211_IFTYPE_MESH_POINT: if (!is_multicast_ether_addr(skb->data)) { struct sta_info *next_hop; bool mpp_lookup = true; mpath = mesh_path_lookup(sdata, skb->data); if (mpath) { mpp_lookup = false; next_hop = rcu_dereference(mpath->next_hop); if (!next_hop || !(mpath->flags & (MESH_PATH_ACTIVE | MESH_PATH_RESOLVING))) mpp_lookup = true; } if (mpp_lookup) mppath = mpp_path_lookup(sdata, skb->data); if (mppath && mpath) mesh_path_del(mpath->sdata, mpath->dst); } /* * Use address extension if it is a packet from * another interface or if we know the destination * is being proxied by a portal (i.e. portal address * differs from proxied address) */ if (ether_addr_equal(sdata->vif.addr, skb->data + ETH_ALEN) && !(mppath && !ether_addr_equal(mppath->mpp, skb->data))) { hdrlen = ieee80211_fill_mesh_addresses(&hdr, &fc, skb->data, skb->data + ETH_ALEN); meshhdrlen = ieee80211_new_mesh_header(sdata, &mesh_hdr, NULL, NULL); } else { /* DS -> MBSS (802.11-2012 13.11.3.3). * For unicast with unknown forwarding information, * destination might be in the MBSS or if that fails * forwarded to another mesh gate. In either case * resolution will be handled in ieee80211_xmit(), so * leave the original DA. This also works for mcast */ const u8 *mesh_da = skb->data; if (mppath) mesh_da = mppath->mpp; else if (mpath) mesh_da = mpath->dst; hdrlen = ieee80211_fill_mesh_addresses(&hdr, &fc, mesh_da, sdata->vif.addr); if (is_multicast_ether_addr(mesh_da)) /* DA TA mSA AE:SA */ meshhdrlen = ieee80211_new_mesh_header( sdata, &mesh_hdr, skb->data + ETH_ALEN, NULL); else /* RA TA mDA mSA AE:DA SA */ meshhdrlen = ieee80211_new_mesh_header( sdata, &mesh_hdr, skb->data, skb->data + ETH_ALEN); } chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; break; #endif case NL80211_IFTYPE_STATION: if (sdata->wdev.wiphy->flags & WIPHY_FLAG_SUPPORTS_TDLS) { bool tdls_peer = false; sta = sta_info_get(sdata, skb->data); if (sta) { authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED); wme_sta = test_sta_flag(sta, WLAN_STA_WME); tdls_peer = test_sta_flag(sta, WLAN_STA_TDLS_PEER); tdls_auth = test_sta_flag(sta, WLAN_STA_TDLS_PEER_AUTH); } /* * If the TDLS link is enabled, send everything * directly. Otherwise, allow TDLS setup frames * to be transmitted indirectly. */ tdls_direct = tdls_peer && (tdls_auth || !(ethertype == ETH_P_TDLS && skb->len > 14 && skb->data[14] == WLAN_TDLS_SNAP_RFTYPE)); } if (tdls_direct) { /* link during setup - throw out frames to peer */ if (!tdls_auth) goto fail_rcu; /* DA SA BSSID */ memcpy(hdr.addr1, skb->data, ETH_ALEN); memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN); memcpy(hdr.addr3, sdata->u.mgd.bssid, ETH_ALEN); hdrlen = 24; } else if (sdata->u.mgd.use_4addr && cpu_to_be16(ethertype) != sdata->control_port_protocol) { fc |= cpu_to_le16(IEEE80211_FCTL_FROMDS | IEEE80211_FCTL_TODS); /* RA TA DA SA */ memcpy(hdr.addr1, sdata->u.mgd.bssid, ETH_ALEN); memcpy(hdr.addr2, sdata->vif.addr, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); memcpy(hdr.addr4, skb->data + ETH_ALEN, ETH_ALEN); hdrlen = 30; } else { fc |= cpu_to_le16(IEEE80211_FCTL_TODS); /* BSSID SA DA */ memcpy(hdr.addr1, sdata->u.mgd.bssid, ETH_ALEN); memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN); memcpy(hdr.addr3, skb->data, ETH_ALEN); hdrlen = 24; } chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; break; case NL80211_IFTYPE_ADHOC: /* DA SA BSSID */ memcpy(hdr.addr1, skb->data, ETH_ALEN); memcpy(hdr.addr2, skb->data + ETH_ALEN, ETH_ALEN); memcpy(hdr.addr3, sdata->u.ibss.bssid, ETH_ALEN); hdrlen = 24; chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto fail_rcu; band = chanctx_conf->def.chan->band; break; default: goto fail_rcu; } /* * There's no need to try to look up the destination * if it is a multicast address (which can only happen * in AP mode) */ multicast = is_multicast_ether_addr(hdr.addr1); if (!multicast) { sta = sta_info_get(sdata, hdr.addr1); if (sta) { authorized = test_sta_flag(sta, WLAN_STA_AUTHORIZED); wme_sta = test_sta_flag(sta, WLAN_STA_WME); } } /* For mesh, the use of the QoS header is mandatory */ if (ieee80211_vif_is_mesh(&sdata->vif)) wme_sta = true; /* receiver and we are QoS enabled, use a QoS type frame */ if (wme_sta && local->hw.queues >= IEEE80211_NUM_ACS) { fc |= cpu_to_le16(IEEE80211_STYPE_QOS_DATA); hdrlen += 2; } /* * Drop unicast frames to unauthorised stations unless they are * EAPOL frames from the local station. */ if (unlikely(!ieee80211_vif_is_mesh(&sdata->vif) && !multicast && !authorized && (cpu_to_be16(ethertype) != sdata->control_port_protocol || !ether_addr_equal(sdata->vif.addr, skb->data + ETH_ALEN)))) { #ifdef CONFIG_MAC80211_VERBOSE_DEBUG net_info_ratelimited("%s: dropped frame to %pM (unauthorized port)\n", dev->name, hdr.addr1); #endif I802_DEBUG_INC(local->tx_handlers_drop_unauth_port); goto fail_rcu; } if (unlikely(!multicast && skb->sk && skb_shinfo(skb)->tx_flags & SKBTX_WIFI_STATUS)) { struct sk_buff *orig_skb = skb; skb = skb_clone(skb, GFP_ATOMIC); if (skb) { unsigned long flags; int id; spin_lock_irqsave(&local->ack_status_lock, flags); id = idr_alloc(&local->ack_status_frames, orig_skb, 1, 0x10000, GFP_ATOMIC); spin_unlock_irqrestore(&local->ack_status_lock, flags); if (id >= 0) { info_id = id; info_flags |= IEEE80211_TX_CTL_REQ_TX_STATUS; } else if (skb_shared(skb)) { kfree_skb(orig_skb); } else { kfree_skb(skb); skb = orig_skb; } } else { /* couldn't clone -- lose tx status ... */ skb = orig_skb; } } /* * If the skb is shared we need to obtain our own copy. */ if (skb_shared(skb)) { struct sk_buff *tmp_skb = skb; /* can't happen -- skb is a clone if info_id != 0 */ WARN_ON(info_id); skb = skb_clone(skb, GFP_ATOMIC); kfree_skb(tmp_skb); if (!skb) goto fail_rcu; } hdr.frame_control = fc; hdr.duration_id = 0; hdr.seq_ctrl = 0; skip_header_bytes = ETH_HLEN; if (ethertype == ETH_P_AARP || ethertype == ETH_P_IPX) { encaps_data = bridge_tunnel_header; encaps_len = sizeof(bridge_tunnel_header); skip_header_bytes -= 2; } else if (ethertype >= ETH_P_802_3_MIN) { encaps_data = rfc1042_header; encaps_len = sizeof(rfc1042_header); skip_header_bytes -= 2; } else { encaps_data = NULL; encaps_len = 0; } nh_pos = skb_network_header(skb) - skb->data; h_pos = skb_transport_header(skb) - skb->data; skb_pull(skb, skip_header_bytes); nh_pos -= skip_header_bytes; h_pos -= skip_header_bytes; head_need = hdrlen + encaps_len + meshhdrlen - skb_headroom(skb); /* * So we need to modify the skb header and hence need a copy of * that. The head_need variable above doesn't, so far, include * the needed header space that we don't need right away. If we * can, then we don't reallocate right now but only after the * frame arrives at the master device (if it does...) * * If we cannot, however, then we will reallocate to include all * the ever needed space. Also, if we need to reallocate it anyway, * make it big enough for everything we may ever need. */ if (head_need > 0 || skb_cloned(skb)) { head_need += sdata->encrypt_headroom; head_need += local->tx_headroom; head_need = max_t(int, 0, head_need); if (ieee80211_skb_resize(sdata, skb, head_need, true)) { ieee80211_free_txskb(&local->hw, skb); skb = NULL; goto fail_rcu; } } if (encaps_data) { memcpy(skb_push(skb, encaps_len), encaps_data, encaps_len); nh_pos += encaps_len; h_pos += encaps_len; } #ifdef CONFIG_MAC80211_MESH if (meshhdrlen > 0) { memcpy(skb_push(skb, meshhdrlen), &mesh_hdr, meshhdrlen); nh_pos += meshhdrlen; h_pos += meshhdrlen; } #endif if (ieee80211_is_data_qos(fc)) { __le16 *qos_control; qos_control = (__le16 *) skb_push(skb, 2); memcpy(skb_push(skb, hdrlen - 2), &hdr, hdrlen - 2); /* * Maybe we could actually set some fields here, for now just * initialise to zero to indicate no special operation. */ *qos_control = 0; } else memcpy(skb_push(skb, hdrlen), &hdr, hdrlen); nh_pos += hdrlen; h_pos += hdrlen; dev->stats.tx_packets++; dev->stats.tx_bytes += skb->len; /* Update skb pointers to various headers since this modified frame * is going to go through Linux networking code that may potentially * need things like pointer to IP header. */ skb_set_mac_header(skb, 0); skb_set_network_header(skb, nh_pos); skb_set_transport_header(skb, h_pos); info = IEEE80211_SKB_CB(skb); memset(info, 0, sizeof(*info)); dev->trans_start = jiffies; info->flags = info_flags; info->ack_frame_id = info_id; ieee80211_xmit(sdata, skb, band); rcu_read_unlock(); return NETDEV_TX_OK; fail_rcu: rcu_read_unlock(); fail: dev_kfree_skb(skb); return NETDEV_TX_OK; } /* * ieee80211_clear_tx_pending may not be called in a context where * it is possible that it packets could come in again. */ void ieee80211_clear_tx_pending(struct ieee80211_local *local) { struct sk_buff *skb; int i; for (i = 0; i < local->hw.queues; i++) { while ((skb = skb_dequeue(&local->pending[i])) != NULL) ieee80211_free_txskb(&local->hw, skb); } } /* * Returns false if the frame couldn't be transmitted but was queued instead, * which in this case means re-queued -- take as an indication to stop sending * more pending frames. */ static bool ieee80211_tx_pending_skb(struct ieee80211_local *local, struct sk_buff *skb) { struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); struct ieee80211_sub_if_data *sdata; struct sta_info *sta; struct ieee80211_hdr *hdr; bool result; struct ieee80211_chanctx_conf *chanctx_conf; sdata = vif_to_sdata(info->control.vif); if (info->flags & IEEE80211_TX_INTFL_NEED_TXPROCESSING) { chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (unlikely(!chanctx_conf)) { dev_kfree_skb(skb); return true; } result = ieee80211_tx(sdata, skb, true, chanctx_conf->def.chan->band); } else { struct sk_buff_head skbs; __skb_queue_head_init(&skbs); __skb_queue_tail(&skbs, skb); hdr = (struct ieee80211_hdr *)skb->data; sta = sta_info_get(sdata, hdr->addr1); result = __ieee80211_tx(local, &skbs, skb->len, sta, true); } return result; } /* * Transmit all pending packets. Called from tasklet. */ void ieee80211_tx_pending(unsigned long data) { struct ieee80211_local *local = (struct ieee80211_local *)data; unsigned long flags; int i; bool txok; rcu_read_lock(); spin_lock_irqsave(&local->queue_stop_reason_lock, flags); for (i = 0; i < local->hw.queues; i++) { /* * If queue is stopped by something other than due to pending * frames, or we have no pending frames, proceed to next queue. */ if (local->queue_stop_reasons[i] || skb_queue_empty(&local->pending[i])) continue; while (!skb_queue_empty(&local->pending[i])) { struct sk_buff *skb = __skb_dequeue(&local->pending[i]); struct ieee80211_tx_info *info = IEEE80211_SKB_CB(skb); if (WARN_ON(!info->control.vif)) { ieee80211_free_txskb(&local->hw, skb); continue; } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); txok = ieee80211_tx_pending_skb(local, skb); spin_lock_irqsave(&local->queue_stop_reason_lock, flags); if (!txok) break; } if (skb_queue_empty(&local->pending[i])) ieee80211_propagate_queue_wake(local, i); } spin_unlock_irqrestore(&local->queue_stop_reason_lock, flags); rcu_read_unlock(); } /* functions for drivers to get certain frames */ static void __ieee80211_beacon_add_tim(struct ieee80211_sub_if_data *sdata, struct ps_data *ps, struct sk_buff *skb) { u8 *pos, *tim; int aid0 = 0; int i, have_bits = 0, n1, n2; /* Generate bitmap for TIM only if there are any STAs in power save * mode. */ if (atomic_read(&ps->num_sta_ps) > 0) /* in the hope that this is faster than * checking byte-for-byte */ have_bits = !bitmap_empty((unsigned long *)ps->tim, IEEE80211_MAX_AID+1); if (ps->dtim_count == 0) ps->dtim_count = sdata->vif.bss_conf.dtim_period - 1; else ps->dtim_count--; tim = pos = (u8 *) skb_put(skb, 6); *pos++ = WLAN_EID_TIM; *pos++ = 4; *pos++ = ps->dtim_count; *pos++ = sdata->vif.bss_conf.dtim_period; if (ps->dtim_count == 0 && !skb_queue_empty(&ps->bc_buf)) aid0 = 1; ps->dtim_bc_mc = aid0 == 1; if (have_bits) { /* Find largest even number N1 so that bits numbered 1 through * (N1 x 8) - 1 in the bitmap are 0 and number N2 so that bits * (N2 + 1) x 8 through 2007 are 0. */ n1 = 0; for (i = 0; i < IEEE80211_MAX_TIM_LEN; i++) { if (ps->tim[i]) { n1 = i & 0xfe; break; } } n2 = n1; for (i = IEEE80211_MAX_TIM_LEN - 1; i >= n1; i--) { if (ps->tim[i]) { n2 = i; break; } } /* Bitmap control */ *pos++ = n1 | aid0; /* Part Virt Bitmap */ skb_put(skb, n2 - n1); memcpy(pos, ps->tim + n1, n2 - n1 + 1); tim[1] = n2 - n1 + 4; } else { *pos++ = aid0; /* Bitmap control */ *pos++ = 0; /* Part Virt Bitmap */ } } static int ieee80211_beacon_add_tim(struct ieee80211_sub_if_data *sdata, struct ps_data *ps, struct sk_buff *skb) { struct ieee80211_local *local = sdata->local; /* * Not very nice, but we want to allow the driver to call * ieee80211_beacon_get() as a response to the set_tim() * callback. That, however, is already invoked under the * sta_lock to guarantee consistent and race-free update * of the tim bitmap in mac80211 and the driver. */ if (local->tim_in_locked_section) { __ieee80211_beacon_add_tim(sdata, ps, skb); } else { spin_lock_bh(&local->tim_lock); __ieee80211_beacon_add_tim(sdata, ps, skb); spin_unlock_bh(&local->tim_lock); } return 0; } void ieee80211_csa_finish(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); ieee80211_queue_work(&sdata->local->hw, &sdata->csa_finalize_work); } EXPORT_SYMBOL(ieee80211_csa_finish); static void ieee80211_update_csa(struct ieee80211_sub_if_data *sdata, struct beacon_data *beacon) { struct probe_resp *resp; int counter_offset_beacon = sdata->csa_counter_offset_beacon; int counter_offset_presp = sdata->csa_counter_offset_presp; u8 *beacon_data; size_t beacon_data_len; switch (sdata->vif.type) { case NL80211_IFTYPE_AP: beacon_data = beacon->tail; beacon_data_len = beacon->tail_len; break; case NL80211_IFTYPE_ADHOC: beacon_data = beacon->head; beacon_data_len = beacon->head_len; break; case NL80211_IFTYPE_MESH_POINT: beacon_data = beacon->head; beacon_data_len = beacon->head_len; break; default: return; } if (WARN_ON(counter_offset_beacon >= beacon_data_len)) return; /* warn if the driver did not check for/react to csa completeness */ if (WARN_ON(beacon_data[counter_offset_beacon] == 0)) return; beacon_data[counter_offset_beacon]--; if (sdata->vif.type == NL80211_IFTYPE_AP && counter_offset_presp) { rcu_read_lock(); resp = rcu_dereference(sdata->u.ap.probe_resp); /* if nl80211 accepted the offset, this should not happen. */ if (WARN_ON(!resp)) { rcu_read_unlock(); return; } resp->data[counter_offset_presp]--; rcu_read_unlock(); } } bool ieee80211_csa_is_complete(struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); struct beacon_data *beacon = NULL; u8 *beacon_data; size_t beacon_data_len; int counter_beacon = sdata->csa_counter_offset_beacon; int ret = false; if (!ieee80211_sdata_running(sdata)) return false; rcu_read_lock(); if (vif->type == NL80211_IFTYPE_AP) { struct ieee80211_if_ap *ap = &sdata->u.ap; beacon = rcu_dereference(ap->beacon); if (WARN_ON(!beacon || !beacon->tail)) goto out; beacon_data = beacon->tail; beacon_data_len = beacon->tail_len; } else if (vif->type == NL80211_IFTYPE_ADHOC) { struct ieee80211_if_ibss *ifibss = &sdata->u.ibss; beacon = rcu_dereference(ifibss->presp); if (!beacon) goto out; beacon_data = beacon->head; beacon_data_len = beacon->head_len; } else if (vif->type == NL80211_IFTYPE_MESH_POINT) { struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh; beacon = rcu_dereference(ifmsh->beacon); if (!beacon) goto out; beacon_data = beacon->head; beacon_data_len = beacon->head_len; } else { WARN_ON(1); goto out; } if (WARN_ON(counter_beacon > beacon_data_len)) goto out; if (beacon_data[counter_beacon] == 0) ret = true; out: rcu_read_unlock(); return ret; } EXPORT_SYMBOL(ieee80211_csa_is_complete); struct sk_buff *ieee80211_beacon_get_tim(struct ieee80211_hw *hw, struct ieee80211_vif *vif, u16 *tim_offset, u16 *tim_length) { struct ieee80211_local *local = hw_to_local(hw); struct sk_buff *skb = NULL; struct ieee80211_tx_info *info; struct ieee80211_sub_if_data *sdata = NULL; enum ieee80211_band band; struct ieee80211_tx_rate_control txrc; struct ieee80211_chanctx_conf *chanctx_conf; rcu_read_lock(); sdata = vif_to_sdata(vif); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!ieee80211_sdata_running(sdata) || !chanctx_conf) goto out; if (tim_offset) *tim_offset = 0; if (tim_length) *tim_length = 0; if (sdata->vif.type == NL80211_IFTYPE_AP) { struct ieee80211_if_ap *ap = &sdata->u.ap; struct beacon_data *beacon = rcu_dereference(ap->beacon); if (beacon) { if (sdata->vif.csa_active) ieee80211_update_csa(sdata, beacon); /* * headroom, head length, * tail length and maximum TIM length */ skb = dev_alloc_skb(local->tx_headroom + beacon->head_len + beacon->tail_len + 256 + local->hw.extra_beacon_tailroom); if (!skb) goto out; skb_reserve(skb, local->tx_headroom); memcpy(skb_put(skb, beacon->head_len), beacon->head, beacon->head_len); ieee80211_beacon_add_tim(sdata, &ap->ps, skb); if (tim_offset) *tim_offset = beacon->head_len; if (tim_length) *tim_length = skb->len - beacon->head_len; if (beacon->tail) memcpy(skb_put(skb, beacon->tail_len), beacon->tail, beacon->tail_len); } else goto out; } else if (sdata->vif.type == NL80211_IFTYPE_ADHOC) { struct ieee80211_if_ibss *ifibss = &sdata->u.ibss; struct ieee80211_hdr *hdr; struct beacon_data *presp = rcu_dereference(ifibss->presp); if (!presp) goto out; if (sdata->vif.csa_active) ieee80211_update_csa(sdata, presp); skb = dev_alloc_skb(local->tx_headroom + presp->head_len + local->hw.extra_beacon_tailroom); if (!skb) goto out; skb_reserve(skb, local->tx_headroom); memcpy(skb_put(skb, presp->head_len), presp->head, presp->head_len); hdr = (struct ieee80211_hdr *) skb->data; hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_BEACON); } else if (ieee80211_vif_is_mesh(&sdata->vif)) { struct ieee80211_if_mesh *ifmsh = &sdata->u.mesh; struct beacon_data *bcn = rcu_dereference(ifmsh->beacon); if (!bcn) goto out; if (sdata->vif.csa_active) ieee80211_update_csa(sdata, bcn); if (ifmsh->sync_ops) ifmsh->sync_ops->adjust_tbtt(sdata, bcn); skb = dev_alloc_skb(local->tx_headroom + bcn->head_len + 256 + /* TIM IE */ bcn->tail_len + local->hw.extra_beacon_tailroom); if (!skb) goto out; skb_reserve(skb, local->tx_headroom); memcpy(skb_put(skb, bcn->head_len), bcn->head, bcn->head_len); ieee80211_beacon_add_tim(sdata, &ifmsh->ps, skb); memcpy(skb_put(skb, bcn->tail_len), bcn->tail, bcn->tail_len); } else { WARN_ON(1); goto out; } band = chanctx_conf->def.chan->band; info = IEEE80211_SKB_CB(skb); info->flags |= IEEE80211_TX_INTFL_DONT_ENCRYPT; info->flags |= IEEE80211_TX_CTL_NO_ACK; info->band = band; memset(&txrc, 0, sizeof(txrc)); txrc.hw = hw; txrc.sband = local->hw.wiphy->bands[band]; txrc.bss_conf = &sdata->vif.bss_conf; txrc.skb = skb; txrc.reported_rate.idx = -1; txrc.rate_idx_mask = sdata->rc_rateidx_mask[band]; if (txrc.rate_idx_mask == (1 << txrc.sband->n_bitrates) - 1) txrc.max_rate_idx = -1; else txrc.max_rate_idx = fls(txrc.rate_idx_mask) - 1; txrc.bss = true; rate_control_get_rate(sdata, NULL, &txrc); info->control.vif = vif; info->flags |= IEEE80211_TX_CTL_CLEAR_PS_FILT | IEEE80211_TX_CTL_ASSIGN_SEQ | IEEE80211_TX_CTL_FIRST_FRAGMENT; out: rcu_read_unlock(); return skb; } EXPORT_SYMBOL(ieee80211_beacon_get_tim); struct sk_buff *ieee80211_proberesp_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_if_ap *ap = NULL; struct sk_buff *skb = NULL; struct probe_resp *presp = NULL; struct ieee80211_hdr *hdr; struct ieee80211_sub_if_data *sdata = vif_to_sdata(vif); if (sdata->vif.type != NL80211_IFTYPE_AP) return NULL; rcu_read_lock(); ap = &sdata->u.ap; presp = rcu_dereference(ap->probe_resp); if (!presp) goto out; skb = dev_alloc_skb(presp->len); if (!skb) goto out; memcpy(skb_put(skb, presp->len), presp->data, presp->len); hdr = (struct ieee80211_hdr *) skb->data; memset(hdr->addr1, 0, sizeof(hdr->addr1)); out: rcu_read_unlock(); return skb; } EXPORT_SYMBOL(ieee80211_proberesp_get); struct sk_buff *ieee80211_pspoll_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_sub_if_data *sdata; struct ieee80211_if_managed *ifmgd; struct ieee80211_pspoll *pspoll; struct ieee80211_local *local; struct sk_buff *skb; if (WARN_ON(vif->type != NL80211_IFTYPE_STATION)) return NULL; sdata = vif_to_sdata(vif); ifmgd = &sdata->u.mgd; local = sdata->local; skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*pspoll)); if (!skb) return NULL; skb_reserve(skb, local->hw.extra_tx_headroom); pspoll = (struct ieee80211_pspoll *) skb_put(skb, sizeof(*pspoll)); memset(pspoll, 0, sizeof(*pspoll)); pspoll->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_PSPOLL); pspoll->aid = cpu_to_le16(ifmgd->aid); /* aid in PS-Poll has its two MSBs each set to 1 */ pspoll->aid |= cpu_to_le16(1 << 15 | 1 << 14); memcpy(pspoll->bssid, ifmgd->bssid, ETH_ALEN); memcpy(pspoll->ta, vif->addr, ETH_ALEN); return skb; } EXPORT_SYMBOL(ieee80211_pspoll_get); struct sk_buff *ieee80211_nullfunc_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_hdr_3addr *nullfunc; struct ieee80211_sub_if_data *sdata; struct ieee80211_if_managed *ifmgd; struct ieee80211_local *local; struct sk_buff *skb; if (WARN_ON(vif->type != NL80211_IFTYPE_STATION)) return NULL; sdata = vif_to_sdata(vif); ifmgd = &sdata->u.mgd; local = sdata->local; skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*nullfunc)); if (!skb) return NULL; skb_reserve(skb, local->hw.extra_tx_headroom); nullfunc = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*nullfunc)); memset(nullfunc, 0, sizeof(*nullfunc)); nullfunc->frame_control = cpu_to_le16(IEEE80211_FTYPE_DATA | IEEE80211_STYPE_NULLFUNC | IEEE80211_FCTL_TODS); memcpy(nullfunc->addr1, ifmgd->bssid, ETH_ALEN); memcpy(nullfunc->addr2, vif->addr, ETH_ALEN); memcpy(nullfunc->addr3, ifmgd->bssid, ETH_ALEN); return skb; } EXPORT_SYMBOL(ieee80211_nullfunc_get); struct sk_buff *ieee80211_probereq_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const u8 *ssid, size_t ssid_len, size_t tailroom) { struct ieee80211_sub_if_data *sdata; struct ieee80211_local *local; struct ieee80211_hdr_3addr *hdr; struct sk_buff *skb; size_t ie_ssid_len; u8 *pos; sdata = vif_to_sdata(vif); local = sdata->local; ie_ssid_len = 2 + ssid_len; skb = dev_alloc_skb(local->hw.extra_tx_headroom + sizeof(*hdr) + ie_ssid_len + tailroom); if (!skb) return NULL; skb_reserve(skb, local->hw.extra_tx_headroom); hdr = (struct ieee80211_hdr_3addr *) skb_put(skb, sizeof(*hdr)); memset(hdr, 0, sizeof(*hdr)); hdr->frame_control = cpu_to_le16(IEEE80211_FTYPE_MGMT | IEEE80211_STYPE_PROBE_REQ); eth_broadcast_addr(hdr->addr1); memcpy(hdr->addr2, vif->addr, ETH_ALEN); eth_broadcast_addr(hdr->addr3); pos = skb_put(skb, ie_ssid_len); *pos++ = WLAN_EID_SSID; *pos++ = ssid_len; if (ssid_len) memcpy(pos, ssid, ssid_len); pos += ssid_len; return skb; } EXPORT_SYMBOL(ieee80211_probereq_get); void ieee80211_rts_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const void *frame, size_t frame_len, const struct ieee80211_tx_info *frame_txctl, struct ieee80211_rts *rts) { const struct ieee80211_hdr *hdr = frame; rts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_RTS); rts->duration = ieee80211_rts_duration(hw, vif, frame_len, frame_txctl); memcpy(rts->ra, hdr->addr1, sizeof(rts->ra)); memcpy(rts->ta, hdr->addr2, sizeof(rts->ta)); } EXPORT_SYMBOL(ieee80211_rts_get); void ieee80211_ctstoself_get(struct ieee80211_hw *hw, struct ieee80211_vif *vif, const void *frame, size_t frame_len, const struct ieee80211_tx_info *frame_txctl, struct ieee80211_cts *cts) { const struct ieee80211_hdr *hdr = frame; cts->frame_control = cpu_to_le16(IEEE80211_FTYPE_CTL | IEEE80211_STYPE_CTS); cts->duration = ieee80211_ctstoself_duration(hw, vif, frame_len, frame_txctl); memcpy(cts->ra, hdr->addr1, sizeof(cts->ra)); } EXPORT_SYMBOL(ieee80211_ctstoself_get); struct sk_buff * ieee80211_get_buffered_bc(struct ieee80211_hw *hw, struct ieee80211_vif *vif) { struct ieee80211_local *local = hw_to_local(hw); struct sk_buff *skb = NULL; struct ieee80211_tx_data tx; struct ieee80211_sub_if_data *sdata; struct ps_data *ps; struct ieee80211_tx_info *info; struct ieee80211_chanctx_conf *chanctx_conf; sdata = vif_to_sdata(vif); rcu_read_lock(); chanctx_conf = rcu_dereference(sdata->vif.chanctx_conf); if (!chanctx_conf) goto out; if (sdata->vif.type == NL80211_IFTYPE_AP) { struct beacon_data *beacon = rcu_dereference(sdata->u.ap.beacon); if (!beacon || !beacon->head) goto out; ps = &sdata->u.ap.ps; } else if (ieee80211_vif_is_mesh(&sdata->vif)) { ps = &sdata->u.mesh.ps; } else { goto out; } if (ps->dtim_count != 0 || !ps->dtim_bc_mc) goto out; /* send buffered bc/mc only after DTIM beacon */ while (1) { skb = skb_dequeue(&ps->bc_buf); if (!skb) goto out; local->total_ps_buffered--; if (!skb_queue_empty(&ps->bc_buf) && skb->len >= 2) { struct ieee80211_hdr *hdr = (struct ieee80211_hdr *) skb->data; /* more buffered multicast/broadcast frames ==> set * MoreData flag in IEEE 802.11 header to inform PS * STAs */ hdr->frame_control |= cpu_to_le16(IEEE80211_FCTL_MOREDATA); } if (sdata->vif.type == NL80211_IFTYPE_AP_VLAN) sdata = IEEE80211_DEV_TO_SUB_IF(skb->dev); if (!ieee80211_tx_prepare(sdata, &tx, skb)) break; dev_kfree_skb_any(skb); } info = IEEE80211_SKB_CB(skb); tx.flags |= IEEE80211_TX_PS_BUFFERED; info->band = chanctx_conf->def.chan->band; if (invoke_tx_handlers(&tx)) skb = NULL; out: rcu_read_unlock(); return skb; } EXPORT_SYMBOL(ieee80211_get_buffered_bc); void __ieee80211_tx_skb_tid_band(struct ieee80211_sub_if_data *sdata, struct sk_buff *skb, int tid, enum ieee80211_band band) { int ac = ieee802_1d_to_ac[tid & 7]; skb_set_mac_header(skb, 0); skb_set_network_header(skb, 0); skb_set_transport_header(skb, 0); skb_set_queue_mapping(skb, ac); skb->priority = tid; skb->dev = sdata->dev; /* * The other path calling ieee80211_xmit is from the tasklet, * and while we can handle concurrent transmissions locking * requirements are that we do not come into tx with bhs on. */ local_bh_disable(); ieee80211_xmit(sdata, skb, band); local_bh_enable(); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2330_0
crossvul-cpp_data_bad_4074_2
/* * This file is part of ubridge, a program to bridge network interfaces * to UDP tunnels. * * Copyright (C) 2015 GNS3 Technologies Inc. * * ubridge is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ubridge is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <stdio.h> #include <stdlib.h> #include "parse.h" #include "nio_udp.h" #include "nio_unix.h" #include "nio_ethernet.h" #include "nio_tap.h" #include "pcap_capture.h" #include "pcap_filter.h" #ifdef LINUX_RAW #include "nio_linux_raw.h" #endif #ifdef __APPLE__ #include "nio_fusion_vmnet.h" #endif static nio_t *create_udp_tunnel(const char *params) { nio_t *nio; char *local_port; char *remote_host; char *remote_port; printf("Creating UDP tunnel %s\n", params); local_port = strtok((char *)params, ":"); remote_host = strtok(NULL, ":"); remote_port = strtok(NULL, ":"); if (local_port == NULL || remote_host == NULL || remote_port == NULL) { fprintf(stderr, "invalid UDP tunnel syntax\n"); return NULL; } nio = create_nio_udp(atoi(local_port), remote_host, atoi(remote_port)); if (!nio) fprintf(stderr, "unable to create UDP NIO\n"); return nio; } static nio_t *create_unix_socket(const char *params) { nio_t *nio; char *local; char *remote; printf("Creating UNIX domain socket %s\n", params); local = strtok((char *)params, ":"); remote = strtok(NULL, ":"); if (local == NULL || remote == NULL) { fprintf(stderr, "invalid UNIX domain socket syntax\n"); return NULL; } nio = create_nio_unix(local, remote); if (!nio) fprintf(stderr, "unable to create UNIX NIO\n"); return nio; } static nio_t *open_ethernet_device(const char *dev_name) { nio_t *nio; printf("Opening Ethernet device %s\n", dev_name); nio = create_nio_ethernet((char *)dev_name); if (!nio) fprintf(stderr, "unable to open Ethernet device\n"); return nio; } static nio_t *open_tap_device(const char *dev_name) { nio_t *nio; printf("Opening TAP device %s\n", dev_name); nio = create_nio_tap((char *)dev_name); if (!nio) fprintf(stderr, "unable to open TAP device\n"); return nio; } #ifdef LINUX_RAW static nio_t *open_linux_raw(const char *dev_name) { nio_t *nio; printf("Opening Linux RAW device %s\n", dev_name); nio = create_nio_linux_raw((char *)dev_name); if (!nio) fprintf(stderr, "unable to open RAW device\n"); return nio; } #endif #ifdef __APPLE__ static nio_t *open_fusion_vmnet(const char *vmnet_name) { nio_t *nio; printf("Opening Fusion VMnet %s\n", vmnet_name); nio = create_nio_fusion_vmnet((char *)vmnet_name); if (!nio) fprintf(stderr, "unable to open Fusion VMnet interface\n"); return nio; } #endif static int getstr(dictionary *ubridge_config, const char *section, const char *entry, const char **value) { char key[MAX_KEY_SIZE]; snprintf(key, MAX_KEY_SIZE, "%s:%s", section, entry); *value = iniparser_getstring(ubridge_config, key, NULL); if (*value) return TRUE; return FALSE; } static bridge_t *add_bridge(bridge_t **head) { bridge_t *bridge; if ((bridge = malloc(sizeof(*bridge))) != NULL) { memset(bridge, 0, sizeof(*bridge)); bridge->next = *head; *head = bridge; } return bridge; } static void parse_capture(dictionary *ubridge_config, const char *bridge_name, bridge_t *bridge) { const char *pcap_file = NULL; const char *pcap_linktype = "EN10MB"; getstr(ubridge_config, bridge_name, "pcap_protocol", &pcap_linktype); if (getstr(ubridge_config, bridge_name, "pcap_file", &pcap_file)) { printf("Starting packet capture to %s with protocol %s\n", pcap_file, pcap_linktype); bridge->capture = create_pcap_capture(pcap_file, pcap_linktype); } } static void parse_filter(dictionary *ubridge_config, const char *bridge_name, bridge_t *bridge) { const char *pcap_filter = NULL; if (getstr(ubridge_config, bridge_name, "pcap_filter", &pcap_filter)) { printf("Applying PCAP filter '%s'\n", pcap_filter); if (bridge->source_nio->type == NIO_TYPE_ETHERNET) { if (set_pcap_filter(bridge->source_nio->dptr, pcap_filter) < 0) fprintf(stderr, "unable to apply filter to source NIO\n"); } else if (bridge->destination_nio->type == NIO_TYPE_ETHERNET) { if (set_pcap_filter(bridge->destination_nio->dptr, pcap_filter) < 0) fprintf(stderr, "unable to apply filter to destination NIO\n"); } } } int parse_config(char *filename, bridge_t **bridges) { dictionary *ubridge_config = NULL; const char *value; const char *bridge_name; int i, nsec; if ((ubridge_config = iniparser_load(filename)) == NULL) { return FALSE; } nsec = iniparser_getnsec(ubridge_config); for (i = 0; i < nsec; i++) { bridge_t *bridge; nio_t *source_nio = NULL; nio_t *destination_nio = NULL; bridge_name = iniparser_getsecname(ubridge_config, i); printf("Parsing %s\n", bridge_name); if (getstr(ubridge_config, bridge_name, "source_udp", &value)) source_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "source_unix", &value)) source_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "source_ethernet", &value)) source_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "source_tap", &value)) source_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "source_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "source_fusion_vmnet", &value)) source_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "source NIO not found\n"); if (getstr(ubridge_config, bridge_name, "destination_udp", &value)) destination_nio = create_udp_tunnel(value); else if (getstr(ubridge_config, bridge_name, "destination_unix", &value)) destination_nio = create_unix_socket(value); else if (getstr(ubridge_config, bridge_name, "destination_ethernet", &value)) destination_nio = open_ethernet_device(value); else if (getstr(ubridge_config, bridge_name, "destination_tap", &value)) destination_nio = open_tap_device(value); #ifdef LINUX_RAW else if (getstr(ubridge_config, bridge_name, "destination_linux_raw", &value)) source_nio = open_linux_raw(value); #endif #ifdef __APPLE__ else if (getstr(ubridge_config, bridge_name, "destination_fusion_vmnet", &value)) destination_nio = open_fusion_vmnet(value); #endif else fprintf(stderr, "destination NIO not found\n"); if (source_nio && destination_nio) { bridge = add_bridge(bridges); bridge->source_nio = source_nio; bridge->destination_nio = destination_nio; if (!(bridge->name = strdup(bridge_name))) { fprintf(stderr, "bridge creation: insufficient memory\n"); return FALSE; } parse_capture(ubridge_config, bridge_name, bridge); parse_filter(ubridge_config, bridge_name, bridge); } else if (source_nio != NULL) free_nio(source_nio); else if (destination_nio != NULL) free_nio(destination_nio); } iniparser_freedict(ubridge_config); return TRUE; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_4074_2
crossvul-cpp_data_good_5073_0
/* * linux/fs/isofs/rock.c * * (C) 1992, 1993 Eric Youngdale * * Rock Ridge Extensions to iso9660 */ #include <linux/slab.h> #include <linux/pagemap.h> #include "isofs.h" #include "rock.h" /* * These functions are designed to read the system areas of a directory record * and extract relevant information. There are different functions provided * depending upon what information we need at the time. One function fills * out an inode structure, a second one extracts a filename, a third one * returns a symbolic link name, and a fourth one returns the extent number * for the file. */ #define SIG(A,B) ((A) | ((B) << 8)) /* isonum_721() */ struct rock_state { void *buffer; unsigned char *chr; int len; int cont_size; int cont_extent; int cont_offset; int cont_loops; struct inode *inode; }; /* * This is a way of ensuring that we have something in the system * use fields that is compatible with Rock Ridge. Return zero on success. */ static int check_sp(struct rock_ridge *rr, struct inode *inode) { if (rr->u.SP.magic[0] != 0xbe) return -1; if (rr->u.SP.magic[1] != 0xef) return -1; ISOFS_SB(inode->i_sb)->s_rock_offset = rr->u.SP.skip; return 0; } static void setup_rock_ridge(struct iso_directory_record *de, struct inode *inode, struct rock_state *rs) { rs->len = sizeof(struct iso_directory_record) + de->name_len[0]; if (rs->len & 1) (rs->len)++; rs->chr = (unsigned char *)de + rs->len; rs->len = *((unsigned char *)de) - rs->len; if (rs->len < 0) rs->len = 0; if (ISOFS_SB(inode->i_sb)->s_rock_offset != -1) { rs->len -= ISOFS_SB(inode->i_sb)->s_rock_offset; rs->chr += ISOFS_SB(inode->i_sb)->s_rock_offset; if (rs->len < 0) rs->len = 0; } } static void init_rock_state(struct rock_state *rs, struct inode *inode) { memset(rs, 0, sizeof(*rs)); rs->inode = inode; } /* Maximum number of Rock Ridge continuation entries */ #define RR_MAX_CE_ENTRIES 32 /* * Returns 0 if the caller should continue scanning, 1 if the scan must end * and -ve on error. */ static int rock_continue(struct rock_state *rs) { int ret = 1; int blocksize = 1 << rs->inode->i_blkbits; const int min_de_size = offsetof(struct rock_ridge, u); kfree(rs->buffer); rs->buffer = NULL; if ((unsigned)rs->cont_offset > blocksize - min_de_size || (unsigned)rs->cont_size > blocksize || (unsigned)(rs->cont_offset + rs->cont_size) > blocksize) { printk(KERN_NOTICE "rock: corrupted directory entry. " "extent=%d, offset=%d, size=%d\n", rs->cont_extent, rs->cont_offset, rs->cont_size); ret = -EIO; goto out; } if (rs->cont_extent) { struct buffer_head *bh; rs->buffer = kmalloc(rs->cont_size, GFP_KERNEL); if (!rs->buffer) { ret = -ENOMEM; goto out; } ret = -EIO; if (++rs->cont_loops >= RR_MAX_CE_ENTRIES) goto out; bh = sb_bread(rs->inode->i_sb, rs->cont_extent); if (bh) { memcpy(rs->buffer, bh->b_data + rs->cont_offset, rs->cont_size); put_bh(bh); rs->chr = rs->buffer; rs->len = rs->cont_size; rs->cont_extent = 0; rs->cont_size = 0; rs->cont_offset = 0; return 0; } printk("Unable to read rock-ridge attributes\n"); } out: kfree(rs->buffer); rs->buffer = NULL; return ret; } /* * We think there's a record of type `sig' at rs->chr. Parse the signature * and make sure that there's really room for a record of that type. */ static int rock_check_overflow(struct rock_state *rs, int sig) { int len; switch (sig) { case SIG('S', 'P'): len = sizeof(struct SU_SP_s); break; case SIG('C', 'E'): len = sizeof(struct SU_CE_s); break; case SIG('E', 'R'): len = sizeof(struct SU_ER_s); break; case SIG('R', 'R'): len = sizeof(struct RR_RR_s); break; case SIG('P', 'X'): len = sizeof(struct RR_PX_s); break; case SIG('P', 'N'): len = sizeof(struct RR_PN_s); break; case SIG('S', 'L'): len = sizeof(struct RR_SL_s); break; case SIG('N', 'M'): len = sizeof(struct RR_NM_s); break; case SIG('C', 'L'): len = sizeof(struct RR_CL_s); break; case SIG('P', 'L'): len = sizeof(struct RR_PL_s); break; case SIG('T', 'F'): len = sizeof(struct RR_TF_s); break; case SIG('Z', 'F'): len = sizeof(struct RR_ZF_s); break; default: len = 0; break; } len += offsetof(struct rock_ridge, u); if (len > rs->len) { printk(KERN_NOTICE "rock: directory entry would overflow " "storage\n"); printk(KERN_NOTICE "rock: sig=0x%02x, size=%d, remaining=%d\n", sig, len, rs->len); return -EIO; } return 0; } /* * return length of name field; 0: not found, -1: to be ignored */ int get_rock_ridge_filename(struct iso_directory_record *de, char *retname, struct inode *inode) { struct rock_state rs; struct rock_ridge *rr; int sig; int retnamlen = 0; int truncate = 0; int ret = 0; char *p; int len; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; *retname = 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_NM) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('N', 'M'): if (truncate) break; if (rr->len < 5) break; /* * If the flags are 2 or 4, this indicates '.' or '..'. * We don't want to do anything with this, because it * screws up the code that calls us. We don't really * care anyways, since we can just use the non-RR * name. */ if (rr->u.NM.flags & 6) break; if (rr->u.NM.flags & ~1) { printk("Unsupported NM flag settings (%d)\n", rr->u.NM.flags); break; } len = rr->len - 5; if (retnamlen + len >= 254) { truncate = 1; break; } p = memchr(rr->u.NM.name, '\0', len); if (unlikely(p)) len = p - rr->u.NM.name; memcpy(retname + retnamlen, rr->u.NM.name, len); retnamlen += len; retname[retnamlen] = '\0'; break; case SIG('R', 'E'): kfree(rs.buffer); return -1; default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) return retnamlen; /* If 0, this file did not have a NM field */ out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } #define RR_REGARD_XA 1 #define RR_RELOC_DE 2 static int parse_rock_ridge_inode_internal(struct iso_directory_record *de, struct inode *inode, int flags) { int symlink_len = 0; int cnt, sig; unsigned int reloc_block; struct inode *reloc; struct rock_ridge *rr; int rootflag; struct rock_state rs; int ret = 0; if (!ISOFS_SB(inode->i_sb)->s_rock) return 0; init_rock_state(&rs, inode); setup_rock_ridge(de, inode, &rs); if (flags & RR_REGARD_XA) { rs.chr += 14; rs.len -= 14; if (rs.len < 0) rs.len = 0; } repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; /* * Ignore rock ridge info if rr->len is out of range, but * don't return -EIO because that would make the file * invisible. */ if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto eio; rs.chr += rr->len; rs.len -= rr->len; /* * As above, just ignore the rock ridge info if rr->len * is bogus. */ if (rs.len < 0) goto out; /* Something got screwed up here */ switch (sig) { #ifndef CONFIG_ZISOFS /* No flag for SF or ZF */ case SIG('R', 'R'): if ((rr->u.RR.flags[0] & (RR_PX | RR_TF | RR_SL | RR_CL)) == 0) goto out; break; #endif case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('C', 'E'): rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); break; case SIG('E', 'R'): /* Invalid length of ER tag id? */ if (rr->u.ER.len_id + offsetof(struct rock_ridge, u.ER.data) > rr->len) goto out; ISOFS_SB(inode->i_sb)->s_rock = 1; printk(KERN_DEBUG "ISO 9660 Extensions: "); { int p; for (p = 0; p < rr->u.ER.len_id; p++) printk("%c", rr->u.ER.data[p]); } printk("\n"); break; case SIG('P', 'X'): inode->i_mode = isonum_733(rr->u.PX.mode); set_nlink(inode, isonum_733(rr->u.PX.n_links)); i_uid_write(inode, isonum_733(rr->u.PX.uid)); i_gid_write(inode, isonum_733(rr->u.PX.gid)); break; case SIG('P', 'N'): { int high, low; high = isonum_733(rr->u.PN.dev_high); low = isonum_733(rr->u.PN.dev_low); /* * The Rock Ridge standard specifies that if * sizeof(dev_t) <= 4, then the high field is * unused, and the device number is completely * stored in the low field. Some writers may * ignore this subtlety, * and as a result we test to see if the entire * device number is * stored in the low field, and use that. */ if ((low & ~0xff) && high == 0) { inode->i_rdev = MKDEV(low >> 8, low & 0xff); } else { inode->i_rdev = MKDEV(high, low); } } break; case SIG('T', 'F'): /* * Some RRIP writers incorrectly place ctime in the * TF_CREATE field. Try to handle this correctly for * either case. */ /* Rock ridge never appears on a High Sierra disk */ cnt = 0; if (rr->u.TF.flags & TF_CREATE) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } if (rr->u.TF.flags & TF_MODIFY) { inode->i_mtime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_mtime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ACCESS) { inode->i_atime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_atime.tv_nsec = 0; } if (rr->u.TF.flags & TF_ATTRIBUTES) { inode->i_ctime.tv_sec = iso_date(rr->u.TF.times[cnt++].time, 0); inode->i_ctime.tv_nsec = 0; } break; case SIG('S', 'L'): { int slen; struct SL_component *slp; struct SL_component *oldslp; slen = rr->len - 5; slp = &rr->u.SL.link; inode->i_size = symlink_len; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: inode->i_size += slp->len; break; case 2: inode->i_size += 1; break; case 4: inode->i_size += 2; break; case 8: rootflag = 1; inode->i_size += 1; break; default: printk("Symlink component flag " "not implemented\n"); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *) (((char *)slp) + slp->len + 2); if (slen < 2) { if (((rr->u.SL. flags & 1) != 0) && ((oldslp-> flags & 1) == 0)) inode->i_size += 1; break; } /* * If this component record isn't * continued, then append a '/'. */ if (!rootflag && (oldslp->flags & 1) == 0) inode->i_size += 1; } } symlink_len = inode->i_size; break; case SIG('R', 'E'): printk(KERN_WARNING "Attempt to read inode for " "relocated directory\n"); goto out; case SIG('C', 'L'): if (flags & RR_RELOC_DE) { printk(KERN_ERR "ISOFS: Recursive directory relocation " "is not supported\n"); goto eio; } reloc_block = isonum_733(rr->u.CL.location); if (reloc_block == ISOFS_I(inode)->i_iget5_block && ISOFS_I(inode)->i_iget5_offset == 0) { printk(KERN_ERR "ISOFS: Directory relocation points to " "itself\n"); goto eio; } ISOFS_I(inode)->i_first_extent = reloc_block; reloc = isofs_iget_reloc(inode->i_sb, reloc_block, 0); if (IS_ERR(reloc)) { ret = PTR_ERR(reloc); goto out; } inode->i_mode = reloc->i_mode; set_nlink(inode, reloc->i_nlink); inode->i_uid = reloc->i_uid; inode->i_gid = reloc->i_gid; inode->i_rdev = reloc->i_rdev; inode->i_size = reloc->i_size; inode->i_blocks = reloc->i_blocks; inode->i_atime = reloc->i_atime; inode->i_ctime = reloc->i_ctime; inode->i_mtime = reloc->i_mtime; iput(reloc); break; #ifdef CONFIG_ZISOFS case SIG('Z', 'F'): { int algo; if (ISOFS_SB(inode->i_sb)->s_nocompress) break; algo = isonum_721(rr->u.ZF.algorithm); if (algo == SIG('p', 'z')) { int block_shift = isonum_711(&rr->u.ZF.parms[1]); if (block_shift > 17) { printk(KERN_WARNING "isofs: " "Can't handle ZF block " "size of 2^%d\n", block_shift); } else { /* * Note: we don't change * i_blocks here */ ISOFS_I(inode)->i_file_format = isofs_file_compressed; /* * Parameters to compression * algorithm (header size, * block size) */ ISOFS_I(inode)->i_format_parm[0] = isonum_711(&rr->u.ZF.parms[0]); ISOFS_I(inode)->i_format_parm[1] = isonum_711(&rr->u.ZF.parms[1]); inode->i_size = isonum_733(rr->u.ZF. real_size); } } else { printk(KERN_WARNING "isofs: Unknown ZF compression " "algorithm: %c%c\n", rr->u.ZF.algorithm[0], rr->u.ZF.algorithm[1]); } break; } #endif default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret == 1) ret = 0; out: kfree(rs.buffer); return ret; eio: ret = -EIO; goto out; } static char *get_symlink_chunk(char *rpnt, struct rock_ridge *rr, char *plimit) { int slen; int rootflag; struct SL_component *oldslp; struct SL_component *slp; slen = rr->len - 5; slp = &rr->u.SL.link; while (slen > 1) { rootflag = 0; switch (slp->flags & ~1) { case 0: if (slp->len > plimit - rpnt) return NULL; memcpy(rpnt, slp->text, slp->len); rpnt += slp->len; break; case 2: if (rpnt >= plimit) return NULL; *rpnt++ = '.'; break; case 4: if (2 > plimit - rpnt) return NULL; *rpnt++ = '.'; *rpnt++ = '.'; break; case 8: if (rpnt >= plimit) return NULL; rootflag = 1; *rpnt++ = '/'; break; default: printk("Symlink component flag not implemented (%d)\n", slp->flags); } slen -= slp->len + 2; oldslp = slp; slp = (struct SL_component *)((char *)slp + slp->len + 2); if (slen < 2) { /* * If there is another SL record, and this component * record isn't continued, then add a slash. */ if ((!rootflag) && (rr->u.SL.flags & 1) && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } break; } /* * If this component record isn't continued, then append a '/'. */ if (!rootflag && !(oldslp->flags & 1)) { if (rpnt >= plimit) return NULL; *rpnt++ = '/'; } } return rpnt; } int parse_rock_ridge_inode(struct iso_directory_record *de, struct inode *inode, int relocated) { int flags = relocated ? RR_RELOC_DE : 0; int result = parse_rock_ridge_inode_internal(de, inode, flags); /* * if rockridge flag was reset and we didn't look for attributes * behind eventual XA attributes, have a look there */ if ((ISOFS_SB(inode->i_sb)->s_rock_offset == -1) && (ISOFS_SB(inode->i_sb)->s_rock == 2)) { result = parse_rock_ridge_inode_internal(de, inode, flags | RR_REGARD_XA); } return result; } /* * readpage() for symlinks: reads symlink contents into the page and either * makes it uptodate and returns 0 or returns error (-EIO) */ static int rock_ridge_symlink_readpage(struct file *file, struct page *page) { struct inode *inode = page->mapping->host; struct iso_inode_info *ei = ISOFS_I(inode); struct isofs_sb_info *sbi = ISOFS_SB(inode->i_sb); char *link = page_address(page); unsigned long bufsize = ISOFS_BUFFER_SIZE(inode); struct buffer_head *bh; char *rpnt = link; unsigned char *pnt; struct iso_directory_record *raw_de; unsigned long block, offset; int sig; struct rock_ridge *rr; struct rock_state rs; int ret; if (!sbi->s_rock) goto error; init_rock_state(&rs, inode); block = ei->i_iget5_block; bh = sb_bread(inode->i_sb, block); if (!bh) goto out_noread; offset = ei->i_iget5_offset; pnt = (unsigned char *)bh->b_data + offset; raw_de = (struct iso_directory_record *)pnt; /* * If we go past the end of the buffer, there is some sort of error. */ if (offset + *pnt > bufsize) goto out_bad_span; /* * Now test for possible Rock Ridge extensions which will override * some of these numbers in the inode structure. */ setup_rock_ridge(raw_de, inode, &rs); repeat: while (rs.len > 2) { /* There may be one byte for padding somewhere */ rr = (struct rock_ridge *)rs.chr; if (rr->len < 3) goto out; /* Something got screwed up here */ sig = isonum_721(rs.chr); if (rock_check_overflow(&rs, sig)) goto out; rs.chr += rr->len; rs.len -= rr->len; if (rs.len < 0) goto out; /* corrupted isofs */ switch (sig) { case SIG('R', 'R'): if ((rr->u.RR.flags[0] & RR_SL) == 0) goto out; break; case SIG('S', 'P'): if (check_sp(rr, inode)) goto out; break; case SIG('S', 'L'): rpnt = get_symlink_chunk(rpnt, rr, link + (PAGE_SIZE - 1)); if (rpnt == NULL) goto out; break; case SIG('C', 'E'): /* This tells is if there is a continuation record */ rs.cont_extent = isonum_733(rr->u.CE.extent); rs.cont_offset = isonum_733(rr->u.CE.offset); rs.cont_size = isonum_733(rr->u.CE.size); default: break; } } ret = rock_continue(&rs); if (ret == 0) goto repeat; if (ret < 0) goto fail; if (rpnt == link) goto fail; brelse(bh); *rpnt = '\0'; SetPageUptodate(page); unlock_page(page); return 0; /* error exit from macro */ out: kfree(rs.buffer); goto fail; out_noread: printk("unable to read i-node block"); goto fail; out_bad_span: printk("symlink spans iso9660 blocks\n"); fail: brelse(bh); error: SetPageError(page); unlock_page(page); return -EIO; } const struct address_space_operations isofs_symlink_aops = { .readpage = rock_ridge_symlink_readpage };
./CrossVul/dataset_final_sorted/CWE-200/c/good_5073_0
crossvul-cpp_data_bad_3841_0
404: Not Found
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3841_0
crossvul-cpp_data_good_3836_0
/* RFCOMM implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com> Copyright (C) 2002 Marcel Holtmann <marcel@holtmann.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* * RFCOMM sockets. */ #include <linux/export.h> #include <linux/debugfs.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include <net/bluetooth/rfcomm.h> static const struct proto_ops rfcomm_sock_ops; static struct bt_sock_list rfcomm_sk_list = { .lock = __RW_LOCK_UNLOCKED(rfcomm_sk_list.lock) }; static void rfcomm_sock_close(struct sock *sk); static void rfcomm_sock_kill(struct sock *sk); /* ---- DLC callbacks ---- * * called under rfcomm_dlc_lock() */ static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb) { struct sock *sk = d->owner; if (!sk) return; atomic_add(skb->len, &sk->sk_rmem_alloc); skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_data_ready(sk, skb->len); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) rfcomm_dlc_throttle(d); } static void rfcomm_sk_state_change(struct rfcomm_dlc *d, int err) { struct sock *sk = d->owner, *parent; unsigned long flags; if (!sk) return; BT_DBG("dlc %p state %ld err %d", d, d->state, err); local_irq_save(flags); bh_lock_sock(sk); if (err) sk->sk_err = err; sk->sk_state = d->state; parent = bt_sk(sk)->parent; if (parent) { if (d->state == BT_CLOSED) { sock_set_flag(sk, SOCK_ZAPPED); bt_accept_unlink(sk); } parent->sk_data_ready(parent, 0); } else { if (d->state == BT_CONNECTED) rfcomm_session_getaddr(d->session, &bt_sk(sk)->src, NULL); sk->sk_state_change(sk); } bh_unlock_sock(sk); local_irq_restore(flags); if (parent && sock_flag(sk, SOCK_ZAPPED)) { /* We have to drop DLC lock here, otherwise * rfcomm_sock_destruct() will dead lock. */ rfcomm_dlc_unlock(d); rfcomm_sock_kill(sk); rfcomm_dlc_lock(d); } } /* ---- Socket functions ---- */ static struct sock *__rfcomm_get_sock_by_addr(u8 channel, bdaddr_t *src) { struct sock *sk = NULL; struct hlist_node *node; sk_for_each(sk, node, &rfcomm_sk_list.head) { if (rfcomm_pi(sk)->channel == channel && !bacmp(&bt_sk(sk)->src, src)) break; } return node ? sk : NULL; } /* Find socket with channel and source bdaddr. * Returns closest match. */ static struct sock *rfcomm_get_sock_by_channel(int state, u8 channel, bdaddr_t *src) { struct sock *sk = NULL, *sk1 = NULL; struct hlist_node *node; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, node, &rfcomm_sk_list.head) { if (state && sk->sk_state != state) continue; if (rfcomm_pi(sk)->channel == channel) { /* Exact match. */ if (!bacmp(&bt_sk(sk)->src, src)) break; /* Closest match */ if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY)) sk1 = sk; } } read_unlock(&rfcomm_sk_list.lock); return node ? sk : sk1; } static void rfcomm_sock_destruct(struct sock *sk) { struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; BT_DBG("sk %p dlc %p", sk, d); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); rfcomm_dlc_lock(d); rfcomm_pi(sk)->dlc = NULL; /* Detach DLC if it's owned by this socket */ if (d->owner == sk) d->owner = NULL; rfcomm_dlc_unlock(d); rfcomm_dlc_put(d); } static void rfcomm_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted dlcs */ while ((sk = bt_accept_dequeue(parent, NULL))) { rfcomm_sock_close(sk); rfcomm_sock_kill(sk); } parent->sk_state = BT_CLOSED; sock_set_flag(parent, SOCK_ZAPPED); } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void rfcomm_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %d refcnt %d", sk, sk->sk_state, atomic_read(&sk->sk_refcnt)); /* Kill poor orphan */ bt_sock_unlink(&rfcomm_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static void __rfcomm_sock_close(struct sock *sk) { struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket); switch (sk->sk_state) { case BT_LISTEN: rfcomm_sock_cleanup_listen(sk); break; case BT_CONNECT: case BT_CONNECT2: case BT_CONFIG: case BT_CONNECTED: rfcomm_dlc_close(d, 0); default: sock_set_flag(sk, SOCK_ZAPPED); break; } } /* Close socket. * Must be called on unlocked socket. */ static void rfcomm_sock_close(struct sock *sk) { lock_sock(sk); __rfcomm_sock_close(sk); release_sock(sk); } static void rfcomm_sock_init(struct sock *sk, struct sock *parent) { struct rfcomm_pinfo *pi = rfcomm_pi(sk); BT_DBG("sk %p", sk); if (parent) { sk->sk_type = parent->sk_type; pi->dlc->defer_setup = test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags); pi->sec_level = rfcomm_pi(parent)->sec_level; pi->role_switch = rfcomm_pi(parent)->role_switch; security_sk_clone(parent, sk); } else { pi->dlc->defer_setup = 0; pi->sec_level = BT_SECURITY_LOW; pi->role_switch = 0; } pi->dlc->sec_level = pi->sec_level; pi->dlc->role_switch = pi->role_switch; } static struct proto rfcomm_proto = { .name = "RFCOMM", .owner = THIS_MODULE, .obj_size = sizeof(struct rfcomm_pinfo) }; static struct sock *rfcomm_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio) { struct rfcomm_dlc *d; struct sock *sk; sk = sk_alloc(net, PF_BLUETOOTH, prio, &rfcomm_proto); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); d = rfcomm_dlc_alloc(prio); if (!d) { sk_free(sk); return NULL; } d->data_ready = rfcomm_sk_data_ready; d->state_change = rfcomm_sk_state_change; rfcomm_pi(sk)->dlc = d; d->owner = sk; sk->sk_destruct = rfcomm_sock_destruct; sk->sk_sndtimeo = RFCOMM_CONN_TIMEOUT; sk->sk_sndbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10; sk->sk_rcvbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; bt_sock_link(&rfcomm_sk_list, sk); BT_DBG("sk %p", sk); return sk; } static int rfcomm_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_STREAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sock->ops = &rfcomm_sock_ops; sk = rfcomm_sock_alloc(net, sock, protocol, GFP_ATOMIC); if (!sk) return -ENOMEM; rfcomm_sock_init(sk, NULL); return 0; } static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %s", sk, batostr(&sa->rc_bdaddr)); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } write_lock(&rfcomm_sk_list.lock); if (sa->rc_channel && __rfcomm_get_sock_by_addr(sa->rc_channel, &sa->rc_bdaddr)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&bt_sk(sk)->src, &sa->rc_bdaddr); rfcomm_pi(sk)->channel = sa->rc_channel; sk->sk_state = BT_BOUND; } write_unlock(&rfcomm_sk_list.lock); done: release_sock(sk); return err; } static int rfcomm_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; int err = 0; BT_DBG("sk %p", sk); if (alen < sizeof(struct sockaddr_rc) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } sk->sk_state = BT_CONNECT; bacpy(&bt_sk(sk)->dst, &sa->rc_bdaddr); rfcomm_pi(sk)->channel = sa->rc_channel; d->sec_level = rfcomm_pi(sk)->sec_level; d->role_switch = rfcomm_pi(sk)->role_switch; err = rfcomm_dlc_open(d, &bt_sk(sk)->src, &sa->rc_bdaddr, sa->rc_channel); if (!err) err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } static int rfcomm_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } if (!rfcomm_pi(sk)->channel) { bdaddr_t *src = &bt_sk(sk)->src; u8 channel; err = -EINVAL; write_lock(&rfcomm_sk_list.lock); for (channel = 1; channel < 31; channel++) if (!__rfcomm_get_sock_by_addr(channel, src)) { rfcomm_pi(sk)->channel = channel; err = 0; break; } write_unlock(&rfcomm_sk_list.lock); if (err < 0) goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; } static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock(sk); if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } nsk = bt_accept_dequeue(sk, newsock); if (nsk) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", nsk); done: release_sock(sk); return err; } static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; BT_DBG("sock %p, sk %p", sock, sk); sa->rc_family = AF_BLUETOOTH; sa->rc_channel = rfcomm_pi(sk)->channel; if (peer) bacpy(&sa->rc_bdaddr, &bt_sk(sk)->dst); else bacpy(&sa->rc_bdaddr, &bt_sk(sk)->src); *len = sizeof(struct sockaddr_rc); return 0; } static int rfcomm_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; struct sk_buff *skb; int sent = 0; if (test_bit(RFCOMM_DEFER_SETUP, &d->flags)) return -ENOTCONN; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; if (sk->sk_shutdown & SEND_SHUTDOWN) return -EPIPE; BT_DBG("sock %p, sk %p", sock, sk); lock_sock(sk); while (len) { size_t size = min_t(size_t, len, d->mtu); int err; skb = sock_alloc_send_skb(sk, size + RFCOMM_SKB_RESERVE, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) { if (sent == 0) sent = err; break; } skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE); err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size); if (err) { kfree_skb(skb); if (sent == 0) sent = err; break; } skb->priority = sk->sk_priority; err = rfcomm_dlc_send(d, skb); if (err < 0) { kfree_skb(skb); if (sent == 0) sent = err; break; } sent += size; len -= size; } release_sock(sk); return sent; } static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; int len; if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) { rfcomm_dlc_accept(d); return 0; } len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags); lock_sock(sk); if (!(flags & MSG_PEEK) && len > 0) atomic_sub(len, &sk->sk_rmem_alloc); if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2)) rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc); release_sock(sk); return len; } static int rfcomm_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case RFCOMM_LM: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt & RFCOMM_LM_AUTH) rfcomm_pi(sk)->sec_level = BT_SECURITY_LOW; if (opt & RFCOMM_LM_ENCRYPT) rfcomm_pi(sk)->sec_level = BT_SECURITY_MEDIUM; if (opt & RFCOMM_LM_SECURE) rfcomm_pi(sk)->sec_level = BT_SECURITY_HIGH; rfcomm_pi(sk)->role_switch = (opt & RFCOMM_LM_MASTER); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct bt_security sec; int err = 0; size_t len; u32 opt; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_setsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = BT_SECURITY_LOW; len = min_t(unsigned int, sizeof(sec), optlen); if (copy_from_user((char *) &sec, optval, len)) { err = -EFAULT; break; } if (sec.level > BT_SECURITY_HIGH) { err = -EINVAL; break; } rfcomm_pi(sk)->sec_level = sec.level; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct rfcomm_conninfo cinfo; struct l2cap_conn *conn = l2cap_pi(sk)->chan->conn; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case RFCOMM_LM: switch (rfcomm_pi(sk)->sec_level) { case BT_SECURITY_LOW: opt = RFCOMM_LM_AUTH; break; case BT_SECURITY_MEDIUM: opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT; break; case BT_SECURITY_HIGH: opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT | RFCOMM_LM_SECURE; break; default: opt = 0; break; } if (rfcomm_pi(sk)->role_switch) opt |= RFCOMM_LM_MASTER; if (put_user(opt, (u32 __user *) optval)) err = -EFAULT; break; case RFCOMM_CONNINFO: if (sk->sk_state != BT_CONNECTED && !rfcomm_pi(sk)->dlc->defer_setup) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = conn->hcon->handle; memcpy(cinfo.dev_class, conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *) &cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct bt_security sec; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = rfcomm_pi(sk)->sec_level; sec.key_size = 0; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk __maybe_unused = sock->sk; int err; BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg); err = bt_sock_ioctl(sock, cmd, arg); if (err == -ENOIOCTLCMD) { #ifdef CONFIG_BT_RFCOMM_TTY lock_sock(sk); err = rfcomm_dev_ioctl(sk, cmd, (void __user *) arg); release_sock(sk); #else err = -EOPNOTSUPP; #endif } return err; } static int rfcomm_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; lock_sock(sk); if (!sk->sk_shutdown) { sk->sk_shutdown = SHUTDOWN_MASK; __rfcomm_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } release_sock(sk); return err; } static int rfcomm_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; err = rfcomm_sock_shutdown(sock, 2); sock_orphan(sk); rfcomm_sock_kill(sk); return err; } /* ---- RFCOMM core layer callbacks ---- * * called under rfcomm_lock() */ int rfcomm_connect_ind(struct rfcomm_session *s, u8 channel, struct rfcomm_dlc **d) { struct sock *sk, *parent; bdaddr_t src, dst; int result = 0; BT_DBG("session %p channel %d", s, channel); rfcomm_session_getaddr(s, &src, &dst); /* Check if we have socket listening on channel */ parent = rfcomm_get_sock_by_channel(BT_LISTEN, channel, &src); if (!parent) return 0; bh_lock_sock(parent); /* Check for backlog size */ if (sk_acceptq_is_full(parent)) { BT_DBG("backlog full %d", parent->sk_ack_backlog); goto done; } sk = rfcomm_sock_alloc(sock_net(parent), NULL, BTPROTO_RFCOMM, GFP_ATOMIC); if (!sk) goto done; bt_sock_reclassify_lock(sk, BTPROTO_RFCOMM); rfcomm_sock_init(sk, parent); bacpy(&bt_sk(sk)->src, &src); bacpy(&bt_sk(sk)->dst, &dst); rfcomm_pi(sk)->channel = channel; sk->sk_state = BT_CONFIG; bt_accept_enqueue(parent, sk); /* Accept connection and return socket DLC */ *d = rfcomm_pi(sk)->dlc; result = 1; done: bh_unlock_sock(parent); if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) parent->sk_state_change(parent); return result; } static int rfcomm_sock_debugfs_show(struct seq_file *f, void *p) { struct sock *sk; struct hlist_node *node; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, node, &rfcomm_sk_list.head) { seq_printf(f, "%s %s %d %d\n", batostr(&bt_sk(sk)->src), batostr(&bt_sk(sk)->dst), sk->sk_state, rfcomm_pi(sk)->channel); } read_unlock(&rfcomm_sk_list.lock); return 0; } static int rfcomm_sock_debugfs_open(struct inode *inode, struct file *file) { return single_open(file, rfcomm_sock_debugfs_show, inode->i_private); } static const struct file_operations rfcomm_sock_debugfs_fops = { .open = rfcomm_sock_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *rfcomm_sock_debugfs; static const struct proto_ops rfcomm_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = rfcomm_sock_release, .bind = rfcomm_sock_bind, .connect = rfcomm_sock_connect, .listen = rfcomm_sock_listen, .accept = rfcomm_sock_accept, .getname = rfcomm_sock_getname, .sendmsg = rfcomm_sock_sendmsg, .recvmsg = rfcomm_sock_recvmsg, .shutdown = rfcomm_sock_shutdown, .setsockopt = rfcomm_sock_setsockopt, .getsockopt = rfcomm_sock_getsockopt, .ioctl = rfcomm_sock_ioctl, .poll = bt_sock_poll, .socketpair = sock_no_socketpair, .mmap = sock_no_mmap }; static const struct net_proto_family rfcomm_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = rfcomm_sock_create }; int __init rfcomm_init_sockets(void) { int err; err = proto_register(&rfcomm_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_RFCOMM, &rfcomm_sock_family_ops); if (err < 0) goto error; if (bt_debugfs) { rfcomm_sock_debugfs = debugfs_create_file("rfcomm", 0444, bt_debugfs, NULL, &rfcomm_sock_debugfs_fops); if (!rfcomm_sock_debugfs) BT_ERR("Failed to create RFCOMM debug file"); } BT_INFO("RFCOMM socket layer initialized"); return 0; error: BT_ERR("RFCOMM socket layer registration failed"); proto_unregister(&rfcomm_proto); return err; } void __exit rfcomm_cleanup_sockets(void) { debugfs_remove(rfcomm_sock_debugfs); if (bt_sock_unregister(BTPROTO_RFCOMM) < 0) BT_ERR("RFCOMM socket layer unregistration failed"); proto_unregister(&rfcomm_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3836_0
crossvul-cpp_data_good_3769_1
/* * linux/fs/binfmt_script.c * * Copyright (C) 1996 Martin von Löwis * original #!-checking implemented by tytso. */ #include <linux/module.h> #include <linux/string.h> #include <linux/stat.h> #include <linux/binfmts.h> #include <linux/init.h> #include <linux/file.h> #include <linux/err.h> #include <linux/fs.h> static int load_script(struct linux_binprm *bprm) { const char *i_arg, *i_name; char *cp; struct file *file; char interp[BINPRM_BUF_SIZE]; int retval; if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!')) return -ENOEXEC; /* * This section does the #! interpretation. * Sorta complicated, but hopefully it will work. -TYT */ allow_write_access(bprm->file); fput(bprm->file); bprm->file = NULL; bprm->buf[BINPRM_BUF_SIZE - 1] = '\0'; if ((cp = strchr(bprm->buf, '\n')) == NULL) cp = bprm->buf+BINPRM_BUF_SIZE-1; *cp = '\0'; while (cp > bprm->buf) { cp--; if ((*cp == ' ') || (*cp == '\t')) *cp = '\0'; else break; } for (cp = bprm->buf+2; (*cp == ' ') || (*cp == '\t'); cp++); if (*cp == '\0') return -ENOEXEC; /* No interpreter name found */ i_name = cp; i_arg = NULL; for ( ; *cp && (*cp != ' ') && (*cp != '\t'); cp++) /* nothing */ ; while ((*cp == ' ') || (*cp == '\t')) *cp++ = '\0'; if (*cp) i_arg = cp; strcpy (interp, i_name); /* * OK, we've parsed out the interpreter name and * (optional) argument. * Splice in (1) the interpreter's name for argv[0] * (2) (optional) argument to interpreter * (3) filename of shell script (replace argv[0]) * * This is done in reverse order, because of how the * user environment and arguments are stored. */ retval = remove_arg_zero(bprm); if (retval) return retval; retval = copy_strings_kernel(1, &bprm->interp, bprm); if (retval < 0) return retval; bprm->argc++; if (i_arg) { retval = copy_strings_kernel(1, &i_arg, bprm); if (retval < 0) return retval; bprm->argc++; } retval = copy_strings_kernel(1, &i_name, bprm); if (retval) return retval; bprm->argc++; retval = bprm_change_interp(interp, bprm); if (retval < 0) return retval; /* * OK, now restart the process with the interpreter's dentry. */ file = open_exec(interp); if (IS_ERR(file)) return PTR_ERR(file); bprm->file = file; retval = prepare_binprm(bprm); if (retval < 0) return retval; return search_binary_handler(bprm); } static struct linux_binfmt script_format = { .module = THIS_MODULE, .load_binary = load_script, }; static int __init init_script_binfmt(void) { register_binfmt(&script_format); return 0; } static void __exit exit_script_binfmt(void) { unregister_binfmt(&script_format); } core_initcall(init_script_binfmt); module_exit(exit_script_binfmt); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/good_3769_1
crossvul-cpp_data_good_2951_0
// SPDX-License-Identifier: GPL-2.0 #include <linux/mm.h> #include <linux/highmem.h> #include <linux/sched.h> #include <linux/hugetlb.h> static int walk_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { pte_t *pte; int err = 0; pte = pte_offset_map(pmd, addr); for (;;) { err = walk->pte_entry(pte, addr, addr + PAGE_SIZE, walk); if (err) break; addr += PAGE_SIZE; if (addr == end) break; pte++; } pte_unmap(pte); return err; } static int walk_pmd_range(pud_t *pud, unsigned long addr, unsigned long end, struct mm_walk *walk) { pmd_t *pmd; unsigned long next; int err = 0; pmd = pmd_offset(pud, addr); do { again: next = pmd_addr_end(addr, end); if (pmd_none(*pmd) || !walk->vma) { if (walk->pte_hole) err = walk->pte_hole(addr, next, walk); if (err) break; continue; } /* * This implies that each ->pmd_entry() handler * needs to know about pmd_trans_huge() pmds */ if (walk->pmd_entry) err = walk->pmd_entry(pmd, addr, next, walk); if (err) break; /* * Check this here so we only break down trans_huge * pages when we _need_ to */ if (!walk->pte_entry) continue; split_huge_pmd(walk->vma, pmd, addr); if (pmd_trans_unstable(pmd)) goto again; err = walk_pte_range(pmd, addr, next, walk); if (err) break; } while (pmd++, addr = next, addr != end); return err; } static int walk_pud_range(p4d_t *p4d, unsigned long addr, unsigned long end, struct mm_walk *walk) { pud_t *pud; unsigned long next; int err = 0; pud = pud_offset(p4d, addr); do { again: next = pud_addr_end(addr, end); if (pud_none(*pud) || !walk->vma) { if (walk->pte_hole) err = walk->pte_hole(addr, next, walk); if (err) break; continue; } if (walk->pud_entry) { spinlock_t *ptl = pud_trans_huge_lock(pud, walk->vma); if (ptl) { err = walk->pud_entry(pud, addr, next, walk); spin_unlock(ptl); if (err) break; continue; } } split_huge_pud(walk->vma, pud, addr); if (pud_none(*pud)) goto again; if (walk->pmd_entry || walk->pte_entry) err = walk_pmd_range(pud, addr, next, walk); if (err) break; } while (pud++, addr = next, addr != end); return err; } static int walk_p4d_range(pgd_t *pgd, unsigned long addr, unsigned long end, struct mm_walk *walk) { p4d_t *p4d; unsigned long next; int err = 0; p4d = p4d_offset(pgd, addr); do { next = p4d_addr_end(addr, end); if (p4d_none_or_clear_bad(p4d)) { if (walk->pte_hole) err = walk->pte_hole(addr, next, walk); if (err) break; continue; } if (walk->pmd_entry || walk->pte_entry) err = walk_pud_range(p4d, addr, next, walk); if (err) break; } while (p4d++, addr = next, addr != end); return err; } static int walk_pgd_range(unsigned long addr, unsigned long end, struct mm_walk *walk) { pgd_t *pgd; unsigned long next; int err = 0; pgd = pgd_offset(walk->mm, addr); do { next = pgd_addr_end(addr, end); if (pgd_none_or_clear_bad(pgd)) { if (walk->pte_hole) err = walk->pte_hole(addr, next, walk); if (err) break; continue; } if (walk->pmd_entry || walk->pte_entry) err = walk_p4d_range(pgd, addr, next, walk); if (err) break; } while (pgd++, addr = next, addr != end); return err; } #ifdef CONFIG_HUGETLB_PAGE static unsigned long hugetlb_entry_end(struct hstate *h, unsigned long addr, unsigned long end) { unsigned long boundary = (addr & huge_page_mask(h)) + huge_page_size(h); return boundary < end ? boundary : end; } static int walk_hugetlb_range(unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; struct hstate *h = hstate_vma(vma); unsigned long next; unsigned long hmask = huge_page_mask(h); unsigned long sz = huge_page_size(h); pte_t *pte; int err = 0; do { next = hugetlb_entry_end(h, addr, end); pte = huge_pte_offset(walk->mm, addr & hmask, sz); if (pte) err = walk->hugetlb_entry(pte, hmask, addr, next, walk); else if (walk->pte_hole) err = walk->pte_hole(addr, next, walk); if (err) break; } while (addr = next, addr != end); return err; } #else /* CONFIG_HUGETLB_PAGE */ static int walk_hugetlb_range(unsigned long addr, unsigned long end, struct mm_walk *walk) { return 0; } #endif /* CONFIG_HUGETLB_PAGE */ /* * Decide whether we really walk over the current vma on [@start, @end) * or skip it via the returned value. Return 0 if we do walk over the * current vma, and return 1 if we skip the vma. Negative values means * error, where we abort the current walk. */ static int walk_page_test(unsigned long start, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; if (walk->test_walk) return walk->test_walk(start, end, walk); /* * vma(VM_PFNMAP) doesn't have any valid struct pages behind VM_PFNMAP * range, so we don't walk over it as we do for normal vmas. However, * Some callers are interested in handling hole range and they don't * want to just ignore any single address range. Such users certainly * define their ->pte_hole() callbacks, so let's delegate them to handle * vma(VM_PFNMAP). */ if (vma->vm_flags & VM_PFNMAP) { int err = 1; if (walk->pte_hole) err = walk->pte_hole(start, end, walk); return err ? err : 1; } return 0; } static int __walk_page_range(unsigned long start, unsigned long end, struct mm_walk *walk) { int err = 0; struct vm_area_struct *vma = walk->vma; if (vma && is_vm_hugetlb_page(vma)) { if (walk->hugetlb_entry) err = walk_hugetlb_range(start, end, walk); } else err = walk_pgd_range(start, end, walk); return err; } /** * walk_page_range - walk page table with caller specific callbacks * * Recursively walk the page table tree of the process represented by @walk->mm * within the virtual address range [@start, @end). During walking, we can do * some caller-specific works for each entry, by setting up pmd_entry(), * pte_entry(), and/or hugetlb_entry(). If you don't set up for some of these * callbacks, the associated entries/pages are just ignored. * The return values of these callbacks are commonly defined like below: * - 0 : succeeded to handle the current entry, and if you don't reach the * end address yet, continue to walk. * - >0 : succeeded to handle the current entry, and return to the caller * with caller specific value. * - <0 : failed to handle the current entry, and return to the caller * with error code. * * Before starting to walk page table, some callers want to check whether * they really want to walk over the current vma, typically by checking * its vm_flags. walk_page_test() and @walk->test_walk() are used for this * purpose. * * struct mm_walk keeps current values of some common data like vma and pmd, * which are useful for the access from callbacks. If you want to pass some * caller-specific data to callbacks, @walk->private should be helpful. * * Locking: * Callers of walk_page_range() and walk_page_vma() should hold * @walk->mm->mmap_sem, because these function traverse vma list and/or * access to vma's data. */ int walk_page_range(unsigned long start, unsigned long end, struct mm_walk *walk) { int err = 0; unsigned long next; struct vm_area_struct *vma; if (start >= end) return -EINVAL; if (!walk->mm) return -EINVAL; VM_BUG_ON_MM(!rwsem_is_locked(&walk->mm->mmap_sem), walk->mm); vma = find_vma(walk->mm, start); do { if (!vma) { /* after the last vma */ walk->vma = NULL; next = end; } else if (start < vma->vm_start) { /* outside vma */ walk->vma = NULL; next = min(end, vma->vm_start); } else { /* inside vma */ walk->vma = vma; next = min(end, vma->vm_end); vma = vma->vm_next; err = walk_page_test(start, next, walk); if (err > 0) { /* * positive return values are purely for * controlling the pagewalk, so should never * be passed to the callers. */ err = 0; continue; } if (err < 0) break; } if (walk->vma || walk->pte_hole) err = __walk_page_range(start, next, walk); if (err) break; } while (start = next, start < end); return err; } int walk_page_vma(struct vm_area_struct *vma, struct mm_walk *walk) { int err; if (!walk->mm) return -EINVAL; VM_BUG_ON(!rwsem_is_locked(&walk->mm->mmap_sem)); VM_BUG_ON(!vma); walk->vma = vma; err = walk_page_test(vma->vm_start, vma->vm_end, walk); if (err > 0) return 0; if (err < 0) return err; return __walk_page_range(vma->vm_start, vma->vm_end, walk); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2951_0
crossvul-cpp_data_bad_3840_0
/* * TUN - Universal TUN/TAP device driver. * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $ */ /* * Changes: * * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14 * Add TUNSETLINK ioctl to set the link encapsulation * * Mark Smith <markzzzsmith@yahoo.com.au> * Use eth_random_addr() for tap MAC address. * * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20 * Fixes in packet dropping, queue length setting and queue wakeup. * Increased default tx queue length. * Added ethtool API. * Minor cleanups * * Daniel Podlejski <underley@underley.eu.org> * Modifications for 2.3.99-pre5 kernel. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define DRV_NAME "tun" #define DRV_VERSION "1.6" #define DRV_DESCRIPTION "Universal TUN/TAP device driver" #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>" #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/major.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/miscdevice.h> #include <linux/ethtool.h> #include <linux/rtnetlink.h> #include <linux/compat.h> #include <linux/if.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/crc32.h> #include <linux/nsproxy.h> #include <linux/virtio_net.h> #include <linux/rcupdate.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/rtnetlink.h> #include <net/sock.h> #include <asm/uaccess.h> /* Uncomment to enable debugging */ /* #define TUN_DEBUG 1 */ #ifdef TUN_DEBUG static int debug; #define tun_debug(level, tun, fmt, args...) \ do { \ if (tun->debug) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (debug == 2) \ printk(level fmt, ##args); \ } while (0) #else #define tun_debug(level, tun, fmt, args...) \ do { \ if (0) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (0) \ printk(level fmt, ##args); \ } while (0) #endif #define GOODCOPY_LEN 128 #define FLT_EXACT_COUNT 8 struct tap_filter { unsigned int count; /* Number of addrs. Zero means disabled */ u32 mask[2]; /* Mask of the hashed addrs */ unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN]; }; struct tun_file { atomic_t count; struct tun_struct *tun; struct net *net; }; struct tun_sock; struct tun_struct { struct tun_file *tfile; unsigned int flags; uid_t owner; gid_t group; struct net_device *dev; netdev_features_t set_features; #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \ NETIF_F_TSO6|NETIF_F_UFO) struct fasync_struct *fasync; struct tap_filter txflt; struct socket socket; struct socket_wq wq; int vnet_hdr_sz; #ifdef TUN_DEBUG int debug; #endif }; struct tun_sock { struct sock sk; struct tun_struct *tun; }; static inline struct tun_sock *tun_sk(struct sock *sk) { return container_of(sk, struct tun_sock, sk); } static int tun_attach(struct tun_struct *tun, struct file *file) { struct tun_file *tfile = file->private_data; int err; ASSERT_RTNL(); netif_tx_lock_bh(tun->dev); err = -EINVAL; if (tfile->tun) goto out; err = -EBUSY; if (tun->tfile) goto out; err = 0; tfile->tun = tun; tun->tfile = tfile; tun->socket.file = file; netif_carrier_on(tun->dev); dev_hold(tun->dev); sock_hold(tun->socket.sk); atomic_inc(&tfile->count); out: netif_tx_unlock_bh(tun->dev); return err; } static void __tun_detach(struct tun_struct *tun) { /* Detach from net device */ netif_tx_lock_bh(tun->dev); netif_carrier_off(tun->dev); tun->tfile = NULL; tun->socket.file = NULL; netif_tx_unlock_bh(tun->dev); /* Drop read queue */ skb_queue_purge(&tun->socket.sk->sk_receive_queue); /* Drop the extra count on the net device */ dev_put(tun->dev); } static void tun_detach(struct tun_struct *tun) { rtnl_lock(); __tun_detach(tun); rtnl_unlock(); } static struct tun_struct *__tun_get(struct tun_file *tfile) { struct tun_struct *tun = NULL; if (atomic_inc_not_zero(&tfile->count)) tun = tfile->tun; return tun; } static struct tun_struct *tun_get(struct file *file) { return __tun_get(file->private_data); } static void tun_put(struct tun_struct *tun) { struct tun_file *tfile = tun->tfile; if (atomic_dec_and_test(&tfile->count)) tun_detach(tfile->tun); } /* TAP filtering */ static void addr_hash_set(u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; mask[n >> 5] |= (1 << (n & 31)); } static unsigned int addr_hash_test(const u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; return mask[n >> 5] & (1 << (n & 31)); } static int update_filter(struct tap_filter *filter, void __user *arg) { struct { u8 u[ETH_ALEN]; } *addr; struct tun_filter uf; int err, alen, n, nexact; if (copy_from_user(&uf, arg, sizeof(uf))) return -EFAULT; if (!uf.count) { /* Disabled */ filter->count = 0; return 0; } alen = ETH_ALEN * uf.count; addr = kmalloc(alen, GFP_KERNEL); if (!addr) return -ENOMEM; if (copy_from_user(addr, arg + sizeof(uf), alen)) { err = -EFAULT; goto done; } /* The filter is updated without holding any locks. Which is * perfectly safe. We disable it first and in the worst * case we'll accept a few undesired packets. */ filter->count = 0; wmb(); /* Use first set of addresses as an exact filter */ for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++) memcpy(filter->addr[n], addr[n].u, ETH_ALEN); nexact = n; /* Remaining multicast addresses are hashed, * unicast will leave the filter disabled. */ memset(filter->mask, 0, sizeof(filter->mask)); for (; n < uf.count; n++) { if (!is_multicast_ether_addr(addr[n].u)) { err = 0; /* no filter */ goto done; } addr_hash_set(filter->mask, addr[n].u); } /* For ALLMULTI just set the mask to all ones. * This overrides the mask populated above. */ if ((uf.flags & TUN_FLT_ALLMULTI)) memset(filter->mask, ~0, sizeof(filter->mask)); /* Now enable the filter */ wmb(); filter->count = nexact; /* Return the number of exact filters */ err = nexact; done: kfree(addr); return err; } /* Returns: 0 - drop, !=0 - accept */ static int run_filter(struct tap_filter *filter, const struct sk_buff *skb) { /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect * at this point. */ struct ethhdr *eh = (struct ethhdr *) skb->data; int i; /* Exact match */ for (i = 0; i < filter->count; i++) if (ether_addr_equal(eh->h_dest, filter->addr[i])) return 1; /* Inexact match (multicast only) */ if (is_multicast_ether_addr(eh->h_dest)) return addr_hash_test(filter->mask, eh->h_dest); return 0; } /* * Checks whether the packet is accepted or not. * Returns: 0 - drop, !=0 - accept */ static int check_filter(struct tap_filter *filter, const struct sk_buff *skb) { if (!filter->count) return 1; return run_filter(filter, skb); } /* Network device part of the driver */ static const struct ethtool_ops tun_ethtool_ops; /* Net device detach from fd. */ static void tun_net_uninit(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); struct tun_file *tfile = tun->tfile; /* Inform the methods they need to stop using the dev. */ if (tfile) { wake_up_all(&tun->wq.wait); if (atomic_dec_and_test(&tfile->count)) __tun_detach(tun); } } static void tun_free_netdev(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED, &tun->socket.flags)); sk_release_kernel(tun->socket.sk); } /* Net device open. */ static int tun_net_open(struct net_device *dev) { netif_start_queue(dev); return 0; } /* Net device close. */ static int tun_net_close(struct net_device *dev) { netif_stop_queue(dev); return 0; } /* Net device start xmit */ static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len); /* Drop packet if interface is not attached */ if (!tun->tfile) goto drop; /* Drop if the filter does not like it. * This is a noop if the filter is disabled. * Filter can be enabled only for the TAP devices. */ if (!check_filter(&tun->txflt, skb)) goto drop; if (tun->socket.sk->sk_filter && sk_filter(tun->socket.sk, skb)) goto drop; if (skb_queue_len(&tun->socket.sk->sk_receive_queue) >= dev->tx_queue_len) { if (!(tun->flags & TUN_ONE_QUEUE)) { /* Normal queueing mode. */ /* Packet scheduler handles dropping of further packets. */ netif_stop_queue(dev); /* We won't see all dropped packets individually, so overrun * error is more appropriate. */ dev->stats.tx_fifo_errors++; } else { /* Single queue mode. * Driver handles dropping of all packets itself. */ goto drop; } } /* Orphan the skb - required as we might hang on to it * for indefinite time. */ if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC))) goto drop; skb_orphan(skb); /* Enqueue packet */ skb_queue_tail(&tun->socket.sk->sk_receive_queue, skb); /* Notify and wake up reader process */ if (tun->flags & TUN_FASYNC) kill_fasync(&tun->fasync, SIGIO, POLL_IN); wake_up_interruptible_poll(&tun->wq.wait, POLLIN | POLLRDNORM | POLLRDBAND); return NETDEV_TX_OK; drop: dev->stats.tx_dropped++; kfree_skb(skb); return NETDEV_TX_OK; } static void tun_net_mclist(struct net_device *dev) { /* * This callback is supposed to deal with mc filter in * _rx_ path and has nothing to do with the _tx_ path. * In rx path we always accept everything userspace gives us. */ } #define MIN_MTU 68 #define MAX_MTU 65535 static int tun_net_change_mtu(struct net_device *dev, int new_mtu) { if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU) return -EINVAL; dev->mtu = new_mtu; return 0; } static netdev_features_t tun_net_fix_features(struct net_device *dev, netdev_features_t features) { struct tun_struct *tun = netdev_priv(dev); return (features & tun->set_features) | (features & ~TUN_USER_FEATURES); } #ifdef CONFIG_NET_POLL_CONTROLLER static void tun_poll_controller(struct net_device *dev) { /* * Tun only receives frames when: * 1) the char device endpoint gets data from user space * 2) the tun socket gets a sendmsg call from user space * Since both of those are syncronous operations, we are guaranteed * never to have pending data when we poll for it * so theres nothing to do here but return. * We need this though so netpoll recognizes us as an interface that * supports polling, which enables bridge devices in virt setups to * still use netconsole */ return; } #endif static const struct net_device_ops tun_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_change_mtu = tun_net_change_mtu, .ndo_fix_features = tun_net_fix_features, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif }; static const struct net_device_ops tap_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_change_mtu = tun_net_change_mtu, .ndo_fix_features = tun_net_fix_features, .ndo_set_rx_mode = tun_net_mclist, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif }; /* Initialize net device. */ static void tun_net_init(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: dev->netdev_ops = &tun_netdev_ops; /* Point-to-Point TUN Device */ dev->hard_header_len = 0; dev->addr_len = 0; dev->mtu = 1500; /* Zero header length */ dev->type = ARPHRD_NONE; dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; case TUN_TAP_DEV: dev->netdev_ops = &tap_netdev_ops; /* Ethernet TAP Device */ ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; eth_hw_addr_random(dev); dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; } } /* Character device part */ /* Poll */ static unsigned int tun_chr_poll(struct file *file, poll_table * wait) { struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); struct sock *sk; unsigned int mask = 0; if (!tun) return POLLERR; sk = tun->socket.sk; tun_debug(KERN_INFO, tun, "tun_chr_poll\n"); poll_wait(file, &tun->wq.wait, wait); if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; if (sock_writeable(sk) || (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) && sock_writeable(sk))) mask |= POLLOUT | POLLWRNORM; if (tun->dev->reg_state != NETREG_REGISTERED) mask = POLLERR; tun_put(tun); return mask; } /* prepad is the amount to reserve at front. len is length after that. * linear is a hint as to how much to copy (usually headers). */ static struct sk_buff *tun_alloc_skb(struct tun_struct *tun, size_t prepad, size_t len, size_t linear, int noblock) { struct sock *sk = tun->socket.sk; struct sk_buff *skb; int err; sock_update_classid(sk); /* Under a page? Don't bother with paged skb. */ if (prepad + len < PAGE_SIZE || !linear) linear = len; skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock, &err); if (!skb) return ERR_PTR(err); skb_reserve(skb, prepad); skb_put(skb, linear); skb->data_len = len - linear; skb->len += len - linear; return skb; } /* set skb frags from iovec, this can move to core network code for reuse */ static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from, int offset, size_t count) { int len = iov_length(from, count) - offset; int copy = skb_headlen(skb); int size, offset1 = 0; int i = 0; /* Skip over from offset */ while (count && (offset >= from->iov_len)) { offset -= from->iov_len; ++from; --count; } /* copy up to skb headlen */ while (count && (copy > 0)) { size = min_t(unsigned int, copy, from->iov_len - offset); if (copy_from_user(skb->data + offset1, from->iov_base + offset, size)) return -EFAULT; if (copy > size) { ++from; --count; offset = 0; } else offset += size; copy -= size; offset1 += size; } if (len == offset1) return 0; while (count--) { struct page *page[MAX_SKB_FRAGS]; int num_pages; unsigned long base; unsigned long truesize; len = from->iov_len - offset; if (!len) { offset = 0; ++from; continue; } base = (unsigned long)from->iov_base + offset; size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT; if (i + size > MAX_SKB_FRAGS) return -EMSGSIZE; num_pages = get_user_pages_fast(base, size, 0, &page[i]); if (num_pages != size) { for (i = 0; i < num_pages; i++) put_page(page[i]); return -EFAULT; } truesize = size * PAGE_SIZE; skb->data_len += len; skb->len += len; skb->truesize += truesize; atomic_add(truesize, &skb->sk->sk_wmem_alloc); while (len) { int off = base & ~PAGE_MASK; int size = min_t(int, len, PAGE_SIZE - off); __skb_fill_page_desc(skb, i, page[i], off, size); skb_shinfo(skb)->nr_frags++; /* increase sk_wmem_alloc */ base += size; len -= size; i++; } offset = 0; ++from; } return 0; } /* Get packet from user space buffer */ static ssize_t tun_get_user(struct tun_struct *tun, void *msg_control, const struct iovec *iv, size_t total_len, size_t count, int noblock) { struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) }; struct sk_buff *skb; size_t len = total_len, align = NET_SKB_PAD; struct virtio_net_hdr gso = { 0 }; int offset = 0; int copylen; bool zerocopy = false; int err; if (!(tun->flags & TUN_NO_PI)) { if ((len -= sizeof(pi)) > total_len) return -EINVAL; if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi))) return -EFAULT; offset += sizeof(pi); } if (tun->flags & TUN_VNET_HDR) { if ((len -= tun->vnet_hdr_sz) > total_len) return -EINVAL; if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso))) return -EFAULT; if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && gso.csum_start + gso.csum_offset + 2 > gso.hdr_len) gso.hdr_len = gso.csum_start + gso.csum_offset + 2; if (gso.hdr_len > len) return -EINVAL; offset += tun->vnet_hdr_sz; } if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) { align += NET_IP_ALIGN; if (unlikely(len < ETH_HLEN || (gso.hdr_len && gso.hdr_len < ETH_HLEN))) return -EINVAL; } if (msg_control) zerocopy = true; if (zerocopy) { /* Userspace may produce vectors with count greater than * MAX_SKB_FRAGS, so we need to linearize parts of the skb * to let the rest of data to be fit in the frags. */ if (count > MAX_SKB_FRAGS) { copylen = iov_length(iv, count - MAX_SKB_FRAGS); if (copylen < offset) copylen = 0; else copylen -= offset; } else copylen = 0; /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest of the buffer is mapped from userspace. */ if (copylen < gso.hdr_len) copylen = gso.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = tun_alloc_skb(tun, align, copylen, gso.hdr_len, noblock); if (IS_ERR(skb)) { if (PTR_ERR(skb) != -EAGAIN) tun->dev->stats.rx_dropped++; return PTR_ERR(skb); } if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, offset, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len); if (err) { tun->dev->stats.rx_dropped++; kfree_skb(skb); return -EFAULT; } if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { if (!skb_partial_csum_set(skb, gso.csum_start, gso.csum_offset)) { tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } } switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: if (tun->flags & TUN_NO_PI) { switch (skb->data[0] & 0xf0) { case 0x40: pi.proto = htons(ETH_P_IP); break; case 0x60: pi.proto = htons(ETH_P_IPV6); break; default: tun->dev->stats.rx_dropped++; kfree_skb(skb); return -EINVAL; } } skb_reset_mac_header(skb); skb->protocol = pi.proto; skb->dev = tun->dev; break; case TUN_TAP_DEV: skb->protocol = eth_type_trans(skb, tun->dev); break; } if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) { pr_debug("GSO!\n"); switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) { case VIRTIO_NET_HDR_GSO_TCPV4: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; break; case VIRTIO_NET_HDR_GSO_TCPV6: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6; break; case VIRTIO_NET_HDR_GSO_UDP: skb_shinfo(skb)->gso_type = SKB_GSO_UDP; break; default: tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN) skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; skb_shinfo(skb)->gso_size = gso.gso_size; if (skb_shinfo(skb)->gso_size == 0) { tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } /* Header must be checked, and gso_segs computed. */ skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; skb_shinfo(skb)->gso_segs = 0; } /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } netif_rx_ni(skb); tun->dev->stats.rx_packets++; tun->dev->stats.rx_bytes += len; return total_len; } static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv, unsigned long count, loff_t pos) { struct file *file = iocb->ki_filp; struct tun_struct *tun = tun_get(file); ssize_t result; if (!tun) return -EBADFD; tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count); result = tun_get_user(tun, NULL, iv, iov_length(iv, count), count, file->f_flags & O_NONBLOCK); tun_put(tun); return result; } /* Put packet to the user space buffer */ static ssize_t tun_put_user(struct tun_struct *tun, struct sk_buff *skb, const struct iovec *iv, int len) { struct tun_pi pi = { 0, skb->protocol }; ssize_t total = 0; if (!(tun->flags & TUN_NO_PI)) { if ((len -= sizeof(pi)) < 0) return -EINVAL; if (len < skb->len) { /* Packet will be striped */ pi.flags |= TUN_PKT_STRIP; } if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi))) return -EFAULT; total += sizeof(pi); } if (tun->flags & TUN_VNET_HDR) { struct virtio_net_hdr gso = { 0 }; /* no info leak */ if ((len -= tun->vnet_hdr_sz) < 0) return -EINVAL; if (skb_is_gso(skb)) { struct skb_shared_info *sinfo = skb_shinfo(skb); /* This is a hint as to how much should be linear. */ gso.hdr_len = skb_headlen(skb); gso.gso_size = sinfo->gso_size; if (sinfo->gso_type & SKB_GSO_TCPV4) gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4; else if (sinfo->gso_type & SKB_GSO_TCPV6) gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6; else if (sinfo->gso_type & SKB_GSO_UDP) gso.gso_type = VIRTIO_NET_HDR_GSO_UDP; else { pr_err("unexpected GSO type: " "0x%x, gso_size %d, hdr_len %d\n", sinfo->gso_type, gso.gso_size, gso.hdr_len); print_hex_dump(KERN_ERR, "tun: ", DUMP_PREFIX_NONE, 16, 1, skb->head, min((int)gso.hdr_len, 64), true); WARN_ON_ONCE(1); return -EINVAL; } if (sinfo->gso_type & SKB_GSO_TCP_ECN) gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN; } else gso.gso_type = VIRTIO_NET_HDR_GSO_NONE; if (skb->ip_summed == CHECKSUM_PARTIAL) { gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; gso.csum_start = skb_checksum_start_offset(skb); gso.csum_offset = skb->csum_offset; } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) { gso.flags = VIRTIO_NET_HDR_F_DATA_VALID; } /* else everything is zero */ if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total, sizeof(gso)))) return -EFAULT; total += tun->vnet_hdr_sz; } len = min_t(int, skb->len, len); skb_copy_datagram_const_iovec(skb, 0, iv, total, len); total += skb->len; tun->dev->stats.tx_packets++; tun->dev->stats.tx_bytes += len; return total; } static ssize_t tun_do_read(struct tun_struct *tun, struct kiocb *iocb, const struct iovec *iv, ssize_t len, int noblock) { DECLARE_WAITQUEUE(wait, current); struct sk_buff *skb; ssize_t ret = 0; tun_debug(KERN_INFO, tun, "tun_chr_read\n"); if (unlikely(!noblock)) add_wait_queue(&tun->wq.wait, &wait); while (len) { current->state = TASK_INTERRUPTIBLE; /* Read frames from the queue */ if (!(skb=skb_dequeue(&tun->socket.sk->sk_receive_queue))) { if (noblock) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = -ERESTARTSYS; break; } if (tun->dev->reg_state != NETREG_REGISTERED) { ret = -EIO; break; } /* Nothing to read, let's sleep */ schedule(); continue; } netif_wake_queue(tun->dev); ret = tun_put_user(tun, skb, iv, len); kfree_skb(skb); break; } current->state = TASK_RUNNING; if (unlikely(!noblock)) remove_wait_queue(&tun->wq.wait, &wait); return ret; } static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv, unsigned long count, loff_t pos) { struct file *file = iocb->ki_filp; struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); ssize_t len, ret; if (!tun) return -EBADFD; len = iov_length(iv, count); if (len < 0) { ret = -EINVAL; goto out; } ret = tun_do_read(tun, iocb, iv, len, file->f_flags & O_NONBLOCK); ret = min_t(ssize_t, ret, len); out: tun_put(tun); return ret; } static void tun_setup(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); tun->owner = -1; tun->group = -1; dev->ethtool_ops = &tun_ethtool_ops; dev->destructor = tun_free_netdev; } /* Trivial set of netlink ops to allow deleting tun or tap * device with netlink. */ static int tun_validate(struct nlattr *tb[], struct nlattr *data[]) { return -EINVAL; } static struct rtnl_link_ops tun_link_ops __read_mostly = { .kind = DRV_NAME, .priv_size = sizeof(struct tun_struct), .setup = tun_setup, .validate = tun_validate, }; static void tun_sock_write_space(struct sock *sk) { struct tun_struct *tun; wait_queue_head_t *wqueue; if (!sock_writeable(sk)) return; if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags)) return; wqueue = sk_sleep(sk); if (wqueue && waitqueue_active(wqueue)) wake_up_interruptible_sync_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND); tun = tun_sk(sk)->tun; kill_fasync(&tun->fasync, SIGIO, POLL_OUT); } static void tun_sock_destruct(struct sock *sk) { free_netdev(tun_sk(sk)->tun->dev); } static int tun_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len) { struct tun_struct *tun = container_of(sock, struct tun_struct, socket); return tun_get_user(tun, m->msg_control, m->msg_iov, total_len, m->msg_iovlen, m->msg_flags & MSG_DONTWAIT); } static int tun_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len, int flags) { struct tun_struct *tun = container_of(sock, struct tun_struct, socket); int ret; if (flags & ~(MSG_DONTWAIT|MSG_TRUNC)) return -EINVAL; ret = tun_do_read(tun, iocb, m->msg_iov, total_len, flags & MSG_DONTWAIT); if (ret > total_len) { m->msg_flags |= MSG_TRUNC; ret = flags & MSG_TRUNC ? ret : total_len; } return ret; } static int tun_release(struct socket *sock) { if (sock->sk) sock_put(sock->sk); return 0; } /* Ops structure to mimic raw sockets with tun */ static const struct proto_ops tun_socket_ops = { .sendmsg = tun_sendmsg, .recvmsg = tun_recvmsg, .release = tun_release, }; static struct proto tun_proto = { .name = "tun", .owner = THIS_MODULE, .obj_size = sizeof(struct tun_sock), }; static int tun_flags(struct tun_struct *tun) { int flags = 0; if (tun->flags & TUN_TUN_DEV) flags |= IFF_TUN; else flags |= IFF_TAP; if (tun->flags & TUN_NO_PI) flags |= IFF_NO_PI; if (tun->flags & TUN_ONE_QUEUE) flags |= IFF_ONE_QUEUE; if (tun->flags & TUN_VNET_HDR) flags |= IFF_VNET_HDR; return flags; } static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "0x%x\n", tun_flags(tun)); } static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "%d\n", tun->owner); } static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "%d\n", tun->group); } static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL); static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL); static DEVICE_ATTR(group, 0444, tun_show_group, NULL); static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct sock *sk; struct tun_struct *tun; struct net_device *dev; int err; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { const struct cred *cred = current_cred(); if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (((tun->owner != -1 && cred->euid != tun->owner) || (tun->group != -1 && !in_egroup_p(tun->group))) && !capable(CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_attach(tun->socket.sk); if (err < 0) return err; err = tun_attach(tun, file); if (err < 0) return err; } else { char *name; unsigned long flags = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= TUN_TUN_DEV; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= TUN_TAP_DEV; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev(sizeof(struct tun_struct), name, tun_setup); if (!dev) return -ENOMEM; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); set_bit(SOCK_EXTERNALLY_ALLOCATED, &tun->socket.flags); err = -ENOMEM; sk = sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL, &tun_proto); if (!sk) goto err_free_dev; sk_change_net(sk, net); tun->socket.wq = &tun->wq; init_waitqueue_head(&tun->wq.wait); tun->socket.ops = &tun_socket_ops; sock_init_data(&tun->socket, sk); sk->sk_write_space = tun_sock_write_space; sk->sk_sndbuf = INT_MAX; sock_set_flag(sk, SOCK_ZEROCOPY); tun_sk(sk)->tun = tun; security_tun_dev_post_create(sk); tun_net_init(dev); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES; dev->features = dev->hw_features; err = register_netdevice(tun->dev); if (err < 0) goto err_free_sk; if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) || device_create_file(&tun->dev->dev, &dev_attr_owner) || device_create_file(&tun->dev->dev, &dev_attr_group)) pr_err("Failed to create tun sysfs files\n"); sk->sk_destruct = tun_sock_destruct; err = tun_attach(tun, file); if (err < 0) goto failed; } tun_debug(KERN_INFO, tun, "tun_set_iff\n"); if (ifr->ifr_flags & IFF_NO_PI) tun->flags |= TUN_NO_PI; else tun->flags &= ~TUN_NO_PI; if (ifr->ifr_flags & IFF_ONE_QUEUE) tun->flags |= TUN_ONE_QUEUE; else tun->flags &= ~TUN_ONE_QUEUE; if (ifr->ifr_flags & IFF_VNET_HDR) tun->flags |= TUN_VNET_HDR; else tun->flags &= ~TUN_VNET_HDR; /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_wake_queue(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_free_sk: tun_free_netdev(dev); err_free_dev: free_netdev(dev); failed: return err; } static int tun_get_iff(struct net *net, struct tun_struct *tun, struct ifreq *ifr) { tun_debug(KERN_INFO, tun, "tun_get_iff\n"); strcpy(ifr->ifr_name, tun->dev->name); ifr->ifr_flags = tun_flags(tun); return 0; } /* This is like a cut-down ethtool ops, except done via tun fd so no * privs required. */ static int set_offload(struct tun_struct *tun, unsigned long arg) { netdev_features_t features = 0; if (arg & TUN_F_CSUM) { features |= NETIF_F_HW_CSUM; arg &= ~TUN_F_CSUM; if (arg & (TUN_F_TSO4|TUN_F_TSO6)) { if (arg & TUN_F_TSO_ECN) { features |= NETIF_F_TSO_ECN; arg &= ~TUN_F_TSO_ECN; } if (arg & TUN_F_TSO4) features |= NETIF_F_TSO; if (arg & TUN_F_TSO6) features |= NETIF_F_TSO6; arg &= ~(TUN_F_TSO4|TUN_F_TSO6); } if (arg & TUN_F_UFO) { features |= NETIF_F_UFO; arg &= ~TUN_F_UFO; } } /* This gives the user a way to test for new features in future by * trying to set them. */ if (arg) return -EINVAL; tun->set_features = features; netdev_update_features(tun->dev); return 0; } static long __tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg, int ifreq_len) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; void __user* argp = (void __user*)arg; struct sock_fprog fprog; struct ifreq ifr; int sndbuf; int vnet_hdr_sz; int ret; if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89) if (copy_from_user(&ifr, argp, ifreq_len)) return -EFAULT; if (cmd == TUNGETFEATURES) { /* Currently this just means: "what IFF flags are valid?". * This is needed because we never checked for invalid flags on * TUNSETIFF. */ return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR, (unsigned int __user*)argp); } rtnl_lock(); tun = __tun_get(tfile); if (cmd == TUNSETIFF && !tun) { ifr.ifr_name[IFNAMSIZ-1] = '\0'; ret = tun_set_iff(tfile->net, file, &ifr); if (ret) goto unlock; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; goto unlock; } ret = -EBADFD; if (!tun) goto unlock; tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %d\n", cmd); ret = 0; switch (cmd) { case TUNGETIFF: ret = tun_get_iff(current->nsproxy->net_ns, tun, &ifr); if (ret) break; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case TUNSETNOCSUM: /* Disable/Enable checksum */ /* [unimplemented] */ tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n", arg ? "disabled" : "enabled"); break; case TUNSETPERSIST: /* Disable/Enable persist mode */ if (arg) tun->flags |= TUN_PERSIST; else tun->flags &= ~TUN_PERSIST; tun_debug(KERN_INFO, tun, "persist %s\n", arg ? "enabled" : "disabled"); break; case TUNSETOWNER: /* Set owner of the device */ tun->owner = (uid_t) arg; tun_debug(KERN_INFO, tun, "owner set to %d\n", tun->owner); break; case TUNSETGROUP: /* Set group of the device */ tun->group= (gid_t) arg; tun_debug(KERN_INFO, tun, "group set to %d\n", tun->group); break; case TUNSETLINK: /* Only allow setting the type when the interface is down */ if (tun->dev->flags & IFF_UP) { tun_debug(KERN_INFO, tun, "Linktype set failed because interface is up\n"); ret = -EBUSY; } else { tun->dev->type = (int) arg; tun_debug(KERN_INFO, tun, "linktype set to %d\n", tun->dev->type); ret = 0; } break; #ifdef TUN_DEBUG case TUNSETDEBUG: tun->debug = arg; break; #endif case TUNSETOFFLOAD: ret = set_offload(tun, arg); break; case TUNSETTXFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV) break; ret = update_filter(&tun->txflt, (void __user *)arg); break; case SIOCGIFHWADDR: /* Get hw address */ memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN); ifr.ifr_hwaddr.sa_family = tun->dev->type; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case SIOCSIFHWADDR: /* Set hw address */ tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n", ifr.ifr_hwaddr.sa_data); ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr); break; case TUNGETSNDBUF: sndbuf = tun->socket.sk->sk_sndbuf; if (copy_to_user(argp, &sndbuf, sizeof(sndbuf))) ret = -EFAULT; break; case TUNSETSNDBUF: if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) { ret = -EFAULT; break; } tun->socket.sk->sk_sndbuf = sndbuf; break; case TUNGETVNETHDRSZ: vnet_hdr_sz = tun->vnet_hdr_sz; if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz))) ret = -EFAULT; break; case TUNSETVNETHDRSZ: if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) { ret = -EFAULT; break; } if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) { ret = -EINVAL; break; } tun->vnet_hdr_sz = vnet_hdr_sz; break; case TUNATTACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV) break; ret = -EFAULT; if (copy_from_user(&fprog, argp, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, tun->socket.sk); break; case TUNDETACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV) break; ret = sk_detach_filter(tun->socket.sk); break; default: ret = -EINVAL; break; } unlock: rtnl_unlock(); if (tun) tun_put(tun); return ret; } static long tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq)); } #ifdef CONFIG_COMPAT static long tun_chr_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case TUNSETIFF: case TUNGETIFF: case TUNSETTXFILTER: case TUNGETSNDBUF: case TUNSETSNDBUF: case SIOCGIFHWADDR: case SIOCSIFHWADDR: arg = (unsigned long)compat_ptr(arg); break; default: arg = (compat_ulong_t)arg; break; } /* * compat_ifreq is shorter than ifreq, so we must not access beyond * the end of that structure. All fields that are used in this * driver are compatible though, we don't need to convert the * contents. */ return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq)); } #endif /* CONFIG_COMPAT */ static int tun_chr_fasync(int fd, struct file *file, int on) { struct tun_struct *tun = tun_get(file); int ret; if (!tun) return -EBADFD; tun_debug(KERN_INFO, tun, "tun_chr_fasync %d\n", on); if ((ret = fasync_helper(fd, file, on, &tun->fasync)) < 0) goto out; if (on) { ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0); if (ret) goto out; tun->flags |= TUN_FASYNC; } else tun->flags &= ~TUN_FASYNC; ret = 0; out: tun_put(tun); return ret; } static int tun_chr_open(struct inode *inode, struct file * file) { struct tun_file *tfile; DBG1(KERN_INFO, "tunX: tun_chr_open\n"); tfile = kmalloc(sizeof(*tfile), GFP_KERNEL); if (!tfile) return -ENOMEM; atomic_set(&tfile->count, 0); tfile->tun = NULL; tfile->net = get_net(current->nsproxy->net_ns); file->private_data = tfile; return 0; } static int tun_chr_close(struct inode *inode, struct file *file) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; tun = __tun_get(tfile); if (tun) { struct net_device *dev = tun->dev; tun_debug(KERN_INFO, tun, "tun_chr_close\n"); __tun_detach(tun); /* If desirable, unregister the netdevice. */ if (!(tun->flags & TUN_PERSIST)) { rtnl_lock(); if (dev->reg_state == NETREG_REGISTERED) unregister_netdevice(dev); rtnl_unlock(); } } tun = tfile->tun; if (tun) sock_put(tun->socket.sk); put_net(tfile->net); kfree(tfile); return 0; } static const struct file_operations tun_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .read = do_sync_read, .aio_read = tun_chr_aio_read, .write = do_sync_write, .aio_write = tun_chr_aio_write, .poll = tun_chr_poll, .unlocked_ioctl = tun_chr_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = tun_chr_compat_ioctl, #endif .open = tun_chr_open, .release = tun_chr_close, .fasync = tun_chr_fasync }; static struct miscdevice tun_miscdev = { .minor = TUN_MINOR, .name = "tun", .nodename = "net/tun", .fops = &tun_fops, }; /* ethtool interface */ static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { cmd->supported = 0; cmd->advertising = 0; ethtool_cmd_speed_set(cmd, SPEED_10); cmd->duplex = DUPLEX_FULL; cmd->port = PORT_TP; cmd->phy_address = 0; cmd->transceiver = XCVR_INTERNAL; cmd->autoneg = AUTONEG_DISABLE; cmd->maxtxpkt = 0; cmd->maxrxpkt = 0; return 0; } static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct tun_struct *tun = netdev_priv(dev); strlcpy(info->driver, DRV_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_VERSION, sizeof(info->version)); switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: strlcpy(info->bus_info, "tun", sizeof(info->bus_info)); break; case TUN_TAP_DEV: strlcpy(info->bus_info, "tap", sizeof(info->bus_info)); break; } } static u32 tun_get_msglevel(struct net_device *dev) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); return tun->debug; #else return -EOPNOTSUPP; #endif } static void tun_set_msglevel(struct net_device *dev, u32 value) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); tun->debug = value; #endif } static const struct ethtool_ops tun_ethtool_ops = { .get_settings = tun_get_settings, .get_drvinfo = tun_get_drvinfo, .get_msglevel = tun_get_msglevel, .set_msglevel = tun_set_msglevel, .get_link = ethtool_op_get_link, }; static int __init tun_init(void) { int ret = 0; pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION); pr_info("%s\n", DRV_COPYRIGHT); ret = rtnl_link_register(&tun_link_ops); if (ret) { pr_err("Can't register link_ops\n"); goto err_linkops; } ret = misc_register(&tun_miscdev); if (ret) { pr_err("Can't register misc device %d\n", TUN_MINOR); goto err_misc; } return 0; err_misc: rtnl_link_unregister(&tun_link_ops); err_linkops: return ret; } static void tun_cleanup(void) { misc_deregister(&tun_miscdev); rtnl_link_unregister(&tun_link_ops); } /* Get an underlying socket object from tun file. Returns error unless file is * attached to a device. The returned object works like a packet socket, it * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for * holding a reference to the file for as long as the socket is in use. */ struct socket *tun_get_socket(struct file *file) { struct tun_struct *tun; if (file->f_op != &tun_fops) return ERR_PTR(-EINVAL); tun = tun_get(file); if (!tun) return ERR_PTR(-EBADFD); tun_put(tun); return &tun->socket; } EXPORT_SYMBOL_GPL(tun_get_socket); module_init(tun_init); module_exit(tun_cleanup); MODULE_DESCRIPTION(DRV_DESCRIPTION); MODULE_AUTHOR(DRV_COPYRIGHT); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(TUN_MINOR); MODULE_ALIAS("devname:net/tun");
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3840_0
crossvul-cpp_data_bad_4747_0
#include <linux/mm.h> #include <linux/vmacache.h> #include <linux/hugetlb.h> #include <linux/huge_mm.h> #include <linux/mount.h> #include <linux/seq_file.h> #include <linux/highmem.h> #include <linux/ptrace.h> #include <linux/slab.h> #include <linux/pagemap.h> #include <linux/mempolicy.h> #include <linux/rmap.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/mmu_notifier.h> #include <asm/elf.h> #include <asm/uaccess.h> #include <asm/tlbflush.h> #include "internal.h" void task_mem(struct seq_file *m, struct mm_struct *mm) { unsigned long data, text, lib, swap, ptes, pmds; unsigned long hiwater_vm, total_vm, hiwater_rss, total_rss; /* * Note: to minimize their overhead, mm maintains hiwater_vm and * hiwater_rss only when about to *lower* total_vm or rss. Any * collector of these hiwater stats must therefore get total_vm * and rss too, which will usually be the higher. Barriers? not * worth the effort, such snapshots can always be inconsistent. */ hiwater_vm = total_vm = mm->total_vm; if (hiwater_vm < mm->hiwater_vm) hiwater_vm = mm->hiwater_vm; hiwater_rss = total_rss = get_mm_rss(mm); if (hiwater_rss < mm->hiwater_rss) hiwater_rss = mm->hiwater_rss; data = mm->total_vm - mm->shared_vm - mm->stack_vm; text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> 10; lib = (mm->exec_vm << (PAGE_SHIFT-10)) - text; swap = get_mm_counter(mm, MM_SWAPENTS); ptes = PTRS_PER_PTE * sizeof(pte_t) * atomic_long_read(&mm->nr_ptes); pmds = PTRS_PER_PMD * sizeof(pmd_t) * mm_nr_pmds(mm); seq_printf(m, "VmPeak:\t%8lu kB\n" "VmSize:\t%8lu kB\n" "VmLck:\t%8lu kB\n" "VmPin:\t%8lu kB\n" "VmHWM:\t%8lu kB\n" "VmRSS:\t%8lu kB\n" "VmData:\t%8lu kB\n" "VmStk:\t%8lu kB\n" "VmExe:\t%8lu kB\n" "VmLib:\t%8lu kB\n" "VmPTE:\t%8lu kB\n" "VmPMD:\t%8lu kB\n" "VmSwap:\t%8lu kB\n", hiwater_vm << (PAGE_SHIFT-10), total_vm << (PAGE_SHIFT-10), mm->locked_vm << (PAGE_SHIFT-10), mm->pinned_vm << (PAGE_SHIFT-10), hiwater_rss << (PAGE_SHIFT-10), total_rss << (PAGE_SHIFT-10), data << (PAGE_SHIFT-10), mm->stack_vm << (PAGE_SHIFT-10), text, lib, ptes >> 10, pmds >> 10, swap << (PAGE_SHIFT-10)); } unsigned long task_vsize(struct mm_struct *mm) { return PAGE_SIZE * mm->total_vm; } unsigned long task_statm(struct mm_struct *mm, unsigned long *shared, unsigned long *text, unsigned long *data, unsigned long *resident) { *shared = get_mm_counter(mm, MM_FILEPAGES); *text = (PAGE_ALIGN(mm->end_code) - (mm->start_code & PAGE_MASK)) >> PAGE_SHIFT; *data = mm->total_vm - mm->shared_vm; *resident = *shared + get_mm_counter(mm, MM_ANONPAGES); return mm->total_vm; } #ifdef CONFIG_NUMA /* * Save get_task_policy() for show_numa_map(). */ static void hold_task_mempolicy(struct proc_maps_private *priv) { struct task_struct *task = priv->task; task_lock(task); priv->task_mempolicy = get_task_policy(task); mpol_get(priv->task_mempolicy); task_unlock(task); } static void release_task_mempolicy(struct proc_maps_private *priv) { mpol_put(priv->task_mempolicy); } #else static void hold_task_mempolicy(struct proc_maps_private *priv) { } static void release_task_mempolicy(struct proc_maps_private *priv) { } #endif static void vma_stop(struct proc_maps_private *priv) { struct mm_struct *mm = priv->mm; release_task_mempolicy(priv); up_read(&mm->mmap_sem); mmput(mm); } static struct vm_area_struct * m_next_vma(struct proc_maps_private *priv, struct vm_area_struct *vma) { if (vma == priv->tail_vma) return NULL; return vma->vm_next ?: priv->tail_vma; } static void m_cache_vma(struct seq_file *m, struct vm_area_struct *vma) { if (m->count < m->size) /* vma is copied successfully */ m->version = m_next_vma(m->private, vma) ? vma->vm_start : -1UL; } static void *m_start(struct seq_file *m, loff_t *ppos) { struct proc_maps_private *priv = m->private; unsigned long last_addr = m->version; struct mm_struct *mm; struct vm_area_struct *vma; unsigned int pos = *ppos; /* See m_cache_vma(). Zero at the start or after lseek. */ if (last_addr == -1UL) return NULL; priv->task = get_proc_task(priv->inode); if (!priv->task) return ERR_PTR(-ESRCH); mm = priv->mm; if (!mm || !atomic_inc_not_zero(&mm->mm_users)) return NULL; down_read(&mm->mmap_sem); hold_task_mempolicy(priv); priv->tail_vma = get_gate_vma(mm); if (last_addr) { vma = find_vma(mm, last_addr); if (vma && (vma = m_next_vma(priv, vma))) return vma; } m->version = 0; if (pos < mm->map_count) { for (vma = mm->mmap; pos; pos--) { m->version = vma->vm_start; vma = vma->vm_next; } return vma; } /* we do not bother to update m->version in this case */ if (pos == mm->map_count && priv->tail_vma) return priv->tail_vma; vma_stop(priv); return NULL; } static void *m_next(struct seq_file *m, void *v, loff_t *pos) { struct proc_maps_private *priv = m->private; struct vm_area_struct *next; (*pos)++; next = m_next_vma(priv, v); if (!next) vma_stop(priv); return next; } static void m_stop(struct seq_file *m, void *v) { struct proc_maps_private *priv = m->private; if (!IS_ERR_OR_NULL(v)) vma_stop(priv); if (priv->task) { put_task_struct(priv->task); priv->task = NULL; } } static int proc_maps_open(struct inode *inode, struct file *file, const struct seq_operations *ops, int psize) { struct proc_maps_private *priv = __seq_open_private(file, ops, psize); if (!priv) return -ENOMEM; priv->inode = inode; priv->mm = proc_mem_open(inode, PTRACE_MODE_READ); if (IS_ERR(priv->mm)) { int err = PTR_ERR(priv->mm); seq_release_private(inode, file); return err; } return 0; } static int proc_map_release(struct inode *inode, struct file *file) { struct seq_file *seq = file->private_data; struct proc_maps_private *priv = seq->private; if (priv->mm) mmdrop(priv->mm); return seq_release_private(inode, file); } static int do_maps_open(struct inode *inode, struct file *file, const struct seq_operations *ops) { return proc_maps_open(inode, file, ops, sizeof(struct proc_maps_private)); } static pid_t pid_of_stack(struct proc_maps_private *priv, struct vm_area_struct *vma, bool is_pid) { struct inode *inode = priv->inode; struct task_struct *task; pid_t ret = 0; rcu_read_lock(); task = pid_task(proc_pid(inode), PIDTYPE_PID); if (task) { task = task_of_stack(task, vma, is_pid); if (task) ret = task_pid_nr_ns(task, inode->i_sb->s_fs_info); } rcu_read_unlock(); return ret; } static void show_map_vma(struct seq_file *m, struct vm_area_struct *vma, int is_pid) { struct mm_struct *mm = vma->vm_mm; struct file *file = vma->vm_file; struct proc_maps_private *priv = m->private; vm_flags_t flags = vma->vm_flags; unsigned long ino = 0; unsigned long long pgoff = 0; unsigned long start, end; dev_t dev = 0; const char *name = NULL; if (file) { struct inode *inode = file_inode(vma->vm_file); dev = inode->i_sb->s_dev; ino = inode->i_ino; pgoff = ((loff_t)vma->vm_pgoff) << PAGE_SHIFT; } /* We don't show the stack guard page in /proc/maps */ start = vma->vm_start; if (stack_guard_page_start(vma, start)) start += PAGE_SIZE; end = vma->vm_end; if (stack_guard_page_end(vma, end)) end -= PAGE_SIZE; seq_setwidth(m, 25 + sizeof(void *) * 6 - 1); seq_printf(m, "%08lx-%08lx %c%c%c%c %08llx %02x:%02x %lu ", start, end, flags & VM_READ ? 'r' : '-', flags & VM_WRITE ? 'w' : '-', flags & VM_EXEC ? 'x' : '-', flags & VM_MAYSHARE ? 's' : 'p', pgoff, MAJOR(dev), MINOR(dev), ino); /* * Print the dentry name for named mappings, and a * special [heap] marker for the heap: */ if (file) { seq_pad(m, ' '); seq_path(m, &file->f_path, "\n"); goto done; } if (vma->vm_ops && vma->vm_ops->name) { name = vma->vm_ops->name(vma); if (name) goto done; } name = arch_vma_name(vma); if (!name) { pid_t tid; if (!mm) { name = "[vdso]"; goto done; } if (vma->vm_start <= mm->brk && vma->vm_end >= mm->start_brk) { name = "[heap]"; goto done; } tid = pid_of_stack(priv, vma, is_pid); if (tid != 0) { /* * Thread stack in /proc/PID/task/TID/maps or * the main process stack. */ if (!is_pid || (vma->vm_start <= mm->start_stack && vma->vm_end >= mm->start_stack)) { name = "[stack]"; } else { /* Thread stack in /proc/PID/maps */ seq_pad(m, ' '); seq_printf(m, "[stack:%d]", tid); } } } done: if (name) { seq_pad(m, ' '); seq_puts(m, name); } seq_putc(m, '\n'); } static int show_map(struct seq_file *m, void *v, int is_pid) { show_map_vma(m, v, is_pid); m_cache_vma(m, v); return 0; } static int show_pid_map(struct seq_file *m, void *v) { return show_map(m, v, 1); } static int show_tid_map(struct seq_file *m, void *v) { return show_map(m, v, 0); } static const struct seq_operations proc_pid_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_pid_map }; static const struct seq_operations proc_tid_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_tid_map }; static int pid_maps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_maps_op); } static int tid_maps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_tid_maps_op); } const struct file_operations proc_pid_maps_operations = { .open = pid_maps_open, .read = seq_read, .llseek = seq_lseek, .release = proc_map_release, }; const struct file_operations proc_tid_maps_operations = { .open = tid_maps_open, .read = seq_read, .llseek = seq_lseek, .release = proc_map_release, }; /* * Proportional Set Size(PSS): my share of RSS. * * PSS of a process is the count of pages it has in memory, where each * page is divided by the number of processes sharing it. So if a * process has 1000 pages all to itself, and 1000 shared with one other * process, its PSS will be 1500. * * To keep (accumulated) division errors low, we adopt a 64bit * fixed-point pss counter to minimize division errors. So (pss >> * PSS_SHIFT) would be the real byte count. * * A shift of 12 before division means (assuming 4K page size): * - 1M 3-user-pages add up to 8KB errors; * - supports mapcount up to 2^24, or 16M; * - supports PSS up to 2^52 bytes, or 4PB. */ #define PSS_SHIFT 12 #ifdef CONFIG_PROC_PAGE_MONITOR struct mem_size_stats { unsigned long resident; unsigned long shared_clean; unsigned long shared_dirty; unsigned long private_clean; unsigned long private_dirty; unsigned long referenced; unsigned long anonymous; unsigned long anonymous_thp; unsigned long swap; u64 pss; }; static void smaps_account(struct mem_size_stats *mss, struct page *page, unsigned long size, bool young, bool dirty) { int mapcount; if (PageAnon(page)) mss->anonymous += size; mss->resident += size; /* Accumulate the size in pages that have been accessed. */ if (young || PageReferenced(page)) mss->referenced += size; mapcount = page_mapcount(page); if (mapcount >= 2) { u64 pss_delta; if (dirty || PageDirty(page)) mss->shared_dirty += size; else mss->shared_clean += size; pss_delta = (u64)size << PSS_SHIFT; do_div(pss_delta, mapcount); mss->pss += pss_delta; } else { if (dirty || PageDirty(page)) mss->private_dirty += size; else mss->private_clean += size; mss->pss += (u64)size << PSS_SHIFT; } } static void smaps_pte_entry(pte_t *pte, unsigned long addr, struct mm_walk *walk) { struct mem_size_stats *mss = walk->private; struct vm_area_struct *vma = walk->vma; struct page *page = NULL; if (pte_present(*pte)) { page = vm_normal_page(vma, addr, *pte); } else if (is_swap_pte(*pte)) { swp_entry_t swpent = pte_to_swp_entry(*pte); if (!non_swap_entry(swpent)) mss->swap += PAGE_SIZE; else if (is_migration_entry(swpent)) page = migration_entry_to_page(swpent); } if (!page) return; smaps_account(mss, page, PAGE_SIZE, pte_young(*pte), pte_dirty(*pte)); } #ifdef CONFIG_TRANSPARENT_HUGEPAGE static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr, struct mm_walk *walk) { struct mem_size_stats *mss = walk->private; struct vm_area_struct *vma = walk->vma; struct page *page; /* FOLL_DUMP will return -EFAULT on huge zero page */ page = follow_trans_huge_pmd(vma, addr, pmd, FOLL_DUMP); if (IS_ERR_OR_NULL(page)) return; mss->anonymous_thp += HPAGE_PMD_SIZE; smaps_account(mss, page, HPAGE_PMD_SIZE, pmd_young(*pmd), pmd_dirty(*pmd)); } #else static void smaps_pmd_entry(pmd_t *pmd, unsigned long addr, struct mm_walk *walk) { } #endif static int smaps_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; pte_t *pte; spinlock_t *ptl; if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) { smaps_pmd_entry(pmd, addr, walk); spin_unlock(ptl); return 0; } if (pmd_trans_unstable(pmd)) return 0; /* * The mmap_sem held all the way back in m_start() is what * keeps khugepaged out of here and from collapsing things * in here. */ pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) smaps_pte_entry(pte, addr, walk); pte_unmap_unlock(pte - 1, ptl); cond_resched(); return 0; } static void show_smap_vma_flags(struct seq_file *m, struct vm_area_struct *vma) { /* * Don't forget to update Documentation/ on changes. */ static const char mnemonics[BITS_PER_LONG][2] = { /* * In case if we meet a flag we don't know about. */ [0 ... (BITS_PER_LONG-1)] = "??", [ilog2(VM_READ)] = "rd", [ilog2(VM_WRITE)] = "wr", [ilog2(VM_EXEC)] = "ex", [ilog2(VM_SHARED)] = "sh", [ilog2(VM_MAYREAD)] = "mr", [ilog2(VM_MAYWRITE)] = "mw", [ilog2(VM_MAYEXEC)] = "me", [ilog2(VM_MAYSHARE)] = "ms", [ilog2(VM_GROWSDOWN)] = "gd", [ilog2(VM_PFNMAP)] = "pf", [ilog2(VM_DENYWRITE)] = "dw", #ifdef CONFIG_X86_INTEL_MPX [ilog2(VM_MPX)] = "mp", #endif [ilog2(VM_LOCKED)] = "lo", [ilog2(VM_IO)] = "io", [ilog2(VM_SEQ_READ)] = "sr", [ilog2(VM_RAND_READ)] = "rr", [ilog2(VM_DONTCOPY)] = "dc", [ilog2(VM_DONTEXPAND)] = "de", [ilog2(VM_ACCOUNT)] = "ac", [ilog2(VM_NORESERVE)] = "nr", [ilog2(VM_HUGETLB)] = "ht", [ilog2(VM_ARCH_1)] = "ar", [ilog2(VM_DONTDUMP)] = "dd", #ifdef CONFIG_MEM_SOFT_DIRTY [ilog2(VM_SOFTDIRTY)] = "sd", #endif [ilog2(VM_MIXEDMAP)] = "mm", [ilog2(VM_HUGEPAGE)] = "hg", [ilog2(VM_NOHUGEPAGE)] = "nh", [ilog2(VM_MERGEABLE)] = "mg", }; size_t i; seq_puts(m, "VmFlags: "); for (i = 0; i < BITS_PER_LONG; i++) { if (vma->vm_flags & (1UL << i)) { seq_printf(m, "%c%c ", mnemonics[i][0], mnemonics[i][1]); } } seq_putc(m, '\n'); } static int show_smap(struct seq_file *m, void *v, int is_pid) { struct vm_area_struct *vma = v; struct mem_size_stats mss; struct mm_walk smaps_walk = { .pmd_entry = smaps_pte_range, .mm = vma->vm_mm, .private = &mss, }; memset(&mss, 0, sizeof mss); /* mmap_sem is held in m_start */ walk_page_vma(vma, &smaps_walk); show_map_vma(m, vma, is_pid); seq_printf(m, "Size: %8lu kB\n" "Rss: %8lu kB\n" "Pss: %8lu kB\n" "Shared_Clean: %8lu kB\n" "Shared_Dirty: %8lu kB\n" "Private_Clean: %8lu kB\n" "Private_Dirty: %8lu kB\n" "Referenced: %8lu kB\n" "Anonymous: %8lu kB\n" "AnonHugePages: %8lu kB\n" "Swap: %8lu kB\n" "KernelPageSize: %8lu kB\n" "MMUPageSize: %8lu kB\n" "Locked: %8lu kB\n", (vma->vm_end - vma->vm_start) >> 10, mss.resident >> 10, (unsigned long)(mss.pss >> (10 + PSS_SHIFT)), mss.shared_clean >> 10, mss.shared_dirty >> 10, mss.private_clean >> 10, mss.private_dirty >> 10, mss.referenced >> 10, mss.anonymous >> 10, mss.anonymous_thp >> 10, mss.swap >> 10, vma_kernel_pagesize(vma) >> 10, vma_mmu_pagesize(vma) >> 10, (vma->vm_flags & VM_LOCKED) ? (unsigned long)(mss.pss >> (10 + PSS_SHIFT)) : 0); show_smap_vma_flags(m, vma); m_cache_vma(m, vma); return 0; } static int show_pid_smap(struct seq_file *m, void *v) { return show_smap(m, v, 1); } static int show_tid_smap(struct seq_file *m, void *v) { return show_smap(m, v, 0); } static const struct seq_operations proc_pid_smaps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_pid_smap }; static const struct seq_operations proc_tid_smaps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_tid_smap }; static int pid_smaps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_pid_smaps_op); } static int tid_smaps_open(struct inode *inode, struct file *file) { return do_maps_open(inode, file, &proc_tid_smaps_op); } const struct file_operations proc_pid_smaps_operations = { .open = pid_smaps_open, .read = seq_read, .llseek = seq_lseek, .release = proc_map_release, }; const struct file_operations proc_tid_smaps_operations = { .open = tid_smaps_open, .read = seq_read, .llseek = seq_lseek, .release = proc_map_release, }; /* * We do not want to have constant page-shift bits sitting in * pagemap entries and are about to reuse them some time soon. * * Here's the "migration strategy": * 1. when the system boots these bits remain what they are, * but a warning about future change is printed in log; * 2. once anyone clears soft-dirty bits via clear_refs file, * these flag is set to denote, that user is aware of the * new API and those page-shift bits change their meaning. * The respective warning is printed in dmesg; * 3. In a couple of releases we will remove all the mentions * of page-shift in pagemap entries. */ static bool soft_dirty_cleared __read_mostly; enum clear_refs_types { CLEAR_REFS_ALL = 1, CLEAR_REFS_ANON, CLEAR_REFS_MAPPED, CLEAR_REFS_SOFT_DIRTY, CLEAR_REFS_MM_HIWATER_RSS, CLEAR_REFS_LAST, }; struct clear_refs_private { enum clear_refs_types type; }; #ifdef CONFIG_MEM_SOFT_DIRTY static inline void clear_soft_dirty(struct vm_area_struct *vma, unsigned long addr, pte_t *pte) { /* * The soft-dirty tracker uses #PF-s to catch writes * to pages, so write-protect the pte as well. See the * Documentation/vm/soft-dirty.txt for full description * of how soft-dirty works. */ pte_t ptent = *pte; if (pte_present(ptent)) { ptent = pte_wrprotect(ptent); ptent = pte_clear_flags(ptent, _PAGE_SOFT_DIRTY); } else if (is_swap_pte(ptent)) { ptent = pte_swp_clear_soft_dirty(ptent); } set_pte_at(vma->vm_mm, addr, pte, ptent); } static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma, unsigned long addr, pmd_t *pmdp) { pmd_t pmd = *pmdp; pmd = pmd_wrprotect(pmd); pmd = pmd_clear_flags(pmd, _PAGE_SOFT_DIRTY); if (vma->vm_flags & VM_SOFTDIRTY) vma->vm_flags &= ~VM_SOFTDIRTY; set_pmd_at(vma->vm_mm, addr, pmdp, pmd); } #else static inline void clear_soft_dirty(struct vm_area_struct *vma, unsigned long addr, pte_t *pte) { } static inline void clear_soft_dirty_pmd(struct vm_area_struct *vma, unsigned long addr, pmd_t *pmdp) { } #endif static int clear_refs_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct clear_refs_private *cp = walk->private; struct vm_area_struct *vma = walk->vma; pte_t *pte, ptent; spinlock_t *ptl; struct page *page; if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) { if (cp->type == CLEAR_REFS_SOFT_DIRTY) { clear_soft_dirty_pmd(vma, addr, pmd); goto out; } page = pmd_page(*pmd); /* Clear accessed and referenced bits. */ pmdp_test_and_clear_young(vma, addr, pmd); ClearPageReferenced(page); out: spin_unlock(ptl); return 0; } if (pmd_trans_unstable(pmd)) return 0; pte = pte_offset_map_lock(vma->vm_mm, pmd, addr, &ptl); for (; addr != end; pte++, addr += PAGE_SIZE) { ptent = *pte; if (cp->type == CLEAR_REFS_SOFT_DIRTY) { clear_soft_dirty(vma, addr, pte); continue; } if (!pte_present(ptent)) continue; page = vm_normal_page(vma, addr, ptent); if (!page) continue; /* Clear accessed and referenced bits. */ ptep_test_and_clear_young(vma, addr, pte); ClearPageReferenced(page); } pte_unmap_unlock(pte - 1, ptl); cond_resched(); return 0; } static int clear_refs_test_walk(unsigned long start, unsigned long end, struct mm_walk *walk) { struct clear_refs_private *cp = walk->private; struct vm_area_struct *vma = walk->vma; if (vma->vm_flags & VM_PFNMAP) return 1; /* * Writing 1 to /proc/pid/clear_refs affects all pages. * Writing 2 to /proc/pid/clear_refs only affects anonymous pages. * Writing 3 to /proc/pid/clear_refs only affects file mapped pages. * Writing 4 to /proc/pid/clear_refs affects all pages. */ if (cp->type == CLEAR_REFS_ANON && vma->vm_file) return 1; if (cp->type == CLEAR_REFS_MAPPED && !vma->vm_file) return 1; return 0; } static ssize_t clear_refs_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task; char buffer[PROC_NUMBUF]; struct mm_struct *mm; struct vm_area_struct *vma; enum clear_refs_types type; int itype; int rv; memset(buffer, 0, sizeof(buffer)); if (count > sizeof(buffer) - 1) count = sizeof(buffer) - 1; if (copy_from_user(buffer, buf, count)) return -EFAULT; rv = kstrtoint(strstrip(buffer), 10, &itype); if (rv < 0) return rv; type = (enum clear_refs_types)itype; if (type < CLEAR_REFS_ALL || type >= CLEAR_REFS_LAST) return -EINVAL; if (type == CLEAR_REFS_SOFT_DIRTY) { soft_dirty_cleared = true; pr_warn_once("The pagemap bits 55-60 has changed their meaning!" " See the linux/Documentation/vm/pagemap.txt for " "details.\n"); } task = get_proc_task(file_inode(file)); if (!task) return -ESRCH; mm = get_task_mm(task); if (mm) { struct clear_refs_private cp = { .type = type, }; struct mm_walk clear_refs_walk = { .pmd_entry = clear_refs_pte_range, .test_walk = clear_refs_test_walk, .mm = mm, .private = &cp, }; if (type == CLEAR_REFS_MM_HIWATER_RSS) { /* * Writing 5 to /proc/pid/clear_refs resets the peak * resident set size to this mm's current rss value. */ down_write(&mm->mmap_sem); reset_mm_hiwater_rss(mm); up_write(&mm->mmap_sem); goto out_mm; } down_read(&mm->mmap_sem); if (type == CLEAR_REFS_SOFT_DIRTY) { for (vma = mm->mmap; vma; vma = vma->vm_next) { if (!(vma->vm_flags & VM_SOFTDIRTY)) continue; up_read(&mm->mmap_sem); down_write(&mm->mmap_sem); for (vma = mm->mmap; vma; vma = vma->vm_next) { vma->vm_flags &= ~VM_SOFTDIRTY; vma_set_page_prot(vma); } downgrade_write(&mm->mmap_sem); break; } mmu_notifier_invalidate_range_start(mm, 0, -1); } walk_page_range(0, ~0UL, &clear_refs_walk); if (type == CLEAR_REFS_SOFT_DIRTY) mmu_notifier_invalidate_range_end(mm, 0, -1); flush_tlb_mm(mm); up_read(&mm->mmap_sem); out_mm: mmput(mm); } put_task_struct(task); return count; } const struct file_operations proc_clear_refs_operations = { .write = clear_refs_write, .llseek = noop_llseek, }; typedef struct { u64 pme; } pagemap_entry_t; struct pagemapread { int pos, len; /* units: PM_ENTRY_BYTES, not bytes */ pagemap_entry_t *buffer; bool v2; }; #define PAGEMAP_WALK_SIZE (PMD_SIZE) #define PAGEMAP_WALK_MASK (PMD_MASK) #define PM_ENTRY_BYTES sizeof(pagemap_entry_t) #define PM_STATUS_BITS 3 #define PM_STATUS_OFFSET (64 - PM_STATUS_BITS) #define PM_STATUS_MASK (((1LL << PM_STATUS_BITS) - 1) << PM_STATUS_OFFSET) #define PM_STATUS(nr) (((nr) << PM_STATUS_OFFSET) & PM_STATUS_MASK) #define PM_PSHIFT_BITS 6 #define PM_PSHIFT_OFFSET (PM_STATUS_OFFSET - PM_PSHIFT_BITS) #define PM_PSHIFT_MASK (((1LL << PM_PSHIFT_BITS) - 1) << PM_PSHIFT_OFFSET) #define __PM_PSHIFT(x) (((u64) (x) << PM_PSHIFT_OFFSET) & PM_PSHIFT_MASK) #define PM_PFRAME_MASK ((1LL << PM_PSHIFT_OFFSET) - 1) #define PM_PFRAME(x) ((x) & PM_PFRAME_MASK) /* in "new" pagemap pshift bits are occupied with more status bits */ #define PM_STATUS2(v2, x) (__PM_PSHIFT(v2 ? x : PAGE_SHIFT)) #define __PM_SOFT_DIRTY (1LL) #define PM_PRESENT PM_STATUS(4LL) #define PM_SWAP PM_STATUS(2LL) #define PM_FILE PM_STATUS(1LL) #define PM_NOT_PRESENT(v2) PM_STATUS2(v2, 0) #define PM_END_OF_BUFFER 1 static inline pagemap_entry_t make_pme(u64 val) { return (pagemap_entry_t) { .pme = val }; } static int add_to_pagemap(unsigned long addr, pagemap_entry_t *pme, struct pagemapread *pm) { pm->buffer[pm->pos++] = *pme; if (pm->pos >= pm->len) return PM_END_OF_BUFFER; return 0; } static int pagemap_pte_hole(unsigned long start, unsigned long end, struct mm_walk *walk) { struct pagemapread *pm = walk->private; unsigned long addr = start; int err = 0; while (addr < end) { struct vm_area_struct *vma = find_vma(walk->mm, addr); pagemap_entry_t pme = make_pme(PM_NOT_PRESENT(pm->v2)); /* End of address space hole, which we mark as non-present. */ unsigned long hole_end; if (vma) hole_end = min(end, vma->vm_start); else hole_end = end; for (; addr < hole_end; addr += PAGE_SIZE) { err = add_to_pagemap(addr, &pme, pm); if (err) goto out; } if (!vma) break; /* Addresses in the VMA. */ if (vma->vm_flags & VM_SOFTDIRTY) pme.pme |= PM_STATUS2(pm->v2, __PM_SOFT_DIRTY); for (; addr < min(end, vma->vm_end); addr += PAGE_SIZE) { err = add_to_pagemap(addr, &pme, pm); if (err) goto out; } } out: return err; } static void pte_to_pagemap_entry(pagemap_entry_t *pme, struct pagemapread *pm, struct vm_area_struct *vma, unsigned long addr, pte_t pte) { u64 frame, flags; struct page *page = NULL; int flags2 = 0; if (pte_present(pte)) { frame = pte_pfn(pte); flags = PM_PRESENT; page = vm_normal_page(vma, addr, pte); if (pte_soft_dirty(pte)) flags2 |= __PM_SOFT_DIRTY; } else if (is_swap_pte(pte)) { swp_entry_t entry; if (pte_swp_soft_dirty(pte)) flags2 |= __PM_SOFT_DIRTY; entry = pte_to_swp_entry(pte); frame = swp_type(entry) | (swp_offset(entry) << MAX_SWAPFILES_SHIFT); flags = PM_SWAP; if (is_migration_entry(entry)) page = migration_entry_to_page(entry); } else { if (vma->vm_flags & VM_SOFTDIRTY) flags2 |= __PM_SOFT_DIRTY; *pme = make_pme(PM_NOT_PRESENT(pm->v2) | PM_STATUS2(pm->v2, flags2)); return; } if (page && !PageAnon(page)) flags |= PM_FILE; if ((vma->vm_flags & VM_SOFTDIRTY)) flags2 |= __PM_SOFT_DIRTY; *pme = make_pme(PM_PFRAME(frame) | PM_STATUS2(pm->v2, flags2) | flags); } #ifdef CONFIG_TRANSPARENT_HUGEPAGE static void thp_pmd_to_pagemap_entry(pagemap_entry_t *pme, struct pagemapread *pm, pmd_t pmd, int offset, int pmd_flags2) { /* * Currently pmd for thp is always present because thp can not be * swapped-out, migrated, or HWPOISONed (split in such cases instead.) * This if-check is just to prepare for future implementation. */ if (pmd_present(pmd)) *pme = make_pme(PM_PFRAME(pmd_pfn(pmd) + offset) | PM_STATUS2(pm->v2, pmd_flags2) | PM_PRESENT); else *pme = make_pme(PM_NOT_PRESENT(pm->v2) | PM_STATUS2(pm->v2, pmd_flags2)); } #else static inline void thp_pmd_to_pagemap_entry(pagemap_entry_t *pme, struct pagemapread *pm, pmd_t pmd, int offset, int pmd_flags2) { } #endif static int pagemap_pte_range(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct vm_area_struct *vma = walk->vma; struct pagemapread *pm = walk->private; spinlock_t *ptl; pte_t *pte, *orig_pte; int err = 0; if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) { int pmd_flags2; if ((vma->vm_flags & VM_SOFTDIRTY) || pmd_soft_dirty(*pmd)) pmd_flags2 = __PM_SOFT_DIRTY; else pmd_flags2 = 0; for (; addr != end; addr += PAGE_SIZE) { unsigned long offset; pagemap_entry_t pme; offset = (addr & ~PAGEMAP_WALK_MASK) >> PAGE_SHIFT; thp_pmd_to_pagemap_entry(&pme, pm, *pmd, offset, pmd_flags2); err = add_to_pagemap(addr, &pme, pm); if (err) break; } spin_unlock(ptl); return err; } if (pmd_trans_unstable(pmd)) return 0; /* * We can assume that @vma always points to a valid one and @end never * goes beyond vma->vm_end. */ orig_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); for (; addr < end; pte++, addr += PAGE_SIZE) { pagemap_entry_t pme; pte_to_pagemap_entry(&pme, pm, vma, addr, *pte); err = add_to_pagemap(addr, &pme, pm); if (err) break; } pte_unmap_unlock(orig_pte, ptl); cond_resched(); return err; } #ifdef CONFIG_HUGETLB_PAGE static void huge_pte_to_pagemap_entry(pagemap_entry_t *pme, struct pagemapread *pm, pte_t pte, int offset, int flags2) { if (pte_present(pte)) *pme = make_pme(PM_PFRAME(pte_pfn(pte) + offset) | PM_STATUS2(pm->v2, flags2) | PM_PRESENT); else *pme = make_pme(PM_NOT_PRESENT(pm->v2) | PM_STATUS2(pm->v2, flags2)); } /* This function walks within one hugetlb entry in the single call */ static int pagemap_hugetlb_range(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct pagemapread *pm = walk->private; struct vm_area_struct *vma = walk->vma; int err = 0; int flags2; pagemap_entry_t pme; if (vma->vm_flags & VM_SOFTDIRTY) flags2 = __PM_SOFT_DIRTY; else flags2 = 0; for (; addr != end; addr += PAGE_SIZE) { int offset = (addr & ~hmask) >> PAGE_SHIFT; huge_pte_to_pagemap_entry(&pme, pm, *pte, offset, flags2); err = add_to_pagemap(addr, &pme, pm); if (err) return err; } cond_resched(); return err; } #endif /* HUGETLB_PAGE */ /* * /proc/pid/pagemap - an array mapping virtual pages to pfns * * For each page in the address space, this file contains one 64-bit entry * consisting of the following: * * Bits 0-54 page frame number (PFN) if present * Bits 0-4 swap type if swapped * Bits 5-54 swap offset if swapped * Bits 55-60 page shift (page size = 1<<page shift) * Bit 61 page is file-page or shared-anon * Bit 62 page swapped * Bit 63 page present * * If the page is not present but in swap, then the PFN contains an * encoding of the swap file number and the page's offset into the * swap. Unmapped pages return a null PFN. This allows determining * precisely which pages are mapped (or in swap) and comparing mapped * pages between processes. * * Efficient users of this interface will use /proc/pid/maps to * determine which areas of memory are actually mapped and llseek to * skip over unmapped regions. */ static ssize_t pagemap_read(struct file *file, char __user *buf, size_t count, loff_t *ppos) { struct task_struct *task = get_proc_task(file_inode(file)); struct mm_struct *mm; struct pagemapread pm; int ret = -ESRCH; struct mm_walk pagemap_walk = {}; unsigned long src; unsigned long svpfn; unsigned long start_vaddr; unsigned long end_vaddr; int copied = 0; if (!task) goto out; ret = -EINVAL; /* file position must be aligned */ if ((*ppos % PM_ENTRY_BYTES) || (count % PM_ENTRY_BYTES)) goto out_task; ret = 0; if (!count) goto out_task; pm.v2 = soft_dirty_cleared; pm.len = (PAGEMAP_WALK_SIZE >> PAGE_SHIFT); pm.buffer = kmalloc(pm.len * PM_ENTRY_BYTES, GFP_TEMPORARY); ret = -ENOMEM; if (!pm.buffer) goto out_task; mm = mm_access(task, PTRACE_MODE_READ); ret = PTR_ERR(mm); if (!mm || IS_ERR(mm)) goto out_free; pagemap_walk.pmd_entry = pagemap_pte_range; pagemap_walk.pte_hole = pagemap_pte_hole; #ifdef CONFIG_HUGETLB_PAGE pagemap_walk.hugetlb_entry = pagemap_hugetlb_range; #endif pagemap_walk.mm = mm; pagemap_walk.private = &pm; src = *ppos; svpfn = src / PM_ENTRY_BYTES; start_vaddr = svpfn << PAGE_SHIFT; end_vaddr = TASK_SIZE_OF(task); /* watch out for wraparound */ if (svpfn > TASK_SIZE_OF(task) >> PAGE_SHIFT) start_vaddr = end_vaddr; /* * The odds are that this will stop walking way * before end_vaddr, because the length of the * user buffer is tracked in "pm", and the walk * will stop when we hit the end of the buffer. */ ret = 0; while (count && (start_vaddr < end_vaddr)) { int len; unsigned long end; pm.pos = 0; end = (start_vaddr + PAGEMAP_WALK_SIZE) & PAGEMAP_WALK_MASK; /* overflow ? */ if (end < start_vaddr || end > end_vaddr) end = end_vaddr; down_read(&mm->mmap_sem); ret = walk_page_range(start_vaddr, end, &pagemap_walk); up_read(&mm->mmap_sem); start_vaddr = end; len = min(count, PM_ENTRY_BYTES * pm.pos); if (copy_to_user(buf, pm.buffer, len)) { ret = -EFAULT; goto out_mm; } copied += len; buf += len; count -= len; } *ppos += copied; if (!ret || ret == PM_END_OF_BUFFER) ret = copied; out_mm: mmput(mm); out_free: kfree(pm.buffer); out_task: put_task_struct(task); out: return ret; } static int pagemap_open(struct inode *inode, struct file *file) { pr_warn_once("Bits 55-60 of /proc/PID/pagemap entries are about " "to stop being page-shift some time soon. See the " "linux/Documentation/vm/pagemap.txt for details.\n"); return 0; } const struct file_operations proc_pagemap_operations = { .llseek = mem_lseek, /* borrow this */ .read = pagemap_read, .open = pagemap_open, }; #endif /* CONFIG_PROC_PAGE_MONITOR */ #ifdef CONFIG_NUMA struct numa_maps { unsigned long pages; unsigned long anon; unsigned long active; unsigned long writeback; unsigned long mapcount_max; unsigned long dirty; unsigned long swapcache; unsigned long node[MAX_NUMNODES]; }; struct numa_maps_private { struct proc_maps_private proc_maps; struct numa_maps md; }; static void gather_stats(struct page *page, struct numa_maps *md, int pte_dirty, unsigned long nr_pages) { int count = page_mapcount(page); md->pages += nr_pages; if (pte_dirty || PageDirty(page)) md->dirty += nr_pages; if (PageSwapCache(page)) md->swapcache += nr_pages; if (PageActive(page) || PageUnevictable(page)) md->active += nr_pages; if (PageWriteback(page)) md->writeback += nr_pages; if (PageAnon(page)) md->anon += nr_pages; if (count > md->mapcount_max) md->mapcount_max = count; md->node[page_to_nid(page)] += nr_pages; } static struct page *can_gather_numa_stats(pte_t pte, struct vm_area_struct *vma, unsigned long addr) { struct page *page; int nid; if (!pte_present(pte)) return NULL; page = vm_normal_page(vma, addr, pte); if (!page) return NULL; if (PageReserved(page)) return NULL; nid = page_to_nid(page); if (!node_isset(nid, node_states[N_MEMORY])) return NULL; return page; } static int gather_pte_stats(pmd_t *pmd, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct numa_maps *md = walk->private; struct vm_area_struct *vma = walk->vma; spinlock_t *ptl; pte_t *orig_pte; pte_t *pte; if (pmd_trans_huge_lock(pmd, vma, &ptl) == 1) { pte_t huge_pte = *(pte_t *)pmd; struct page *page; page = can_gather_numa_stats(huge_pte, vma, addr); if (page) gather_stats(page, md, pte_dirty(huge_pte), HPAGE_PMD_SIZE/PAGE_SIZE); spin_unlock(ptl); return 0; } if (pmd_trans_unstable(pmd)) return 0; orig_pte = pte = pte_offset_map_lock(walk->mm, pmd, addr, &ptl); do { struct page *page = can_gather_numa_stats(*pte, vma, addr); if (!page) continue; gather_stats(page, md, pte_dirty(*pte), 1); } while (pte++, addr += PAGE_SIZE, addr != end); pte_unmap_unlock(orig_pte, ptl); return 0; } #ifdef CONFIG_HUGETLB_PAGE static int gather_hugetlb_stats(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { struct numa_maps *md; struct page *page; if (!pte_present(*pte)) return 0; page = pte_page(*pte); if (!page) return 0; md = walk->private; gather_stats(page, md, pte_dirty(*pte), 1); return 0; } #else static int gather_hugetlb_stats(pte_t *pte, unsigned long hmask, unsigned long addr, unsigned long end, struct mm_walk *walk) { return 0; } #endif /* * Display pages allocated per node and memory policy via /proc. */ static int show_numa_map(struct seq_file *m, void *v, int is_pid) { struct numa_maps_private *numa_priv = m->private; struct proc_maps_private *proc_priv = &numa_priv->proc_maps; struct vm_area_struct *vma = v; struct numa_maps *md = &numa_priv->md; struct file *file = vma->vm_file; struct mm_struct *mm = vma->vm_mm; struct mm_walk walk = { .hugetlb_entry = gather_hugetlb_stats, .pmd_entry = gather_pte_stats, .private = md, .mm = mm, }; struct mempolicy *pol; char buffer[64]; int nid; if (!mm) return 0; /* Ensure we start with an empty set of numa_maps statistics. */ memset(md, 0, sizeof(*md)); pol = __get_vma_policy(vma, vma->vm_start); if (pol) { mpol_to_str(buffer, sizeof(buffer), pol); mpol_cond_put(pol); } else { mpol_to_str(buffer, sizeof(buffer), proc_priv->task_mempolicy); } seq_printf(m, "%08lx %s", vma->vm_start, buffer); if (file) { seq_puts(m, " file="); seq_path(m, &file->f_path, "\n\t= "); } else if (vma->vm_start <= mm->brk && vma->vm_end >= mm->start_brk) { seq_puts(m, " heap"); } else { pid_t tid = pid_of_stack(proc_priv, vma, is_pid); if (tid != 0) { /* * Thread stack in /proc/PID/task/TID/maps or * the main process stack. */ if (!is_pid || (vma->vm_start <= mm->start_stack && vma->vm_end >= mm->start_stack)) seq_puts(m, " stack"); else seq_printf(m, " stack:%d", tid); } } if (is_vm_hugetlb_page(vma)) seq_puts(m, " huge"); /* mmap_sem is held by m_start */ walk_page_vma(vma, &walk); if (!md->pages) goto out; if (md->anon) seq_printf(m, " anon=%lu", md->anon); if (md->dirty) seq_printf(m, " dirty=%lu", md->dirty); if (md->pages != md->anon && md->pages != md->dirty) seq_printf(m, " mapped=%lu", md->pages); if (md->mapcount_max > 1) seq_printf(m, " mapmax=%lu", md->mapcount_max); if (md->swapcache) seq_printf(m, " swapcache=%lu", md->swapcache); if (md->active < md->pages && !is_vm_hugetlb_page(vma)) seq_printf(m, " active=%lu", md->active); if (md->writeback) seq_printf(m, " writeback=%lu", md->writeback); for_each_node_state(nid, N_MEMORY) if (md->node[nid]) seq_printf(m, " N%d=%lu", nid, md->node[nid]); seq_printf(m, " kernelpagesize_kB=%lu", vma_kernel_pagesize(vma) >> 10); out: seq_putc(m, '\n'); m_cache_vma(m, vma); return 0; } static int show_pid_numa_map(struct seq_file *m, void *v) { return show_numa_map(m, v, 1); } static int show_tid_numa_map(struct seq_file *m, void *v) { return show_numa_map(m, v, 0); } static const struct seq_operations proc_pid_numa_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_pid_numa_map, }; static const struct seq_operations proc_tid_numa_maps_op = { .start = m_start, .next = m_next, .stop = m_stop, .show = show_tid_numa_map, }; static int numa_maps_open(struct inode *inode, struct file *file, const struct seq_operations *ops) { return proc_maps_open(inode, file, ops, sizeof(struct numa_maps_private)); } static int pid_numa_maps_open(struct inode *inode, struct file *file) { return numa_maps_open(inode, file, &proc_pid_numa_maps_op); } static int tid_numa_maps_open(struct inode *inode, struct file *file) { return numa_maps_open(inode, file, &proc_tid_numa_maps_op); } const struct file_operations proc_pid_numa_maps_operations = { .open = pid_numa_maps_open, .read = seq_read, .llseek = seq_lseek, .release = proc_map_release, }; const struct file_operations proc_tid_numa_maps_operations = { .open = tid_numa_maps_open, .read = seq_read, .llseek = seq_lseek, .release = proc_map_release, }; #endif /* CONFIG_NUMA */
./CrossVul/dataset_final_sorted/CWE-200/c/bad_4747_0
crossvul-cpp_data_bad_3835_0
/* RFCOMM implementation for Linux Bluetooth stack (BlueZ). Copyright (C) 2002 Maxim Krasnyansky <maxk@qualcomm.com> Copyright (C) 2002 Marcel Holtmann <marcel@holtmann.org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* * RFCOMM sockets. */ #include <linux/export.h> #include <linux/debugfs.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include <net/bluetooth/rfcomm.h> static const struct proto_ops rfcomm_sock_ops; static struct bt_sock_list rfcomm_sk_list = { .lock = __RW_LOCK_UNLOCKED(rfcomm_sk_list.lock) }; static void rfcomm_sock_close(struct sock *sk); static void rfcomm_sock_kill(struct sock *sk); /* ---- DLC callbacks ---- * * called under rfcomm_dlc_lock() */ static void rfcomm_sk_data_ready(struct rfcomm_dlc *d, struct sk_buff *skb) { struct sock *sk = d->owner; if (!sk) return; atomic_add(skb->len, &sk->sk_rmem_alloc); skb_queue_tail(&sk->sk_receive_queue, skb); sk->sk_data_ready(sk, skb->len); if (atomic_read(&sk->sk_rmem_alloc) >= sk->sk_rcvbuf) rfcomm_dlc_throttle(d); } static void rfcomm_sk_state_change(struct rfcomm_dlc *d, int err) { struct sock *sk = d->owner, *parent; unsigned long flags; if (!sk) return; BT_DBG("dlc %p state %ld err %d", d, d->state, err); local_irq_save(flags); bh_lock_sock(sk); if (err) sk->sk_err = err; sk->sk_state = d->state; parent = bt_sk(sk)->parent; if (parent) { if (d->state == BT_CLOSED) { sock_set_flag(sk, SOCK_ZAPPED); bt_accept_unlink(sk); } parent->sk_data_ready(parent, 0); } else { if (d->state == BT_CONNECTED) rfcomm_session_getaddr(d->session, &bt_sk(sk)->src, NULL); sk->sk_state_change(sk); } bh_unlock_sock(sk); local_irq_restore(flags); if (parent && sock_flag(sk, SOCK_ZAPPED)) { /* We have to drop DLC lock here, otherwise * rfcomm_sock_destruct() will dead lock. */ rfcomm_dlc_unlock(d); rfcomm_sock_kill(sk); rfcomm_dlc_lock(d); } } /* ---- Socket functions ---- */ static struct sock *__rfcomm_get_sock_by_addr(u8 channel, bdaddr_t *src) { struct sock *sk = NULL; struct hlist_node *node; sk_for_each(sk, node, &rfcomm_sk_list.head) { if (rfcomm_pi(sk)->channel == channel && !bacmp(&bt_sk(sk)->src, src)) break; } return node ? sk : NULL; } /* Find socket with channel and source bdaddr. * Returns closest match. */ static struct sock *rfcomm_get_sock_by_channel(int state, u8 channel, bdaddr_t *src) { struct sock *sk = NULL, *sk1 = NULL; struct hlist_node *node; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, node, &rfcomm_sk_list.head) { if (state && sk->sk_state != state) continue; if (rfcomm_pi(sk)->channel == channel) { /* Exact match. */ if (!bacmp(&bt_sk(sk)->src, src)) break; /* Closest match */ if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY)) sk1 = sk; } } read_unlock(&rfcomm_sk_list.lock); return node ? sk : sk1; } static void rfcomm_sock_destruct(struct sock *sk) { struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; BT_DBG("sk %p dlc %p", sk, d); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); rfcomm_dlc_lock(d); rfcomm_pi(sk)->dlc = NULL; /* Detach DLC if it's owned by this socket */ if (d->owner == sk) d->owner = NULL; rfcomm_dlc_unlock(d); rfcomm_dlc_put(d); } static void rfcomm_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted dlcs */ while ((sk = bt_accept_dequeue(parent, NULL))) { rfcomm_sock_close(sk); rfcomm_sock_kill(sk); } parent->sk_state = BT_CLOSED; sock_set_flag(parent, SOCK_ZAPPED); } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void rfcomm_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %d refcnt %d", sk, sk->sk_state, atomic_read(&sk->sk_refcnt)); /* Kill poor orphan */ bt_sock_unlink(&rfcomm_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static void __rfcomm_sock_close(struct sock *sk) { struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket); switch (sk->sk_state) { case BT_LISTEN: rfcomm_sock_cleanup_listen(sk); break; case BT_CONNECT: case BT_CONNECT2: case BT_CONFIG: case BT_CONNECTED: rfcomm_dlc_close(d, 0); default: sock_set_flag(sk, SOCK_ZAPPED); break; } } /* Close socket. * Must be called on unlocked socket. */ static void rfcomm_sock_close(struct sock *sk) { lock_sock(sk); __rfcomm_sock_close(sk); release_sock(sk); } static void rfcomm_sock_init(struct sock *sk, struct sock *parent) { struct rfcomm_pinfo *pi = rfcomm_pi(sk); BT_DBG("sk %p", sk); if (parent) { sk->sk_type = parent->sk_type; pi->dlc->defer_setup = test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags); pi->sec_level = rfcomm_pi(parent)->sec_level; pi->role_switch = rfcomm_pi(parent)->role_switch; security_sk_clone(parent, sk); } else { pi->dlc->defer_setup = 0; pi->sec_level = BT_SECURITY_LOW; pi->role_switch = 0; } pi->dlc->sec_level = pi->sec_level; pi->dlc->role_switch = pi->role_switch; } static struct proto rfcomm_proto = { .name = "RFCOMM", .owner = THIS_MODULE, .obj_size = sizeof(struct rfcomm_pinfo) }; static struct sock *rfcomm_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio) { struct rfcomm_dlc *d; struct sock *sk; sk = sk_alloc(net, PF_BLUETOOTH, prio, &rfcomm_proto); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); d = rfcomm_dlc_alloc(prio); if (!d) { sk_free(sk); return NULL; } d->data_ready = rfcomm_sk_data_ready; d->state_change = rfcomm_sk_state_change; rfcomm_pi(sk)->dlc = d; d->owner = sk; sk->sk_destruct = rfcomm_sock_destruct; sk->sk_sndtimeo = RFCOMM_CONN_TIMEOUT; sk->sk_sndbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10; sk->sk_rcvbuf = RFCOMM_MAX_CREDITS * RFCOMM_DEFAULT_MTU * 10; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; bt_sock_link(&rfcomm_sk_list, sk); BT_DBG("sk %p", sk); return sk; } static int rfcomm_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_STREAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sock->ops = &rfcomm_sock_ops; sk = rfcomm_sock_alloc(net, sock, protocol, GFP_ATOMIC); if (!sk) return -ENOMEM; rfcomm_sock_init(sk, NULL); return 0; } static int rfcomm_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p %s", sk, batostr(&sa->rc_bdaddr)); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } write_lock(&rfcomm_sk_list.lock); if (sa->rc_channel && __rfcomm_get_sock_by_addr(sa->rc_channel, &sa->rc_bdaddr)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&bt_sk(sk)->src, &sa->rc_bdaddr); rfcomm_pi(sk)->channel = sa->rc_channel; sk->sk_state = BT_BOUND; } write_unlock(&rfcomm_sk_list.lock); done: release_sock(sk); return err; } static int rfcomm_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; int err = 0; BT_DBG("sk %p", sk); if (alen < sizeof(struct sockaddr_rc) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } sk->sk_state = BT_CONNECT; bacpy(&bt_sk(sk)->dst, &sa->rc_bdaddr); rfcomm_pi(sk)->channel = sa->rc_channel; d->sec_level = rfcomm_pi(sk)->sec_level; d->role_switch = rfcomm_pi(sk)->role_switch; err = rfcomm_dlc_open(d, &bt_sk(sk)->src, &sa->rc_bdaddr, sa->rc_channel); if (!err) err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } static int rfcomm_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } if (!rfcomm_pi(sk)->channel) { bdaddr_t *src = &bt_sk(sk)->src; u8 channel; err = -EINVAL; write_lock(&rfcomm_sk_list.lock); for (channel = 1; channel < 31; channel++) if (!__rfcomm_get_sock_by_addr(channel, src)) { rfcomm_pi(sk)->channel = channel; err = 0; break; } write_unlock(&rfcomm_sk_list.lock); if (err < 0) goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; } static int rfcomm_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock(sk); if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } nsk = bt_accept_dequeue(sk, newsock); if (nsk) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", nsk); done: release_sock(sk); return err; } static int rfcomm_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_rc *sa = (struct sockaddr_rc *) addr; struct sock *sk = sock->sk; BT_DBG("sock %p, sk %p", sock, sk); sa->rc_family = AF_BLUETOOTH; sa->rc_channel = rfcomm_pi(sk)->channel; if (peer) bacpy(&sa->rc_bdaddr, &bt_sk(sk)->dst); else bacpy(&sa->rc_bdaddr, &bt_sk(sk)->src); *len = sizeof(struct sockaddr_rc); return 0; } static int rfcomm_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; struct sk_buff *skb; int sent = 0; if (test_bit(RFCOMM_DEFER_SETUP, &d->flags)) return -ENOTCONN; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; if (sk->sk_shutdown & SEND_SHUTDOWN) return -EPIPE; BT_DBG("sock %p, sk %p", sock, sk); lock_sock(sk); while (len) { size_t size = min_t(size_t, len, d->mtu); int err; skb = sock_alloc_send_skb(sk, size + RFCOMM_SKB_RESERVE, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) { if (sent == 0) sent = err; break; } skb_reserve(skb, RFCOMM_SKB_HEAD_RESERVE); err = memcpy_fromiovec(skb_put(skb, size), msg->msg_iov, size); if (err) { kfree_skb(skb); if (sent == 0) sent = err; break; } skb->priority = sk->sk_priority; err = rfcomm_dlc_send(d, skb); if (err < 0) { kfree_skb(skb); if (sent == 0) sent = err; break; } sent += size; len -= size; } release_sock(sk); return sent; } static int rfcomm_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct rfcomm_dlc *d = rfcomm_pi(sk)->dlc; int len; if (test_and_clear_bit(RFCOMM_DEFER_SETUP, &d->flags)) { rfcomm_dlc_accept(d); return 0; } len = bt_sock_stream_recvmsg(iocb, sock, msg, size, flags); lock_sock(sk); if (!(flags & MSG_PEEK) && len > 0) atomic_sub(len, &sk->sk_rmem_alloc); if (atomic_read(&sk->sk_rmem_alloc) <= (sk->sk_rcvbuf >> 2)) rfcomm_dlc_unthrottle(rfcomm_pi(sk)->dlc); release_sock(sk); return len; } static int rfcomm_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case RFCOMM_LM: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt & RFCOMM_LM_AUTH) rfcomm_pi(sk)->sec_level = BT_SECURITY_LOW; if (opt & RFCOMM_LM_ENCRYPT) rfcomm_pi(sk)->sec_level = BT_SECURITY_MEDIUM; if (opt & RFCOMM_LM_SECURE) rfcomm_pi(sk)->sec_level = BT_SECURITY_HIGH; rfcomm_pi(sk)->role_switch = (opt & RFCOMM_LM_MASTER); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct bt_security sec; int err = 0; size_t len; u32 opt; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_setsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = BT_SECURITY_LOW; len = min_t(unsigned int, sizeof(sec), optlen); if (copy_from_user((char *) &sec, optval, len)) { err = -EFAULT; break; } if (sec.level > BT_SECURITY_HIGH) { err = -EINVAL; break; } rfcomm_pi(sk)->sec_level = sec.level; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct rfcomm_conninfo cinfo; struct l2cap_conn *conn = l2cap_pi(sk)->chan->conn; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case RFCOMM_LM: switch (rfcomm_pi(sk)->sec_level) { case BT_SECURITY_LOW: opt = RFCOMM_LM_AUTH; break; case BT_SECURITY_MEDIUM: opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT; break; case BT_SECURITY_HIGH: opt = RFCOMM_LM_AUTH | RFCOMM_LM_ENCRYPT | RFCOMM_LM_SECURE; break; default: opt = 0; break; } if (rfcomm_pi(sk)->role_switch) opt |= RFCOMM_LM_MASTER; if (put_user(opt, (u32 __user *) optval)) err = -EFAULT; break; case RFCOMM_CONNINFO: if (sk->sk_state != BT_CONNECTED && !rfcomm_pi(sk)->dlc->defer_setup) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = conn->hcon->handle; memcpy(cinfo.dev_class, conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *) &cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct bt_security sec; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_RFCOMM) return rfcomm_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (sk->sk_type != SOCK_STREAM) { err = -EINVAL; break; } sec.level = rfcomm_pi(sk)->sec_level; sec.key_size = 0; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int rfcomm_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk __maybe_unused = sock->sk; int err; BT_DBG("sk %p cmd %x arg %lx", sk, cmd, arg); err = bt_sock_ioctl(sock, cmd, arg); if (err == -ENOIOCTLCMD) { #ifdef CONFIG_BT_RFCOMM_TTY lock_sock(sk); err = rfcomm_dev_ioctl(sk, cmd, (void __user *) arg); release_sock(sk); #else err = -EOPNOTSUPP; #endif } return err; } static int rfcomm_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; lock_sock(sk); if (!sk->sk_shutdown) { sk->sk_shutdown = SHUTDOWN_MASK; __rfcomm_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } release_sock(sk); return err; } static int rfcomm_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; err = rfcomm_sock_shutdown(sock, 2); sock_orphan(sk); rfcomm_sock_kill(sk); return err; } /* ---- RFCOMM core layer callbacks ---- * * called under rfcomm_lock() */ int rfcomm_connect_ind(struct rfcomm_session *s, u8 channel, struct rfcomm_dlc **d) { struct sock *sk, *parent; bdaddr_t src, dst; int result = 0; BT_DBG("session %p channel %d", s, channel); rfcomm_session_getaddr(s, &src, &dst); /* Check if we have socket listening on channel */ parent = rfcomm_get_sock_by_channel(BT_LISTEN, channel, &src); if (!parent) return 0; bh_lock_sock(parent); /* Check for backlog size */ if (sk_acceptq_is_full(parent)) { BT_DBG("backlog full %d", parent->sk_ack_backlog); goto done; } sk = rfcomm_sock_alloc(sock_net(parent), NULL, BTPROTO_RFCOMM, GFP_ATOMIC); if (!sk) goto done; bt_sock_reclassify_lock(sk, BTPROTO_RFCOMM); rfcomm_sock_init(sk, parent); bacpy(&bt_sk(sk)->src, &src); bacpy(&bt_sk(sk)->dst, &dst); rfcomm_pi(sk)->channel = channel; sk->sk_state = BT_CONFIG; bt_accept_enqueue(parent, sk); /* Accept connection and return socket DLC */ *d = rfcomm_pi(sk)->dlc; result = 1; done: bh_unlock_sock(parent); if (test_bit(BT_SK_DEFER_SETUP, &bt_sk(parent)->flags)) parent->sk_state_change(parent); return result; } static int rfcomm_sock_debugfs_show(struct seq_file *f, void *p) { struct sock *sk; struct hlist_node *node; read_lock(&rfcomm_sk_list.lock); sk_for_each(sk, node, &rfcomm_sk_list.head) { seq_printf(f, "%s %s %d %d\n", batostr(&bt_sk(sk)->src), batostr(&bt_sk(sk)->dst), sk->sk_state, rfcomm_pi(sk)->channel); } read_unlock(&rfcomm_sk_list.lock); return 0; } static int rfcomm_sock_debugfs_open(struct inode *inode, struct file *file) { return single_open(file, rfcomm_sock_debugfs_show, inode->i_private); } static const struct file_operations rfcomm_sock_debugfs_fops = { .open = rfcomm_sock_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *rfcomm_sock_debugfs; static const struct proto_ops rfcomm_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = rfcomm_sock_release, .bind = rfcomm_sock_bind, .connect = rfcomm_sock_connect, .listen = rfcomm_sock_listen, .accept = rfcomm_sock_accept, .getname = rfcomm_sock_getname, .sendmsg = rfcomm_sock_sendmsg, .recvmsg = rfcomm_sock_recvmsg, .shutdown = rfcomm_sock_shutdown, .setsockopt = rfcomm_sock_setsockopt, .getsockopt = rfcomm_sock_getsockopt, .ioctl = rfcomm_sock_ioctl, .poll = bt_sock_poll, .socketpair = sock_no_socketpair, .mmap = sock_no_mmap }; static const struct net_proto_family rfcomm_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = rfcomm_sock_create }; int __init rfcomm_init_sockets(void) { int err; err = proto_register(&rfcomm_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_RFCOMM, &rfcomm_sock_family_ops); if (err < 0) goto error; if (bt_debugfs) { rfcomm_sock_debugfs = debugfs_create_file("rfcomm", 0444, bt_debugfs, NULL, &rfcomm_sock_debugfs_fops); if (!rfcomm_sock_debugfs) BT_ERR("Failed to create RFCOMM debug file"); } BT_INFO("RFCOMM socket layer initialized"); return 0; error: BT_ERR("RFCOMM socket layer registration failed"); proto_unregister(&rfcomm_proto); return err; } void __exit rfcomm_cleanup_sockets(void) { debugfs_remove(rfcomm_sock_debugfs); if (bt_sock_unregister(BTPROTO_RFCOMM) < 0) BT_ERR("RFCOMM socket layer unregistration failed"); proto_unregister(&rfcomm_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3835_0
crossvul-cpp_data_good_187_0
/* ecc.c * * Copyright (C) 2006-2017 wolfSSL Inc. * * This file is part of wolfSSL. * * wolfSSL is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * wolfSSL is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA */ #ifdef HAVE_CONFIG_H #include <config.h> #endif /* in case user set HAVE_ECC there */ #include <wolfssl/wolfcrypt/settings.h> /* Possible ECC enable options: * HAVE_ECC: Overall control of ECC default: on * HAVE_ECC_ENCRYPT: ECC encrypt/decrypt w/AES and HKDF default: off * HAVE_ECC_SIGN: ECC sign default: on * HAVE_ECC_VERIFY: ECC verify default: on * HAVE_ECC_DHE: ECC build shared secret default: on * HAVE_ECC_CDH: ECC cofactor DH shared secret default: off * HAVE_ECC_KEY_IMPORT: ECC Key import default: on * HAVE_ECC_KEY_EXPORT: ECC Key export default: on * ECC_SHAMIR: Enables Shamir calc method default: on * HAVE_COMP_KEY: Enables compressed key default: off * WOLFSSL_VALIDATE_ECC_IMPORT: Validate ECC key on import default: off * WOLFSSL_VALIDATE_ECC_KEYGEN: Validate ECC key gen default: off * WOLFSSL_CUSTOM_CURVES: Allow non-standard curves. default: off * Includes the curve "a" variable in calculation * ECC_DUMP_OID: Enables dump of OID encoding and sum default: off * ECC_CACHE_CURVE: Enables cache of curve info to improve perofrmance default: off * FP_ECC: ECC Fixed Point Cache default: off * USE_ECC_B_PARAM: Enable ECC curve B param default: off (on for HAVE_COMP_KEY) */ /* ECC Curve Types: * NO_ECC_SECP Disables SECP curves default: off (not defined) * HAVE_ECC_SECPR2 Enables SECP R2 curves default: off * HAVE_ECC_SECPR3 Enables SECP R3 curves default: off * HAVE_ECC_BRAINPOOL Enables Brainpool curves default: off * HAVE_ECC_KOBLITZ Enables Koblitz curves default: off */ /* ECC Curve Sizes: * ECC_USER_CURVES: Allows custom combination of key sizes below * HAVE_ALL_CURVES: Enable all key sizes (on unless ECC_USER_CURVES is defined) * HAVE_ECC112: 112 bit key * HAVE_ECC128: 128 bit key * HAVE_ECC160: 160 bit key * HAVE_ECC192: 192 bit key * HAVE_ECC224: 224 bit key * HAVE_ECC239: 239 bit key * NO_ECC256: Disables 256 bit key (on by default) * HAVE_ECC320: 320 bit key * HAVE_ECC384: 384 bit key * HAVE_ECC512: 512 bit key * HAVE_ECC521: 521 bit key */ #ifdef HAVE_ECC /* Make sure custom curves is enabled for Brainpool or Koblitz curve types */ #if (defined(HAVE_ECC_BRAINPOOL) || defined(HAVE_ECC_KOBLITZ)) &&\ !defined(WOLFSSL_CUSTOM_CURVES) #error Brainpool and Koblitz curves requires WOLFSSL_CUSTOM_CURVES #endif /* Make sure ASN is enabled for ECC sign/verify */ #if (defined(HAVE_ECC_SIGN) || defined(HAVE_ECC_VERIFY)) && defined(NO_ASN) #error ASN must be enabled for ECC sign/verify #endif #if defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2) /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */ #define FIPS_NO_WRAPPERS #ifdef USE_WINDOWS_API #pragma code_seg(".fipsA$e2") #pragma const_seg(".fipsB$e2") #endif #endif #include <wolfssl/wolfcrypt/ecc.h> #include <wolfssl/wolfcrypt/asn.h> #include <wolfssl/wolfcrypt/error-crypt.h> #include <wolfssl/wolfcrypt/logging.h> #include <wolfssl/wolfcrypt/types.h> #ifdef WOLFSSL_HAVE_SP_ECC #include <wolfssl/wolfcrypt/sp.h> #endif #ifdef HAVE_ECC_ENCRYPT #include <wolfssl/wolfcrypt/hmac.h> #include <wolfssl/wolfcrypt/aes.h> #endif #ifdef HAVE_X963_KDF #include <wolfssl/wolfcrypt/hash.h> #endif #ifdef WOLF_CRYPTO_DEV #include <wolfssl/wolfcrypt/cryptodev.h> #endif #ifdef NO_INLINE #include <wolfssl/wolfcrypt/misc.h> #else #define WOLFSSL_MISC_INCLUDED #include <wolfcrypt/src/misc.c> #endif #if defined(FREESCALE_LTC_ECC) #include <wolfssl/wolfcrypt/port/nxp/ksdk_port.h> #endif #ifdef WOLFSSL_SP_MATH #define GEN_MEM_ERR MP_MEM #elif defined(USE_FAST_MATH) #define GEN_MEM_ERR FP_MEM #else #define GEN_MEM_ERR MP_MEM #endif /* internal ECC states */ enum { ECC_STATE_NONE = 0, ECC_STATE_SHARED_SEC_GEN, ECC_STATE_SHARED_SEC_RES, ECC_STATE_SIGN_DO, ECC_STATE_SIGN_ENCODE, ECC_STATE_VERIFY_DECODE, ECC_STATE_VERIFY_DO, ECC_STATE_VERIFY_RES, }; /* map ptmul -> mulmod */ /* 256-bit curve on by default whether user curves or not */ #if defined(HAVE_ECC112) || defined(HAVE_ALL_CURVES) #define ECC112 #endif #if defined(HAVE_ECC128) || defined(HAVE_ALL_CURVES) #define ECC128 #endif #if defined(HAVE_ECC160) || defined(HAVE_ALL_CURVES) #define ECC160 #endif #if defined(HAVE_ECC192) || defined(HAVE_ALL_CURVES) #define ECC192 #endif #if defined(HAVE_ECC224) || defined(HAVE_ALL_CURVES) #define ECC224 #endif #if defined(HAVE_ECC239) || defined(HAVE_ALL_CURVES) #define ECC239 #endif #if !defined(NO_ECC256) || defined(HAVE_ALL_CURVES) #define ECC256 #endif #if defined(HAVE_ECC320) || defined(HAVE_ALL_CURVES) #define ECC320 #endif #if defined(HAVE_ECC384) || defined(HAVE_ALL_CURVES) #define ECC384 #endif #if defined(HAVE_ECC512) || defined(HAVE_ALL_CURVES) #define ECC512 #endif #if defined(HAVE_ECC521) || defined(HAVE_ALL_CURVES) #define ECC521 #endif /* The encoded OID's for ECC curves */ #ifdef ECC112 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp112r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,6 #else 0x2B,0x81,0x04,0x00,0x06 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_secp112r2[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,7 #else 0x2B,0x81,0x04,0x00,0x07 #endif }; #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC112 */ #ifdef ECC128 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp128r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,28 #else 0x2B,0x81,0x04,0x00,0x1C #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_secp128r2[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,29 #else 0x2B,0x81,0x04,0x00,0x1D #endif }; #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC128 */ #ifdef ECC160 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp160r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,8 #else 0x2B,0x81,0x04,0x00,0x08 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_secp160r2[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,30 #else 0x2B,0x81,0x04,0x00,0x1E #endif }; #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp160k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,9 #else 0x2B,0x81,0x04,0x00,0x09 #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp160r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,1 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x01 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC160 */ #ifdef ECC192 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp192r1[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,1 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x01 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_prime192v2[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,2 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x02 #endif }; #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 static const ecc_oid_t ecc_oid_prime192v3[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,3 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x03 #endif }; #endif /* HAVE_ECC_SECPR3 */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp192k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,31 #else 0x2B,0x81,0x04,0x00,0x1F #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp192r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,3 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x03 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC192 */ #ifdef ECC224 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp224r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,33 #else 0x2B,0x81,0x04,0x00,0x21 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp224k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,32 #else 0x2B,0x81,0x04,0x00,0x20 #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp224r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,5 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x05 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC224 */ #ifdef ECC239 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_prime239v1[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,4 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x04 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 static const ecc_oid_t ecc_oid_prime239v2[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,5 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x05 #endif }; #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 static const ecc_oid_t ecc_oid_prime239v3[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,6 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x06 #endif }; #endif /* HAVE_ECC_SECPR3 */ #endif /* ECC239 */ #ifdef ECC256 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp256r1[] = { #ifdef HAVE_OID_ENCODING 1,2,840,10045,3,1,7 #else 0x2A,0x86,0x48,0xCE,0x3D,0x03,0x01,0x07 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ static const ecc_oid_t ecc_oid_secp256k1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,10 #else 0x2B,0x81,0x04,0x00,0x0A #endif }; #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp256r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,7 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x07 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC256 */ #ifdef ECC320 #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp320r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,9 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x09 #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC320 */ #ifdef ECC384 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp384r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,34 #else 0x2B,0x81,0x04,0x00,0x22 #endif }; #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp384r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,11 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0B #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC384 */ #ifdef ECC512 #ifdef HAVE_ECC_BRAINPOOL static const ecc_oid_t ecc_oid_brainpoolp512r1[] = { #ifdef HAVE_OID_ENCODING 1,3,36,3,3,2,8,1,1,13 #else 0x2B,0x24,0x03,0x03,0x02,0x08,0x01,0x01,0x0D #endif }; #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC512 */ #ifdef ECC521 #ifndef NO_ECC_SECP static const ecc_oid_t ecc_oid_secp521r1[] = { #ifdef HAVE_OID_ENCODING 1,3,132,0,35 #else 0x2B,0x81,0x04,0x00,0x23 #endif }; #endif /* !NO_ECC_SECP */ #endif /* ECC521 */ /* This holds the key settings. ***MUST*** be organized by size from smallest to largest. */ const ecc_set_type ecc_sets[] = { #ifdef ECC112 #ifndef NO_ECC_SECP { 14, /* size/bytes */ ECC_SECP112R1, /* ID */ "SECP112R1", /* curve name */ "DB7C2ABF62E35E668076BEAD208B", /* prime */ "DB7C2ABF62E35E668076BEAD2088", /* A */ "659EF8BA043916EEDE8911702B22", /* B */ "DB7C2ABF62E35E7628DFAC6561C5", /* order */ "9487239995A5EE76B55F9C2F098", /* Gx */ "A89CE5AF8724C0A23E0E0FF77500", /* Gy */ ecc_oid_secp112r1, /* oid/oidSz */ sizeof(ecc_oid_secp112r1) / sizeof(ecc_oid_t), ECC_SECP112R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 14, /* size/bytes */ ECC_SECP112R2, /* ID */ "SECP112R2", /* curve name */ "DB7C2ABF62E35E668076BEAD208B", /* prime */ "6127C24C05F38A0AAAF65C0EF02C", /* A */ "51DEF1815DB5ED74FCC34C85D709", /* B */ "36DF0AAFD8B8D7597CA10520D04B", /* order */ "4BA30AB5E892B4E1649DD0928643", /* Gx */ "ADCD46F5882E3747DEF36E956E97", /* Gy */ ecc_oid_secp112r2, /* oid/oidSz */ sizeof(ecc_oid_secp112r2) / sizeof(ecc_oid_t), ECC_SECP112R2_OID, /* oid sum */ 4, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC112 */ #ifdef ECC128 #ifndef NO_ECC_SECP { 16, /* size/bytes */ ECC_SECP128R1, /* ID */ "SECP128R1", /* curve name */ "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFC", /* A */ "E87579C11079F43DD824993C2CEE5ED3", /* B */ "FFFFFFFE0000000075A30D1B9038A115", /* order */ "161FF7528B899B2D0C28607CA52C5B86", /* Gx */ "CF5AC8395BAFEB13C02DA292DDED7A83", /* Gy */ ecc_oid_secp128r1, /* oid/oidSz */ sizeof(ecc_oid_secp128r1) / sizeof(ecc_oid_t), ECC_SECP128R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 16, /* size/bytes */ ECC_SECP128R2, /* ID */ "SECP128R2", /* curve name */ "FFFFFFFDFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "D6031998D1B3BBFEBF59CC9BBFF9AEE1", /* A */ "5EEEFCA380D02919DC2C6558BB6D8A5D", /* B */ "3FFFFFFF7FFFFFFFBE0024720613B5A3", /* order */ "7B6AA5D85E572983E6FB32A7CDEBC140", /* Gx */ "27B6916A894D3AEE7106FE805FC34B44", /* Gy */ ecc_oid_secp128r2, /* oid/oidSz */ sizeof(ecc_oid_secp128r2) / sizeof(ecc_oid_t), ECC_SECP128R2_OID, /* oid sum */ 4, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #endif /* ECC128 */ #ifdef ECC160 #ifndef NO_ECC_SECP { 20, /* size/bytes */ ECC_SECP160R1, /* ID */ "SECP160R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF7FFFFFFC", /* A */ "1C97BEFC54BD7A8B65ACF89F81D4D4ADC565FA45", /* B */ "100000000000000000001F4C8F927AED3CA752257",/* order */ "4A96B5688EF573284664698968C38BB913CBFC82", /* Gx */ "23A628553168947D59DCC912042351377AC5FB32", /* Gy */ ecc_oid_secp160r1, /* oid/oidSz */ sizeof(ecc_oid_secp160r1) / sizeof(ecc_oid_t), ECC_SECP160R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 20, /* size/bytes */ ECC_SECP160R2, /* ID */ "SECP160R2", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC70", /* A */ "B4E134D3FB59EB8BAB57274904664D5AF50388BA", /* B */ "100000000000000000000351EE786A818F3A1A16B",/* order */ "52DCB034293A117E1F4FF11B30F7199D3144CE6D", /* Gx */ "FEAFFEF2E331F296E071FA0DF9982CFEA7D43F2E", /* Gy */ ecc_oid_secp160r2, /* oid/oidSz */ sizeof(ecc_oid_secp160r2) / sizeof(ecc_oid_t), ECC_SECP160R2_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_KOBLITZ { 20, /* size/bytes */ ECC_SECP160K1, /* ID */ "SECP160K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFAC73", /* prime */ "0000000000000000000000000000000000000000", /* A */ "0000000000000000000000000000000000000007", /* B */ "100000000000000000001B8FA16DFAB9ACA16B6B3",/* order */ "3B4C382CE37AA192A4019E763036F4F5DD4D7EBB", /* Gx */ "938CF935318FDCED6BC28286531733C3F03C4FEE", /* Gy */ ecc_oid_secp160k1, /* oid/oidSz */ sizeof(ecc_oid_secp160k1) / sizeof(ecc_oid_t), ECC_SECP160K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 20, /* size/bytes */ ECC_BRAINPOOLP160R1, /* ID */ "BRAINPOOLP160R1", /* curve name */ "E95E4A5F737059DC60DFC7AD95B3D8139515620F", /* prime */ "340E7BE2A280EB74E2BE61BADA745D97E8F7C300", /* A */ "1E589A8595423412134FAA2DBDEC95C8D8675E58", /* B */ "E95E4A5F737059DC60DF5991D45029409E60FC09", /* order */ "BED5AF16EA3F6A4F62938C4631EB5AF7BDBCDBC3", /* Gx */ "1667CB477A1A8EC338F94741669C976316DA6321", /* Gy */ ecc_oid_brainpoolp160r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp160r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP160R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC160 */ #ifdef ECC192 #ifndef NO_ECC_SECP { 24, /* size/bytes */ ECC_SECP192R1, /* ID */ "SECP192R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */ "64210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831", /* order */ "188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF1012", /* Gx */ "7192B95FFC8DA78631011ED6B24CDD573F977A11E794811", /* Gy */ ecc_oid_secp192r1, /* oid/oidSz */ sizeof(ecc_oid_secp192r1) / sizeof(ecc_oid_t), ECC_SECP192R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 24, /* size/bytes */ ECC_PRIME192V2, /* ID */ "PRIME192V2", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */ "CC22D6DFB95C6B25E49C0D6364A4E5980C393AA21668D953", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFE5FB1A724DC80418648D8DD31", /* order */ "EEA2BAE7E1497842F2DE7769CFE9C989C072AD696F48034A", /* Gx */ "6574D11D69B6EC7A672BB82A083DF2F2B0847DE970B2DE15", /* Gy */ ecc_oid_prime192v2, /* oid/oidSz */ sizeof(ecc_oid_prime192v2) / sizeof(ecc_oid_t), ECC_PRIME192V2_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 { 24, /* size/bytes */ ECC_PRIME192V3, /* ID */ "PRIME192V3", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC", /* A */ "22123DC2395A05CAA7423DAECCC94760A7D462256BD56916", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFF7A62D031C83F4294F640EC13", /* order */ "7D29778100C65A1DA1783716588DCE2B8B4AEE8E228F1896", /* Gx */ "38A90F22637337334B49DCB66A6DC8F9978ACA7648A943B0", /* Gy */ ecc_oid_prime192v3, /* oid/oidSz */ sizeof(ecc_oid_prime192v3) / sizeof(ecc_oid_t), ECC_PRIME192V3_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR3 */ #ifdef HAVE_ECC_KOBLITZ { 24, /* size/bytes */ ECC_SECP192K1, /* ID */ "SECP192K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFEE37", /* prime */ "000000000000000000000000000000000000000000000000", /* A */ "000000000000000000000000000000000000000000000003", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFE26F2FC170F69466A74DEFD8D", /* order */ "DB4FF10EC057E9AE26B07D0280B7F4341DA5D1B1EAE06C7D", /* Gx */ "9B2F2F6D9C5628A7844163D015BE86344082AA88D95E2F9D", /* Gy */ ecc_oid_secp192k1, /* oid/oidSz */ sizeof(ecc_oid_secp192k1) / sizeof(ecc_oid_t), ECC_SECP192K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 24, /* size/bytes */ ECC_BRAINPOOLP192R1, /* ID */ "BRAINPOOLP192R1", /* curve name */ "C302F41D932A36CDA7A3463093D18DB78FCE476DE1A86297", /* prime */ "6A91174076B1E0E19C39C031FE8685C1CAE040E5C69A28EF", /* A */ "469A28EF7C28CCA3DC721D044F4496BCCA7EF4146FBF25C9", /* B */ "C302F41D932A36CDA7A3462F9E9E916B5BE8F1029AC4ACC1", /* order */ "C0A0647EAAB6A48753B033C56CB0F0900A2F5C4853375FD6", /* Gx */ "14B690866ABD5BB88B5F4828C1490002E6773FA2FA299B8F", /* Gy */ ecc_oid_brainpoolp192r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp192r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP192R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC192 */ #ifdef ECC224 #ifndef NO_ECC_SECP { 28, /* size/bytes */ ECC_SECP224R1, /* ID */ "SECP224R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000001", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFE", /* A */ "B4050A850C04B3ABF54132565044B0B7D7BFD8BA270B39432355FFB4", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFF16A2E0B8F03E13DD29455C5C2A3D", /* order */ "B70E0CBD6BB4BF7F321390B94A03C1D356C21122343280D6115C1D21", /* Gx */ "BD376388B5F723FB4C22DFE6CD4375A05A07476444D5819985007E34", /* Gy */ ecc_oid_secp224r1, /* oid/oidSz */ sizeof(ecc_oid_secp224r1) / sizeof(ecc_oid_t), ECC_SECP224R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ { 28, /* size/bytes */ ECC_SECP224K1, /* ID */ "SECP224K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFE56D", /* prime */ "00000000000000000000000000000000000000000000000000000000", /* A */ "00000000000000000000000000000000000000000000000000000005", /* B */ "10000000000000000000000000001DCE8D2EC6184CAF0A971769FB1F7",/* order */ "A1455B334DF099DF30FC28A169A467E9E47075A90F7E650EB6B7A45C", /* Gx */ "7E089FED7FBA344282CAFBD6F7E319F7C0B0BD59E2CA4BDB556D61A5", /* Gy */ ecc_oid_secp224k1, /* oid/oidSz */ sizeof(ecc_oid_secp224k1) / sizeof(ecc_oid_t), ECC_SECP224K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 28, /* size/bytes */ ECC_BRAINPOOLP224R1, /* ID */ "BRAINPOOLP224R1", /* curve name */ "D7C134AA264366862A18302575D1D787B09F075797DA89F57EC8C0FF", /* prime */ "68A5E62CA9CE6C1C299803A6C1530B514E182AD8B0042A59CAD29F43", /* A */ "2580F63CCFE44138870713B1A92369E33E2135D266DBB372386C400B", /* B */ "D7C134AA264366862A18302575D0FB98D116BC4B6DDEBCA3A5A7939F", /* order */ "0D9029AD2C7E5CF4340823B2A87DC68C9E4CE3174C1E6EFDEE12C07D", /* Gx */ "58AA56F772C0726F24C6B89E4ECDAC24354B9E99CAA3F6D3761402CD", /* Gy */ ecc_oid_brainpoolp224r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp224r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP224R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC224 */ #ifdef ECC239 #ifndef NO_ECC_SECP { 30, /* size/bytes */ ECC_PRIME239V1, /* ID */ "PRIME239V1", /* curve name */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */ "6B016C3BDCF18941D0D654921475CA71A9DB2FB27D1D37796185C2942C0A", /* B */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF9E5E9A9F5D9071FBD1522688909D0B", /* order */ "0FFA963CDCA8816CCC33B8642BEDF905C3D358573D3F27FBBD3B3CB9AAAF", /* Gx */ "7DEBE8E4E90A5DAE6E4054CA530BA04654B36818CE226B39FCCB7B02F1AE", /* Gy */ ecc_oid_prime239v1, /* oid/oidSz */ sizeof(ecc_oid_prime239v1) / sizeof(ecc_oid_t), ECC_PRIME239V1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_SECPR2 { 30, /* size/bytes */ ECC_PRIME239V2, /* ID */ "PRIME239V2", /* curve name */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */ "617FAB6832576CBBFED50D99F0249C3FEE58B94BA0038C7AE84C8C832F2C", /* B */ "7FFFFFFFFFFFFFFFFFFFFFFF800000CFA7E8594377D414C03821BC582063", /* order */ "38AF09D98727705120C921BB5E9E26296A3CDCF2F35757A0EAFD87B830E7", /* Gx */ "5B0125E4DBEA0EC7206DA0FC01D9B081329FB555DE6EF460237DFF8BE4BA", /* Gy */ ecc_oid_prime239v2, /* oid/oidSz */ sizeof(ecc_oid_prime239v2) / sizeof(ecc_oid_t), ECC_PRIME239V2_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR2 */ #ifdef HAVE_ECC_SECPR3 { 30, /* size/bytes */ ECC_PRIME239V3, /* ID */ "PRIME239V3", /* curve name */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFF", /* prime */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFFFFFFFF8000000000007FFFFFFFFFFC", /* A */ "255705FA2A306654B1F4CB03D6A750A30C250102D4988717D9BA15AB6D3E", /* B */ "7FFFFFFFFFFFFFFFFFFFFFFF7FFFFF975DEB41B3A6057C3C432146526551", /* order */ "6768AE8E18BB92CFCF005C949AA2C6D94853D0E660BBF854B1C9505FE95A", /* Gx */ "1607E6898F390C06BC1D552BAD226F3B6FCFE48B6E818499AF18E3ED6CF3", /* Gy */ ecc_oid_prime239v3, /* oid/oidSz */ sizeof(ecc_oid_prime239v3) / sizeof(ecc_oid_t), ECC_PRIME239V3_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_SECPR3 */ #endif /* ECC239 */ #ifdef ECC256 #ifndef NO_ECC_SECP { 32, /* size/bytes */ ECC_SECP256R1, /* ID */ "SECP256R1", /* curve name */ "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC", /* A */ "5AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B", /* B */ "FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC632551", /* order */ "6B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C296", /* Gx */ "4FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F5", /* Gy */ ecc_oid_secp256r1, /* oid/oidSz */ sizeof(ecc_oid_secp256r1) / sizeof(ecc_oid_t), ECC_SECP256R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_KOBLITZ { 32, /* size/bytes */ ECC_SECP256K1, /* ID */ "SECP256K1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F", /* prime */ "0000000000000000000000000000000000000000000000000000000000000000", /* A */ "0000000000000000000000000000000000000000000000000000000000000007", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141", /* order */ "79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798", /* Gx */ "483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8", /* Gy */ ecc_oid_secp256k1, /* oid/oidSz */ sizeof(ecc_oid_secp256k1) / sizeof(ecc_oid_t), ECC_SECP256K1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_KOBLITZ */ #ifdef HAVE_ECC_BRAINPOOL { 32, /* size/bytes */ ECC_BRAINPOOLP256R1, /* ID */ "BRAINPOOLP256R1", /* curve name */ "A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E5377", /* prime */ "7D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9", /* A */ "26DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B6", /* B */ "A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7", /* order */ "8BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262", /* Gx */ "547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F046997", /* Gy */ ecc_oid_brainpoolp256r1, /* oid/oidSz */ sizeof(ecc_oid_brainpoolp256r1) / sizeof(ecc_oid_t), ECC_BRAINPOOLP256R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC256 */ #ifdef ECC320 #ifdef HAVE_ECC_BRAINPOOL { 40, /* size/bytes */ ECC_BRAINPOOLP320R1, /* ID */ "BRAINPOOLP320R1", /* curve name */ "D35E472036BC4FB7E13C785ED201E065F98FCFA6F6F40DEF4F92B9EC7893EC28FCD412B1F1B32E27", /* prime */ "3EE30B568FBAB0F883CCEBD46D3F3BB8A2A73513F5EB79DA66190EB085FFA9F492F375A97D860EB4", /* A */ "520883949DFDBC42D3AD198640688A6FE13F41349554B49ACC31DCCD884539816F5EB4AC8FB1F1A6", /* B */ "D35E472036BC4FB7E13C785ED201E065F98FCFA5B68F12A32D482EC7EE8658E98691555B44C59311", /* order */ "43BD7E9AFB53D8B85289BCC48EE5BFE6F20137D10A087EB6E7871E2A10A599C710AF8D0D39E20611", /* Gx */ "14FDD05545EC1CC8AB4093247F77275E0743FFED117182EAA9C77877AAAC6AC7D35245D1692E8EE1", /* Gy */ ecc_oid_brainpoolp320r1, sizeof(ecc_oid_brainpoolp320r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_BRAINPOOLP320R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC320 */ #ifdef ECC384 #ifndef NO_ECC_SECP { 48, /* size/bytes */ ECC_SECP384R1, /* ID */ "SECP384R1", /* curve name */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFF", /* prime */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFF0000000000000000FFFFFFFC", /* A */ "B3312FA7E23EE7E4988E056BE3F82D19181D9C6EFE8141120314088F5013875AC656398D8A2ED19D2A85C8EDD3EC2AEF", /* B */ "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC7634D81F4372DDF581A0DB248B0A77AECEC196ACCC52973", /* order */ "AA87CA22BE8B05378EB1C71EF320AD746E1D3B628BA79B9859F741E082542A385502F25DBF55296C3A545E3872760AB7", /* Gx */ "3617DE4A96262C6F5D9E98BF9292DC29F8F41DBD289A147CE9DA3113B5F0B8C00A60B1CE1D7E819D7A431D7C90EA0E5F", /* Gy */ ecc_oid_secp384r1, sizeof(ecc_oid_secp384r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_SECP384R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #ifdef HAVE_ECC_BRAINPOOL { 48, /* size/bytes */ ECC_BRAINPOOLP384R1, /* ID */ "BRAINPOOLP384R1", /* curve name */ "8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B412B1DA197FB71123ACD3A729901D1A71874700133107EC53", /* prime */ "7BC382C63D8C150C3C72080ACE05AFA0C2BEA28E4FB22787139165EFBA91F90F8AA5814A503AD4EB04A8C7DD22CE2826", /* A */ "04A8C7DD22CE28268B39B55416F0447C2FB77DE107DCD2A62E880EA53EEB62D57CB4390295DBC9943AB78696FA504C11", /* B */ "8CB91E82A3386D280F5D6F7E50E641DF152F7109ED5456B31F166E6CAC0425A7CF3AB6AF6B7FC3103B883202E9046565", /* order */ "1D1C64F068CF45FFA2A63A81B7C13F6B8847A3E77EF14FE3DB7FCAFE0CBD10E8E826E03436D646AAEF87B2E247D4AF1E", /* Gx */ "8ABE1D7520F9C2A45CB1EB8E95CFD55262B70B29FEEC5864E19C054FF99129280E4646217791811142820341263C5315", /* Gy */ ecc_oid_brainpoolp384r1, sizeof(ecc_oid_brainpoolp384r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_BRAINPOOLP384R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC384 */ #ifdef ECC512 #ifdef HAVE_ECC_BRAINPOOL { 64, /* size/bytes */ ECC_BRAINPOOLP512R1, /* ID */ "BRAINPOOLP512R1", /* curve name */ "AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA703308717D4D9B009BC66842AECDA12AE6A380E62881FF2F2D82C68528AA6056583A48F3", /* prime */ "7830A3318B603B89E2327145AC234CC594CBDD8D3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CA", /* A */ "3DF91610A83441CAEA9863BC2DED5D5AA8253AA10A2EF1C98B9AC8B57F1117A72BF2C7B9E7C1AC4D77FC94CADC083E67984050B75EBAE5DD2809BD638016F723", /* B */ "AADD9DB8DBE9C48B3FD4E6AE33C9FC07CB308DB3B3C9D20ED6639CCA70330870553E5C414CA92619418661197FAC10471DB1D381085DDADDB58796829CA90069", /* order */ "81AEE4BDD82ED9645A21322E9C4C6A9385ED9F70B5D916C1B43B62EEF4D0098EFF3B1F78E2D0D48D50D1687B93B97D5F7C6D5047406A5E688B352209BCB9F822", /* Gx */ "7DDE385D566332ECC0EABFA9CF7822FDF209F70024A57B1AA000C55B881F8111B2DCDE494A5F485E5BCA4BD88A2763AED1CA2B2FA8F0540678CD1E0F3AD80892", /* Gy */ ecc_oid_brainpoolp512r1, sizeof(ecc_oid_brainpoolp512r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_BRAINPOOLP512R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* HAVE_ECC_BRAINPOOL */ #endif /* ECC512 */ #ifdef ECC521 #ifndef NO_ECC_SECP { 66, /* size/bytes */ ECC_SECP521R1, /* ID */ "SECP521R1", /* curve name */ "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF", /* prime */ "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFC", /* A */ "51953EB9618E1C9A1F929A21A0B68540EEA2DA725B99B315F3B8B489918EF109E156193951EC7E937B1652C0BD3BB1BF073573DF883D2C34F1EF451FD46B503F00", /* B */ "1FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFA51868783BF2F966B7FCC0148F709A5D03BB5C9B8899C47AEBB6FB71E91386409", /* order */ "C6858E06B70404E9CD9E3ECB662395B4429C648139053FB521F828AF606B4D3DBAA14B5E77EFE75928FE1DC127A2FFA8DE3348B3C1856A429BF97E7E31C2E5BD66", /* Gx */ "11839296A789A3BC0045C8A5FB42C7D1BD998F54449579B446817AFBD17273E662C97EE72995EF42640C550B9013FAD0761353C7086A272C24088BE94769FD16650", /* Gy */ ecc_oid_secp521r1, sizeof(ecc_oid_secp521r1) / sizeof(ecc_oid_t), /* oid/oidSz */ ECC_SECP521R1_OID, /* oid sum */ 1, /* cofactor */ }, #endif /* !NO_ECC_SECP */ #endif /* ECC521 */ #if defined(WOLFSSL_CUSTOM_CURVES) && defined(ECC_CACHE_CURVE) /* place holder for custom curve index for cache */ { 1, /* non-zero */ ECC_CURVE_CUSTOM, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0 }, #endif { 0, -1, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 0, 0 } }; #define ECC_SET_COUNT (sizeof(ecc_sets)/sizeof(ecc_set_type)) #ifdef HAVE_OID_ENCODING /* encoded OID cache */ typedef struct { word32 oidSz; byte oid[ECC_MAX_OID_LEN]; } oid_cache_t; static oid_cache_t ecc_oid_cache[ECC_SET_COUNT]; #endif #ifdef HAVE_COMP_KEY static int wc_ecc_export_x963_compressed(ecc_key*, byte* out, word32* outLen); #endif #ifdef WOLFSSL_ATECC508A typedef void* ecc_curve_spec; #else #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH) static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a, mp_int* prime, mp_int* order); #endif int mp_jacobi(mp_int* a, mp_int* n, int* c); int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret); /* Curve Specs */ typedef struct ecc_curve_spec { const ecc_set_type* dp; mp_int* prime; mp_int* Af; #ifdef USE_ECC_B_PARAM mp_int* Bf; #endif mp_int* order; mp_int* Gx; mp_int* Gy; #ifdef ECC_CACHE_CURVE mp_int prime_lcl; mp_int Af_lcl; #ifdef USE_ECC_B_PARAM mp_int Bf_lcl; #endif mp_int order_lcl; mp_int Gx_lcl; mp_int Gy_lcl; #else mp_int* spec_ints; word32 spec_count; word32 spec_use; #endif byte load_mask; } ecc_curve_spec; enum ecc_curve_load_mask { ECC_CURVE_FIELD_NONE = 0x00, ECC_CURVE_FIELD_PRIME = 0x01, ECC_CURVE_FIELD_AF = 0x02, #ifdef USE_ECC_B_PARAM ECC_CURVE_FIELD_BF = 0x04, #endif ECC_CURVE_FIELD_ORDER = 0x08, ECC_CURVE_FIELD_GX = 0x10, ECC_CURVE_FIELD_GY = 0x20, #ifdef USE_ECC_B_PARAM ECC_CURVE_FIELD_ALL = 0x3F, ECC_CURVE_FIELD_COUNT = 6, #else ECC_CURVE_FIELD_ALL = 0x3B, ECC_CURVE_FIELD_COUNT = 5, #endif }; #ifdef ECC_CACHE_CURVE /* cache (mp_int) of the curve parameters */ static ecc_curve_spec* ecc_curve_spec_cache[ECC_SET_COUNT]; #ifndef SINGLE_THREADED static wolfSSL_Mutex ecc_curve_cache_mutex; #endif #define DECLARE_CURVE_SPECS(intcount) ecc_curve_spec* curve = NULL; #else #define DECLARE_CURVE_SPECS(intcount) \ mp_int spec_ints[(intcount)]; \ ecc_curve_spec curve_lcl; \ ecc_curve_spec* curve = &curve_lcl; \ XMEMSET(curve, 0, sizeof(ecc_curve_spec)); \ curve->spec_ints = spec_ints; \ curve->spec_count = intcount; #endif /* ECC_CACHE_CURVE */ static void _wc_ecc_curve_free(ecc_curve_spec* curve) { if (curve == NULL) { return; } if (curve->load_mask & ECC_CURVE_FIELD_PRIME) mp_clear(curve->prime); if (curve->load_mask & ECC_CURVE_FIELD_AF) mp_clear(curve->Af); #ifdef USE_ECC_B_PARAM if (curve->load_mask & ECC_CURVE_FIELD_BF) mp_clear(curve->Bf); #endif if (curve->load_mask & ECC_CURVE_FIELD_ORDER) mp_clear(curve->order); if (curve->load_mask & ECC_CURVE_FIELD_GX) mp_clear(curve->Gx); if (curve->load_mask & ECC_CURVE_FIELD_GY) mp_clear(curve->Gy); curve->load_mask = 0; } static void wc_ecc_curve_free(ecc_curve_spec* curve) { /* don't free cached curves */ #ifndef ECC_CACHE_CURVE _wc_ecc_curve_free(curve); #endif (void)curve; } static int wc_ecc_curve_load_item(const char* src, mp_int** dst, ecc_curve_spec* curve, byte mask) { int err; #ifndef ECC_CACHE_CURVE /* get mp_int from temp */ if (curve->spec_use >= curve->spec_count) { WOLFSSL_MSG("Invalid DECLARE_CURVE_SPECS count"); return ECC_BAD_ARG_E; } *dst = &curve->spec_ints[curve->spec_use++]; #endif err = mp_init(*dst); if (err == MP_OKAY) { curve->load_mask |= mask; err = mp_read_radix(*dst, src, MP_RADIX_HEX); #ifdef HAVE_WOLF_BIGINT if (err == MP_OKAY) err = wc_mp_to_bigint(*dst, &(*dst)->raw); #endif } return err; } static int wc_ecc_curve_load(const ecc_set_type* dp, ecc_curve_spec** pCurve, byte load_mask) { int ret = 0, x; ecc_curve_spec* curve; byte load_items = 0; /* mask of items to load */ if (dp == NULL || pCurve == NULL) return BAD_FUNC_ARG; #ifdef ECC_CACHE_CURVE x = wc_ecc_get_curve_idx(dp->id); if (x == ECC_CURVE_INVALID) return ECC_BAD_ARG_E; #if !defined(SINGLE_THREADED) ret = wc_LockMutex(&ecc_curve_cache_mutex); if (ret != 0) { return ret; } #endif /* make sure cache has been allocated */ if (ecc_curve_spec_cache[x] == NULL) { ecc_curve_spec_cache[x] = (ecc_curve_spec*)XMALLOC( sizeof(ecc_curve_spec), NULL, DYNAMIC_TYPE_ECC); if (ecc_curve_spec_cache[x] == NULL) { #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) wc_UnLockMutex(&ecc_curve_cache_mutex); #endif return MEMORY_E; } XMEMSET(ecc_curve_spec_cache[x], 0, sizeof(ecc_curve_spec)); } /* set curve pointer to cache */ *pCurve = ecc_curve_spec_cache[x]; #endif /* ECC_CACHE_CURVE */ curve = *pCurve; /* make sure the curve is initialized */ if (curve->dp != dp) { curve->load_mask = 0; #ifdef ECC_CACHE_CURVE curve->prime = &curve->prime_lcl; curve->Af = &curve->Af_lcl; #ifdef USE_ECC_B_PARAM curve->Bf = &curve->Bf_lcl; #endif curve->order = &curve->order_lcl; curve->Gx = &curve->Gx_lcl; curve->Gy = &curve->Gy_lcl; #endif } curve->dp = dp; /* set dp info */ /* determine items to load */ load_items = (~curve->load_mask & load_mask); curve->load_mask |= load_items; /* load items */ x = 0; if (load_items & ECC_CURVE_FIELD_PRIME) x += wc_ecc_curve_load_item(dp->prime, &curve->prime, curve, ECC_CURVE_FIELD_PRIME); if (load_items & ECC_CURVE_FIELD_AF) x += wc_ecc_curve_load_item(dp->Af, &curve->Af, curve, ECC_CURVE_FIELD_AF); #ifdef USE_ECC_B_PARAM if (load_items & ECC_CURVE_FIELD_BF) x += wc_ecc_curve_load_item(dp->Bf, &curve->Bf, curve, ECC_CURVE_FIELD_BF); #endif if (load_items & ECC_CURVE_FIELD_ORDER) x += wc_ecc_curve_load_item(dp->order, &curve->order, curve, ECC_CURVE_FIELD_ORDER); if (load_items & ECC_CURVE_FIELD_GX) x += wc_ecc_curve_load_item(dp->Gx, &curve->Gx, curve, ECC_CURVE_FIELD_GX); if (load_items & ECC_CURVE_FIELD_GY) x += wc_ecc_curve_load_item(dp->Gy, &curve->Gy, curve, ECC_CURVE_FIELD_GY); /* check for error */ if (x != 0) { wc_ecc_curve_free(curve); ret = MP_READ_E; } #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) wc_UnLockMutex(&ecc_curve_cache_mutex); #endif return ret; } #ifdef ECC_CACHE_CURVE int wc_ecc_curve_cache_init(void) { int ret = 0; #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) ret = wc_InitMutex(&ecc_curve_cache_mutex); #endif return ret; } void wc_ecc_curve_cache_free(void) { int x; /* free all ECC curve caches */ for (x = 0; x < (int)ECC_SET_COUNT; x++) { if (ecc_curve_spec_cache[x]) { _wc_ecc_curve_free(ecc_curve_spec_cache[x]); XFREE(ecc_curve_spec_cache[x], NULL, DYNAMIC_TYPE_ECC); ecc_curve_spec_cache[x] = NULL; } } #if defined(ECC_CACHE_CURVE) && !defined(SINGLE_THREADED) wc_FreeMutex(&ecc_curve_cache_mutex); #endif } #endif /* ECC_CACHE_CURVE */ #endif /* WOLFSSL_ATECC508A */ /* Retrieve the curve name for the ECC curve id. * * curve_id The id of the curve. * returns the name stored from the curve if available, otherwise NULL. */ const char* wc_ecc_get_name(int curve_id) { int curve_idx = wc_ecc_get_curve_idx(curve_id); if (curve_idx == ECC_CURVE_INVALID) return NULL; return ecc_sets[curve_idx].name; } int wc_ecc_set_curve(ecc_key* key, int keysize, int curve_id) { if (keysize <= 0 && curve_id < 0) { return BAD_FUNC_ARG; } if (keysize > ECC_MAXSIZE) { return ECC_BAD_ARG_E; } /* handle custom case */ if (key->idx != ECC_CUSTOM_IDX) { int x; /* default values */ key->idx = 0; key->dp = NULL; /* find ecc_set based on curve_id or key size */ for (x = 0; ecc_sets[x].size != 0; x++) { if (curve_id > ECC_CURVE_DEF) { if (curve_id == ecc_sets[x].id) break; } else if (keysize <= ecc_sets[x].size) { break; } } if (ecc_sets[x].size == 0) { WOLFSSL_MSG("ECC Curve not found"); return ECC_CURVE_OID_E; } key->idx = x; key->dp = &ecc_sets[x]; } return 0; } #ifdef ALT_ECC_SIZE static void alt_fp_init(fp_int* a) { a->size = FP_SIZE_ECC; fp_zero(a); } #endif /* ALT_ECC_SIZE */ #ifndef WOLFSSL_ATECC508A #if !defined(WOLFSSL_SP_MATH) || defined(WOLFSSL_PUBLIC_ECC_ADD_DBL) /** Add two ECC points P The point to add Q The point to add R [out] The destination of the double a ECC curve parameter a modulus The modulus of the field the ECC curve is in mp The "b" value from montgomery_setup() return MP_OKAY on success */ int ecc_projective_add_point(ecc_point* P, ecc_point* Q, ecc_point* R, mp_int* a, mp_int* modulus, mp_digit mp) { #ifndef WOLFSSL_SP_MATH mp_int t1, t2; #ifdef ALT_ECC_SIZE mp_int rx, ry, rz; #endif mp_int *x, *y, *z; int err; if (P == NULL || Q == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } /* if Q == R then swap P and Q, so we don't require a local x,y,z */ if (Q == R) { ecc_point* tPt = P; P = Q; Q = tPt; } if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return err; } /* should we dbl instead? */ if (err == MP_OKAY) err = mp_sub(modulus, Q->y, &t1); if (err == MP_OKAY) { if ( (mp_cmp(P->x, Q->x) == MP_EQ) && (get_digit_count(Q->z) && mp_cmp(P->z, Q->z) == MP_EQ) && (mp_cmp(P->y, Q->y) == MP_EQ || mp_cmp(P->y, &t1) == MP_EQ)) { mp_clear(&t1); mp_clear(&t2); return ecc_projective_dbl_point(P, R, a, modulus, mp); } } if (err != MP_OKAY) { goto done; } /* If use ALT_ECC_SIZE we need to use local stack variable since ecc_point x,y,z is reduced size */ #ifdef ALT_ECC_SIZE /* Use local stack variable */ x = &rx; y = &ry; z = &rz; if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { goto done; } #else /* Use destination directly */ x = R->x; y = R->y; z = R->z; #endif if (err == MP_OKAY) err = mp_copy(P->x, x); if (err == MP_OKAY) err = mp_copy(P->y, y); if (err == MP_OKAY) err = mp_copy(P->z, z); /* if Z is one then these are no-operations */ if (err == MP_OKAY) { if (!mp_iszero(Q->z)) { /* T1 = Z' * Z' */ err = mp_sqr(Q->z, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* X = X * T1 */ if (err == MP_OKAY) err = mp_mul(&t1, x, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* T1 = Z' * T1 */ if (err == MP_OKAY) err = mp_mul(Q->z, &t1, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* Y = Y * T1 */ if (err == MP_OKAY) err = mp_mul(&t1, y, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); } } /* T1 = Z*Z */ if (err == MP_OKAY) err = mp_sqr(z, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* T2 = X' * T1 */ if (err == MP_OKAY) err = mp_mul(Q->x, &t1, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = Z * T1 */ if (err == MP_OKAY) err = mp_mul(z, &t1, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* T1 = Y' * T1 */ if (err == MP_OKAY) err = mp_mul(Q->y, &t1, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* Y = Y - T1 */ if (err == MP_OKAY) err = mp_sub(y, &t1, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } /* T1 = 2T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t1, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = Y + T1 */ if (err == MP_OKAY) err = mp_add(&t1, y, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* X = X - T2 */ if (err == MP_OKAY) err = mp_sub(x, &t2, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* T2 = 2T2 */ if (err == MP_OKAY) err = mp_add(&t2, &t2, &t2); if (err == MP_OKAY) { if (mp_cmp(&t2, modulus) != MP_LT) err = mp_sub(&t2, modulus, &t2); } /* T2 = X + T2 */ if (err == MP_OKAY) err = mp_add(&t2, x, &t2); if (err == MP_OKAY) { if (mp_cmp(&t2, modulus) != MP_LT) err = mp_sub(&t2, modulus, &t2); } if (err == MP_OKAY) { if (!mp_iszero(Q->z)) { /* Z = Z * Z' */ err = mp_mul(z, Q->z, z); if (err == MP_OKAY) err = mp_montgomery_reduce(z, modulus, mp); } } /* Z = Z * X */ if (err == MP_OKAY) err = mp_mul(z, x, z); if (err == MP_OKAY) err = mp_montgomery_reduce(z, modulus, mp); /* T1 = T1 * X */ if (err == MP_OKAY) err = mp_mul(&t1, x, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* X = X * X */ if (err == MP_OKAY) err = mp_sqr(x, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* T2 = T2 * x */ if (err == MP_OKAY) err = mp_mul(&t2, x, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = T1 * X */ if (err == MP_OKAY) err = mp_mul(&t1, x, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* X = Y*Y */ if (err == MP_OKAY) err = mp_sqr(y, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* X = X - T2 */ if (err == MP_OKAY) err = mp_sub(x, &t2, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* T2 = T2 - X */ if (err == MP_OKAY) err = mp_sub(&t2, x, &t2); if (err == MP_OKAY) { if (mp_isneg(&t2)) err = mp_add(&t2, modulus, &t2); } /* T2 = T2 - X */ if (err == MP_OKAY) err = mp_sub(&t2, x, &t2); if (err == MP_OKAY) { if (mp_isneg(&t2)) err = mp_add(&t2, modulus, &t2); } /* T2 = T2 * Y */ if (err == MP_OKAY) err = mp_mul(&t2, y, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* Y = T2 - T1 */ if (err == MP_OKAY) err = mp_sub(&t2, &t1, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } /* Y = Y/2 */ if (err == MP_OKAY) { if (mp_isodd(y) == MP_YES) err = mp_add(y, modulus, y); } if (err == MP_OKAY) err = mp_div_2(y, y); #ifdef ALT_ECC_SIZE if (err == MP_OKAY) err = mp_copy(x, R->x); if (err == MP_OKAY) err = mp_copy(y, R->y); if (err == MP_OKAY) err = mp_copy(z, R->z); #endif done: /* clean up */ mp_clear(&t1); mp_clear(&t2); return err; #else if (P == NULL || Q == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } (void)a; (void)mp; return sp_ecc_proj_add_point_256(P->x, P->y, P->z, Q->x, Q->y, Q->z, R->x, R->y, R->z); #endif } /* ### Point doubling in Jacobian coordinate system ### * * let us have a curve: y^2 = x^3 + a*x + b * in Jacobian coordinates it becomes: y^2 = x^3 + a*x*z^4 + b*z^6 * * The doubling of P = (Xp, Yp, Zp) is given by R = (Xr, Yr, Zr) where: * Xr = M^2 - 2*S * Yr = M * (S - Xr) - 8*T * Zr = 2 * Yp * Zp * * M = 3 * Xp^2 + a*Zp^4 * T = Yp^4 * S = 4 * Xp * Yp^2 * * SPECIAL CASE: when a == 3 we can compute M as * M = 3 * (Xp^2 - Zp^4) = 3 * (Xp + Zp^2) * (Xp - Zp^2) */ /** Double an ECC point P The point to double R [out] The destination of the double a ECC curve parameter a modulus The modulus of the field the ECC curve is in mp The "b" value from montgomery_setup() return MP_OKAY on success */ int ecc_projective_dbl_point(ecc_point *P, ecc_point *R, mp_int* a, mp_int* modulus, mp_digit mp) { #ifndef WOLFSSL_SP_MATH mp_int t1, t2; #ifdef ALT_ECC_SIZE mp_int rx, ry, rz; #endif mp_int *x, *y, *z; int err; if (P == NULL || R == NULL || modulus == NULL) return ECC_BAD_ARG_E; if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return err; } /* If use ALT_ECC_SIZE we need to use local stack variable since ecc_point x,y,z is reduced size */ #ifdef ALT_ECC_SIZE /* Use local stack variable */ x = &rx; y = &ry; z = &rz; if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { mp_clear(&t1); mp_clear(&t2); return err; } #else /* Use destination directly */ x = R->x; y = R->y; z = R->z; #endif if (err == MP_OKAY) err = mp_copy(P->x, x); if (err == MP_OKAY) err = mp_copy(P->y, y); if (err == MP_OKAY) err = mp_copy(P->z, z); /* T1 = Z * Z */ if (err == MP_OKAY) err = mp_sqr(z, &t1); if (err == MP_OKAY) err = mp_montgomery_reduce(&t1, modulus, mp); /* Z = Y * Z */ if (err == MP_OKAY) err = mp_mul(z, y, z); if (err == MP_OKAY) err = mp_montgomery_reduce(z, modulus, mp); /* Z = 2Z */ if (err == MP_OKAY) err = mp_add(z, z, z); if (err == MP_OKAY) { if (mp_cmp(z, modulus) != MP_LT) err = mp_sub(z, modulus, z); } /* Determine if curve "a" should be used in calc */ #ifdef WOLFSSL_CUSTOM_CURVES if (err == MP_OKAY) { /* Use a and prime to determine if a == 3 */ err = mp_submod(modulus, a, modulus, &t2); } if (err == MP_OKAY && mp_cmp_d(&t2, 3) != MP_EQ) { /* use "a" in calc */ /* T2 = T1 * T1 */ if (err == MP_OKAY) err = mp_sqr(&t1, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = T2 * a */ if (err == MP_OKAY) err = mp_mulmod(&t2, a, modulus, &t1); /* T2 = X * X */ if (err == MP_OKAY) err = mp_sqr(x, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = T2 + T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = T2 + T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = T2 + T1 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } } else #endif /* WOLFSSL_CUSTOM_CURVES */ { /* assumes "a" == 3 */ (void)a; /* T2 = X - T1 */ if (err == MP_OKAY) err = mp_sub(x, &t1, &t2); if (err == MP_OKAY) { if (mp_isneg(&t2)) err = mp_add(&t2, modulus, &t2); } /* T1 = X + T1 */ if (err == MP_OKAY) err = mp_add(&t1, x, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T2 = T1 * T2 */ if (err == MP_OKAY) err = mp_mul(&t1, &t2, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T1 = 2T2 */ if (err == MP_OKAY) err = mp_add(&t2, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } /* T1 = T1 + T2 */ if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); if (err == MP_OKAY) { if (mp_cmp(&t1, modulus) != MP_LT) err = mp_sub(&t1, modulus, &t1); } } /* Y = 2Y */ if (err == MP_OKAY) err = mp_add(y, y, y); if (err == MP_OKAY) { if (mp_cmp(y, modulus) != MP_LT) err = mp_sub(y, modulus, y); } /* Y = Y * Y */ if (err == MP_OKAY) err = mp_sqr(y, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); /* T2 = Y * Y */ if (err == MP_OKAY) err = mp_sqr(y, &t2); if (err == MP_OKAY) err = mp_montgomery_reduce(&t2, modulus, mp); /* T2 = T2/2 */ if (err == MP_OKAY) { if (mp_isodd(&t2) == MP_YES) err = mp_add(&t2, modulus, &t2); } if (err == MP_OKAY) err = mp_div_2(&t2, &t2); /* Y = Y * X */ if (err == MP_OKAY) err = mp_mul(y, x, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); /* X = T1 * T1 */ if (err == MP_OKAY) err = mp_sqr(&t1, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); /* X = X - Y */ if (err == MP_OKAY) err = mp_sub(x, y, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* X = X - Y */ if (err == MP_OKAY) err = mp_sub(x, y, x); if (err == MP_OKAY) { if (mp_isneg(x)) err = mp_add(x, modulus, x); } /* Y = Y - X */ if (err == MP_OKAY) err = mp_sub(y, x, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } /* Y = Y * T1 */ if (err == MP_OKAY) err = mp_mul(y, &t1, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); /* Y = Y - T2 */ if (err == MP_OKAY) err = mp_sub(y, &t2, y); if (err == MP_OKAY) { if (mp_isneg(y)) err = mp_add(y, modulus, y); } #ifdef ALT_ECC_SIZE if (err == MP_OKAY) err = mp_copy(x, R->x); if (err == MP_OKAY) err = mp_copy(y, R->y); if (err == MP_OKAY) err = mp_copy(z, R->z); #endif /* clean up */ mp_clear(&t1); mp_clear(&t2); return err; #else if (P == NULL || R == NULL || modulus == NULL) return ECC_BAD_ARG_E; (void)a; (void)mp; return sp_ecc_proj_dbl_point_256(P->x, P->y, P->z, R->x, R->y, R->z); #endif } /** Map a projective jacbobian point back to affine space P [in/out] The point to map modulus The modulus of the field the ECC curve is in mp The "b" value from montgomery_setup() return MP_OKAY on success */ int ecc_map(ecc_point* P, mp_int* modulus, mp_digit mp) { #ifndef WOLFSSL_SP_MATH mp_int t1, t2; #ifdef ALT_ECC_SIZE mp_int rx, ry, rz; #endif mp_int *x, *y, *z; int err; if (P == NULL || modulus == NULL) return ECC_BAD_ARG_E; /* special case for point at infinity */ if (mp_cmp_d(P->z, 0) == MP_EQ) { err = mp_set(P->x, 0); if (err == MP_OKAY) err = mp_set(P->y, 0); if (err == MP_OKAY) err = mp_set(P->z, 1); return err; } if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return MEMORY_E; } #ifdef ALT_ECC_SIZE /* Use local stack variable */ x = &rx; y = &ry; z = &rz; if ((err = mp_init_multi(x, y, z, NULL, NULL, NULL)) != MP_OKAY) { goto done; } if (err == MP_OKAY) err = mp_copy(P->x, x); if (err == MP_OKAY) err = mp_copy(P->y, y); if (err == MP_OKAY) err = mp_copy(P->z, z); if (err != MP_OKAY) { goto done; } #else /* Use destination directly */ x = P->x; y = P->y; z = P->z; #endif /* first map z back to normal */ err = mp_montgomery_reduce(z, modulus, mp); /* get 1/z */ if (err == MP_OKAY) err = mp_invmod(z, modulus, &t1); /* get 1/z^2 and 1/z^3 */ if (err == MP_OKAY) err = mp_sqr(&t1, &t2); if (err == MP_OKAY) err = mp_mod(&t2, modulus, &t2); if (err == MP_OKAY) err = mp_mul(&t1, &t2, &t1); if (err == MP_OKAY) err = mp_mod(&t1, modulus, &t1); /* multiply against x/y */ if (err == MP_OKAY) err = mp_mul(x, &t2, x); if (err == MP_OKAY) err = mp_montgomery_reduce(x, modulus, mp); if (err == MP_OKAY) err = mp_mul(y, &t1, y); if (err == MP_OKAY) err = mp_montgomery_reduce(y, modulus, mp); if (err == MP_OKAY) err = mp_set(z, 1); #ifdef ALT_ECC_SIZE /* return result */ if (err == MP_OKAY) err = mp_copy(x, P->x); if (err == MP_OKAY) err = mp_copy(y, P->y); if (err == MP_OKAY) err = mp_copy(z, P->z); done: #endif /* clean up */ mp_clear(&t1); mp_clear(&t2); return err; #else if (P == NULL || modulus == NULL) return ECC_BAD_ARG_E; (void)mp; return sp_ecc_map_256(P->x, P->y, P->z); #endif } #endif /* !WOLFSSL_SP_MATH || WOLFSSL_PUBLIC_ECC_ADD_DBL */ #if !defined(FREESCALE_LTC_ECC) #if !defined(FP_ECC) || !defined(WOLFSSL_SP_MATH) /** Perform a point multiplication k The scalar to multiply by G The base point R [out] Destination for kG a ECC curve parameter a modulus The modulus of the field the ECC curve is in map Boolean whether to map back to affine or not (1==map, 0 == leave in projective) return MP_OKAY on success */ #ifdef FP_ECC static int normal_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map, void* heap) #else int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map, void* heap) #endif { #ifndef WOLFSSL_SP_MATH #ifndef ECC_TIMING_RESISTANT /* size of sliding window, don't change this! */ #define WINSIZE 4 #define M_POINTS 8 int first = 1, bitbuf = 0, bitcpy = 0, j; #else #define M_POINTS 3 #endif ecc_point *tG, *M[M_POINTS]; int i, err; mp_int mu; mp_digit mp; mp_digit buf; int bitcnt = 0, mode = 0, digidx = 0; if (k == NULL || G == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } /* init variables */ tG = NULL; XMEMSET(M, 0, sizeof(M)); /* init montgomery reduction */ if ((err = mp_montgomery_setup(modulus, &mp)) != MP_OKAY) { return err; } if ((err = mp_init(&mu)) != MP_OKAY) { return err; } if ((err = mp_montgomery_calc_normalization(&mu, modulus)) != MP_OKAY) { mp_clear(&mu); return err; } /* alloc ram for window temps */ for (i = 0; i < M_POINTS; i++) { M[i] = wc_ecc_new_point_h(heap); if (M[i] == NULL) { mp_clear(&mu); err = MEMORY_E; goto exit; } } /* make a copy of G in case R==G */ tG = wc_ecc_new_point_h(heap); if (tG == NULL) err = MEMORY_E; /* tG = G and convert to montgomery */ if (err == MP_OKAY) { if (mp_cmp_d(&mu, 1) == MP_EQ) { err = mp_copy(G->x, tG->x); if (err == MP_OKAY) err = mp_copy(G->y, tG->y); if (err == MP_OKAY) err = mp_copy(G->z, tG->z); } else { err = mp_mulmod(G->x, &mu, modulus, tG->x); if (err == MP_OKAY) err = mp_mulmod(G->y, &mu, modulus, tG->y); if (err == MP_OKAY) err = mp_mulmod(G->z, &mu, modulus, tG->z); } } /* done with mu */ mp_clear(&mu); #ifndef ECC_TIMING_RESISTANT /* calc the M tab, which holds kG for k==8..15 */ /* M[0] == 8G */ if (err == MP_OKAY) err = ecc_projective_dbl_point(tG, M[0], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[0], M[0], a, modulus, mp); /* now find (8+k)G for k=1..7 */ if (err == MP_OKAY) for (j = 9; j < 16; j++) { err = ecc_projective_add_point(M[j-9], tG, M[j-M_POINTS], a, modulus, mp); if (err != MP_OKAY) break; } /* setup sliding window */ if (err == MP_OKAY) { mode = 0; bitcnt = 1; buf = 0; digidx = get_digit_count(k) - 1; bitcpy = bitbuf = 0; first = 1; /* perform ops */ for (;;) { /* grab next digit as required */ if (--bitcnt == 0) { if (digidx == -1) { break; } buf = get_digit(k, digidx); bitcnt = (int) DIGIT_BIT; --digidx; } /* grab the next msb from the ltiplicand */ i = (int)(buf >> (DIGIT_BIT - 1)) & 1; buf <<= 1; /* skip leading zero bits */ if (mode == 0 && i == 0) continue; /* if the bit is zero and mode == 1 then we double */ if (mode == 1 && i == 0) { err = ecc_projective_dbl_point(R, R, a, modulus, mp); if (err != MP_OKAY) break; continue; } /* else we add it to the window */ bitbuf |= (i << (WINSIZE - ++bitcpy)); mode = 2; if (bitcpy == WINSIZE) { /* if this is the first window we do a simple copy */ if (first == 1) { /* R = kG [k = first window] */ err = mp_copy(M[bitbuf-M_POINTS]->x, R->x); if (err != MP_OKAY) break; err = mp_copy(M[bitbuf-M_POINTS]->y, R->y); if (err != MP_OKAY) break; err = mp_copy(M[bitbuf-M_POINTS]->z, R->z); first = 0; } else { /* normal window */ /* ok window is filled so double as required and add */ /* double first */ for (j = 0; j < WINSIZE; j++) { err = ecc_projective_dbl_point(R, R, a, modulus, mp); if (err != MP_OKAY) break; } if (err != MP_OKAY) break; /* out of first for(;;) */ /* then add, bitbuf will be 8..15 [8..2^WINSIZE] guaranteed */ err = ecc_projective_add_point(R, M[bitbuf-M_POINTS], R, a, modulus, mp); } if (err != MP_OKAY) break; /* empty window and reset */ bitcpy = bitbuf = 0; mode = 1; } } } /* if bits remain then double/add */ if (err == MP_OKAY) { if (mode == 2 && bitcpy > 0) { /* double then add */ for (j = 0; j < bitcpy; j++) { /* only double if we have had at least one add first */ if (first == 0) { err = ecc_projective_dbl_point(R, R, a, modulus, mp); if (err != MP_OKAY) break; } bitbuf <<= 1; if ((bitbuf & (1 << WINSIZE)) != 0) { if (first == 1) { /* first add, so copy */ err = mp_copy(tG->x, R->x); if (err != MP_OKAY) break; err = mp_copy(tG->y, R->y); if (err != MP_OKAY) break; err = mp_copy(tG->z, R->z); if (err != MP_OKAY) break; first = 0; } else { /* then add */ err = ecc_projective_add_point(R, tG, R, a, modulus, mp); if (err != MP_OKAY) break; } } } } } #undef WINSIZE #else /* ECC_TIMING_RESISTANT */ /* calc the M tab */ /* M[0] == G */ if (err == MP_OKAY) err = mp_copy(tG->x, M[0]->x); if (err == MP_OKAY) err = mp_copy(tG->y, M[0]->y); if (err == MP_OKAY) err = mp_copy(tG->z, M[0]->z); /* M[1] == 2G */ if (err == MP_OKAY) err = ecc_projective_dbl_point(tG, M[1], a, modulus, mp); /* setup sliding window */ mode = 0; bitcnt = 1; buf = 0; digidx = get_digit_count(k) - 1; /* perform ops */ if (err == MP_OKAY) { for (;;) { /* grab next digit as required */ if (--bitcnt == 0) { if (digidx == -1) { break; } buf = get_digit(k, digidx); bitcnt = (int)DIGIT_BIT; --digidx; } /* grab the next msb from the multiplicand */ i = (buf >> (DIGIT_BIT - 1)) & 1; buf <<= 1; if (mode == 0 && i == 0) { /* timing resistant - dummy operations */ if (err == MP_OKAY) err = ecc_projective_add_point(M[0], M[1], M[2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[1], M[2], a, modulus, mp); if (err == MP_OKAY) continue; } if (mode == 0 && i == 1) { mode = 1; /* timing resistant - dummy operations */ if (err == MP_OKAY) err = ecc_projective_add_point(M[0], M[1], M[2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[1], M[2], a, modulus, mp); if (err == MP_OKAY) continue; } if (err == MP_OKAY) err = ecc_projective_add_point(M[0], M[1], M[i^1], a, modulus, mp); #ifdef WC_NO_CACHE_RESISTANT if (err == MP_OKAY) err = ecc_projective_dbl_point(M[i], M[i], a, modulus, mp); #else /* instead of using M[i] for double, which leaks key bit to cache * monitor, use M[2] as temp, make sure address calc is constant, * keep M[0] and M[1] in cache */ if (err == MP_OKAY) err = mp_copy((mp_int*) ( ((wolfssl_word)M[0]->x & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->x & wc_off_on_addr[i])), M[2]->x); if (err == MP_OKAY) err = mp_copy((mp_int*) ( ((wolfssl_word)M[0]->y & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->y & wc_off_on_addr[i])), M[2]->y); if (err == MP_OKAY) err = mp_copy((mp_int*) ( ((wolfssl_word)M[0]->z & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->z & wc_off_on_addr[i])), M[2]->z); if (err == MP_OKAY) err = ecc_projective_dbl_point(M[2], M[2], a, modulus, mp); /* copy M[2] back to M[i] */ if (err == MP_OKAY) err = mp_copy(M[2]->x, (mp_int*) ( ((wolfssl_word)M[0]->x & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->x & wc_off_on_addr[i])) ); if (err == MP_OKAY) err = mp_copy(M[2]->y, (mp_int*) ( ((wolfssl_word)M[0]->y & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->y & wc_off_on_addr[i])) ); if (err == MP_OKAY) err = mp_copy(M[2]->z, (mp_int*) ( ((wolfssl_word)M[0]->z & wc_off_on_addr[i^1]) + ((wolfssl_word)M[1]->z & wc_off_on_addr[i])) ); if (err != MP_OKAY) break; #endif /* WC_NO_CACHE_RESISTANT */ } /* end for */ } /* copy result out */ if (err == MP_OKAY) err = mp_copy(M[0]->x, R->x); if (err == MP_OKAY) err = mp_copy(M[0]->y, R->y); if (err == MP_OKAY) err = mp_copy(M[0]->z, R->z); #endif /* ECC_TIMING_RESISTANT */ /* map R back from projective space */ if (err == MP_OKAY && map) err = ecc_map(R, modulus, mp); exit: /* done */ wc_ecc_del_point_h(tG, heap); for (i = 0; i < M_POINTS; i++) { wc_ecc_del_point_h(M[i], heap); } return err; #else if (k == NULL || G == NULL || R == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } (void)a; return sp_ecc_mulmod_256(k, G, R, map, heap); #endif } #endif /* !FP_ECC || !WOLFSSL_SP_MATH */ #endif /* !FREESCALE_LTC_ECC */ /** ECC Fixed Point mulmod global k The multiplicand G Base point to multiply R [out] Destination of product a ECC curve parameter a modulus The modulus for the curve map [boolean] If non-zero maps the point back to affine co-ordinates, otherwise it's left in jacobian-montgomery form return MP_OKAY if successful */ int wc_ecc_mulmod(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map) { return wc_ecc_mulmod_ex(k, G, R, a, modulus, map, NULL); } #endif /* !WOLFSSL_ATECC508A */ /** * use a heap hint when creating new ecc_point * return an allocated point on success or NULL on failure */ ecc_point* wc_ecc_new_point_h(void* heap) { ecc_point* p; (void)heap; p = (ecc_point*)XMALLOC(sizeof(ecc_point), heap, DYNAMIC_TYPE_ECC); if (p == NULL) { return NULL; } XMEMSET(p, 0, sizeof(ecc_point)); #ifndef ALT_ECC_SIZE if (mp_init_multi(p->x, p->y, p->z, NULL, NULL, NULL) != MP_OKAY) { XFREE(p, heap, DYNAMIC_TYPE_ECC); return NULL; } #else p->x = (mp_int*)&p->xyz[0]; p->y = (mp_int*)&p->xyz[1]; p->z = (mp_int*)&p->xyz[2]; alt_fp_init(p->x); alt_fp_init(p->y); alt_fp_init(p->z); #endif return p; } /** Allocate a new ECC point return A newly allocated point or NULL on error */ ecc_point* wc_ecc_new_point(void) { return wc_ecc_new_point_h(NULL); } void wc_ecc_del_point_h(ecc_point* p, void* heap) { /* prevents free'ing null arguments */ if (p != NULL) { mp_clear(p->x); mp_clear(p->y); mp_clear(p->z); XFREE(p, heap, DYNAMIC_TYPE_ECC); } (void)heap; } /** Free an ECC point from memory p The point to free */ void wc_ecc_del_point(ecc_point* p) { wc_ecc_del_point_h(p, NULL); } /** Copy the value of a point to an other one p The point to copy r The created point */ int wc_ecc_copy_point(ecc_point* p, ecc_point *r) { int ret; /* prevents null arguments */ if (p == NULL || r == NULL) return ECC_BAD_ARG_E; ret = mp_copy(p->x, r->x); if (ret != MP_OKAY) return ret; ret = mp_copy(p->y, r->y); if (ret != MP_OKAY) return ret; ret = mp_copy(p->z, r->z); if (ret != MP_OKAY) return ret; return MP_OKAY; } /** Compare the value of a point with an other one a The point to compare b The other point to compare return MP_EQ if equal, MP_LT/MP_GT if not, < 0 in case of error */ int wc_ecc_cmp_point(ecc_point* a, ecc_point *b) { int ret; /* prevents null arguments */ if (a == NULL || b == NULL) return BAD_FUNC_ARG; ret = mp_cmp(a->x, b->x); if (ret != MP_EQ) return ret; ret = mp_cmp(a->y, b->y); if (ret != MP_EQ) return ret; ret = mp_cmp(a->z, b->z); if (ret != MP_EQ) return ret; return MP_EQ; } /** Returns whether an ECC idx is valid or not n The idx number to check return 1 if valid, 0 if not */ int wc_ecc_is_valid_idx(int n) { int x; for (x = 0; ecc_sets[x].size != 0; x++) ; /* -1 is a valid index --- indicating that the domain params were supplied by the user */ if ((n >= ECC_CUSTOM_IDX) && (n < x)) { return 1; } return 0; } int wc_ecc_get_curve_idx(int curve_id) { int curve_idx; for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) { if (curve_id == ecc_sets[curve_idx].id) break; } if (ecc_sets[curve_idx].size == 0) { return ECC_CURVE_INVALID; } return curve_idx; } int wc_ecc_get_curve_id(int curve_idx) { if (wc_ecc_is_valid_idx(curve_idx)) { return ecc_sets[curve_idx].id; } return ECC_CURVE_INVALID; } /* Returns the curve size that corresponds to a given ecc_curve_id identifier * * id curve id, from ecc_curve_id enum in ecc.h * return curve size, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_size_from_id(int curve_id) { int curve_idx = wc_ecc_get_curve_idx(curve_id); if (curve_idx == ECC_CURVE_INVALID) return ECC_BAD_ARG_E; return ecc_sets[curve_idx].size; } /* Returns the curve index that corresponds to a given curve name in * ecc_sets[] of ecc.c * * name curve name, from ecc_sets[].name in ecc.c * return curve index in ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_idx_from_name(const char* curveName) { int curve_idx; word32 len; if (curveName == NULL) return BAD_FUNC_ARG; len = (word32)XSTRLEN(curveName); for (curve_idx = 0; ecc_sets[curve_idx].size != 0; curve_idx++) { if (ecc_sets[curve_idx].name && XSTRNCASECMP(ecc_sets[curve_idx].name, curveName, len) == 0) { break; } } if (ecc_sets[curve_idx].size == 0) { WOLFSSL_MSG("ecc_set curve name not found"); return ECC_CURVE_INVALID; } return curve_idx; } /* Returns the curve size that corresponds to a given curve name, * as listed in ecc_sets[] of ecc.c. * * name curve name, from ecc_sets[].name in ecc.c * return curve size, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_size_from_name(const char* curveName) { int curve_idx; if (curveName == NULL) return BAD_FUNC_ARG; curve_idx = wc_ecc_get_curve_idx_from_name(curveName); if (curve_idx < 0) return curve_idx; return ecc_sets[curve_idx].size; } /* Returns the curve id that corresponds to a given curve name, * as listed in ecc_sets[] of ecc.c. * * name curve name, from ecc_sets[].name in ecc.c * return curve id, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_id_from_name(const char* curveName) { int curve_idx; if (curveName == NULL) return BAD_FUNC_ARG; curve_idx = wc_ecc_get_curve_idx_from_name(curveName); if (curve_idx < 0) return curve_idx; return ecc_sets[curve_idx].id; } /* Compares a curve parameter (hex, from ecc_sets[]) to given input * parameter (byte array) for equality. * * Returns MP_EQ on success, negative on error */ static int wc_ecc_cmp_param(const char* curveParam, const byte* param, word32 paramSz) { int err = MP_OKAY; mp_int a, b; if (param == NULL || curveParam == NULL) return BAD_FUNC_ARG; if ((err = mp_init_multi(&a, &b, NULL, NULL, NULL, NULL)) != MP_OKAY) return err; if (err == MP_OKAY) err = mp_read_unsigned_bin(&a, param, paramSz); if (err == MP_OKAY) err = mp_read_radix(&b, curveParam, MP_RADIX_HEX); if (err == MP_OKAY) { if (mp_cmp(&a, &b) != MP_EQ) { err = -1; } else { err = MP_EQ; } } mp_clear(&a); mp_clear(&b); return err; } /* Returns the curve id in ecc_sets[] that corresponds to a given set of * curve parameters. * * fieldSize the field size in bits * prime prime of the finite field * primeSz size of prime in octets * Af first coefficient a of the curve * AfSz size of Af in octets * Bf second coefficient b of the curve * BfSz size of Bf in octets * order curve order * orderSz size of curve in octets * Gx affine x coordinate of base point * GxSz size of Gx in octets * Gy affine y coordinate of base point * GySz size of Gy in octets * cofactor curve cofactor * * return curve id, from ecc_sets[] on success, negative on error */ int wc_ecc_get_curve_id_from_params(int fieldSize, const byte* prime, word32 primeSz, const byte* Af, word32 AfSz, const byte* Bf, word32 BfSz, const byte* order, word32 orderSz, const byte* Gx, word32 GxSz, const byte* Gy, word32 GySz, int cofactor) { int idx; int curveSz; if (prime == NULL || Af == NULL || Bf == NULL || order == NULL || Gx == NULL || Gy == NULL) return BAD_FUNC_ARG; curveSz = (fieldSize + 1) / 8; /* round up */ for (idx = 0; ecc_sets[idx].size != 0; idx++) { if (curveSz == ecc_sets[idx].size) { if ((wc_ecc_cmp_param(ecc_sets[idx].prime, prime, primeSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Af, Af, AfSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Bf, Bf, BfSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].order, order, orderSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Gx, Gx, GxSz) == MP_EQ) && (wc_ecc_cmp_param(ecc_sets[idx].Gy, Gy, GySz) == MP_EQ) && (cofactor == ecc_sets[idx].cofactor)) { break; } } } if (ecc_sets[idx].size == 0) return ECC_CURVE_INVALID; return ecc_sets[idx].id; } #ifdef WOLFSSL_ASYNC_CRYPT static INLINE int wc_ecc_alloc_mpint(ecc_key* key, mp_int** mp) { if (key == NULL || mp == NULL) return BAD_FUNC_ARG; if (*mp == NULL) { *mp = (mp_int*)XMALLOC(sizeof(mp_int), key->heap, DYNAMIC_TYPE_BIGINT); if (*mp == NULL) { return MEMORY_E; } XMEMSET(*mp, 0, sizeof(mp_int)); } return 0; } static INLINE void wc_ecc_free_mpint(ecc_key* key, mp_int** mp) { if (key && mp && *mp) { mp_clear(*mp); XFREE(*mp, key->heap, DYNAMIC_TYPE_BIGINT); *mp = NULL; } } static int wc_ecc_alloc_async(ecc_key* key) { int err = wc_ecc_alloc_mpint(key, &key->r); if (err == 0) err = wc_ecc_alloc_mpint(key, &key->s); return err; } static void wc_ecc_free_async(ecc_key* key) { wc_ecc_free_mpint(key, &key->r); wc_ecc_free_mpint(key, &key->s); #ifdef HAVE_CAVIUM_V wc_ecc_free_mpint(key, &key->e); wc_ecc_free_mpint(key, &key->signK); #endif /* HAVE_CAVIUM_V */ } #endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef HAVE_ECC_DHE /** Create an ECC shared secret between two keys private_key The private ECC key (heap hint based off of private key) public_key The public key out [out] Destination of the shared secret Conforms to EC-DH from ANSI X9.63 outlen [in/out] The max size and resulting size of the shared secret return MP_OKAY if successful */ int wc_ecc_shared_secret(ecc_key* private_key, ecc_key* public_key, byte* out, word32* outlen) { int err; if (private_key == NULL || public_key == NULL || out == NULL || outlen == NULL) { return BAD_FUNC_ARG; } #ifdef WOLF_CRYPTO_DEV if (private_key->devId != INVALID_DEVID) { err = wc_CryptoDev_Ecdh(private_key, public_key, out, outlen); if (err != NOT_COMPILED_IN) return err; } #endif /* type valid? */ if (private_key->type != ECC_PRIVATEKEY && private_key->type != ECC_PRIVATEKEY_ONLY) { return ECC_BAD_ARG_E; } /* Verify domain params supplied */ if (wc_ecc_is_valid_idx(private_key->idx) == 0 || wc_ecc_is_valid_idx(public_key->idx) == 0) { return ECC_BAD_ARG_E; } /* Verify curve id matches */ if (private_key->dp->id != public_key->dp->id) { return ECC_BAD_ARG_E; } #ifdef WOLFSSL_ATECC508A err = atcatls_ecdh(private_key->slot, public_key->pubkey_raw, out); if (err != ATCA_SUCCESS) { err = BAD_COND_E; } *outlen = private_key->dp->size; #else err = wc_ecc_shared_secret_ex(private_key, &public_key->pubkey, out, outlen); #endif /* WOLFSSL_ATECC508A */ return err; } #ifndef WOLFSSL_ATECC508A static int wc_ecc_shared_secret_gen_sync(ecc_key* private_key, ecc_point* point, byte* out, word32* outlen, ecc_curve_spec* curve) { int err; #ifndef WOLFSSL_SP_MATH ecc_point* result = NULL; word32 x = 0; #endif mp_int* k = &private_key->k; #ifdef HAVE_ECC_CDH mp_int k_lcl; /* if cofactor flag has been set */ if (private_key->flags & WC_ECC_FLAG_COFACTOR) { mp_digit cofactor = (mp_digit)private_key->dp->cofactor; /* only perform cofactor calc if not equal to 1 */ if (cofactor != 1) { k = &k_lcl; if (mp_init(k) != MP_OKAY) return MEMORY_E; /* multiply cofactor times private key "k" */ err = mp_mul_d(&private_key->k, cofactor, k); if (err != MP_OKAY) { mp_clear(k); return err; } } } #endif #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (private_key->idx != ECC_CUSTOM_IDX && ecc_sets[private_key->idx].id == ECC_SECP256R1) { err = sp_ecc_secret_gen_256(k, point, out, outlen, private_key->heap); } else #endif #endif #ifdef WOLFSSL_SP_MATH { err = WC_KEY_SIZE_E; (void)curve; } #else { /* make new point */ result = wc_ecc_new_point_h(private_key->heap); if (result == NULL) { #ifdef HAVE_ECC_CDH if (k == &k_lcl) mp_clear(k); #endif return MEMORY_E; } err = wc_ecc_mulmod_ex(k, point, result, curve->Af, curve->prime, 1, private_key->heap); if (err == MP_OKAY) { x = mp_unsigned_bin_size(curve->prime); if (*outlen < x) { err = BUFFER_E; } } if (err == MP_OKAY) { XMEMSET(out, 0, x); err = mp_to_unsigned_bin(result->x,out + (x - mp_unsigned_bin_size(result->x))); } *outlen = x; wc_ecc_del_point_h(result, private_key->heap); } #endif #ifdef HAVE_ECC_CDH if (k == &k_lcl) mp_clear(k); #endif return err; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) static int wc_ecc_shared_secret_gen_async(ecc_key* private_key, ecc_point* point, byte* out, word32 *outlen, ecc_curve_spec* curve) { int err; #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) #ifdef HAVE_CAVIUM_V /* verify the curve is supported by hardware */ if (NitroxEccIsCurveSupported(private_key)) #endif { word32 keySz = private_key->dp->size; /* sync public key x/y */ err = wc_mp_to_bigint_sz(&private_key->k, &private_key->k.raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(point->x, &point->x->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(point->y, &point->y->raw, keySz); #ifdef HAVE_CAVIUM_V /* allocate buffer for output */ if (err == MP_OKAY) err = wc_ecc_alloc_mpint(private_key, &private_key->e); if (err == MP_OKAY) err = wc_bigint_alloc(&private_key->e->raw, NitroxEccGetSize(private_key)*2); if (err == MP_OKAY) err = NitroxEcdh(private_key, &private_key->k.raw, &point->x->raw, &point->y->raw, private_key->e->raw.buf, &private_key->e->raw.len, &curve->prime->raw); #else if (err == MP_OKAY) err = wc_ecc_curve_load(private_key->dp, &curve, ECC_CURVE_FIELD_BF); if (err == MP_OKAY) err = IntelQaEcdh(&private_key->asyncDev, &private_key->k.raw, &point->x->raw, &point->y->raw, out, outlen, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, private_key->dp->cofactor); #endif return err; } #elif defined(WOLFSSL_ASYNC_CRYPT_TEST) if (wc_AsyncTestInit(&private_key->asyncDev, ASYNC_TEST_ECC_SHARED_SEC)) { WC_ASYNC_TEST* testDev = &private_key->asyncDev.test; testDev->eccSharedSec.private_key = private_key; testDev->eccSharedSec.public_point = point; testDev->eccSharedSec.out = out; testDev->eccSharedSec.outLen = outlen; return WC_PENDING_E; } #endif /* use sync in other cases */ err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen, curve); return err; } #endif /* WOLFSSL_ASYNC_CRYPT */ int wc_ecc_shared_secret_gen(ecc_key* private_key, ecc_point* point, byte* out, word32 *outlen) { int err; DECLARE_CURVE_SPECS(2) if (private_key == NULL || point == NULL || out == NULL || outlen == NULL) { return BAD_FUNC_ARG; } /* load curve info */ err = wc_ecc_curve_load(private_key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF)); if (err != MP_OKAY) return err; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { err = wc_ecc_shared_secret_gen_async(private_key, point, out, outlen, curve); } else #endif { err = wc_ecc_shared_secret_gen_sync(private_key, point, out, outlen, curve); } wc_ecc_curve_free(curve); return err; } /** Create an ECC shared secret between private key and public point private_key The private ECC key (heap hint based on private key) point The point to use (public key) out [out] Destination of the shared secret Conforms to EC-DH from ANSI X9.63 outlen [in/out] The max size and resulting size of the shared secret return MP_OKAY if successful */ int wc_ecc_shared_secret_ex(ecc_key* private_key, ecc_point* point, byte* out, word32 *outlen) { int err; if (private_key == NULL || point == NULL || out == NULL || outlen == NULL) { return BAD_FUNC_ARG; } /* type valid? */ if (private_key->type != ECC_PRIVATEKEY && private_key->type != ECC_PRIVATEKEY_ONLY) { return ECC_BAD_ARG_E; } /* Verify domain params supplied */ if (wc_ecc_is_valid_idx(private_key->idx) == 0) return ECC_BAD_ARG_E; switch(private_key->state) { case ECC_STATE_NONE: case ECC_STATE_SHARED_SEC_GEN: private_key->state = ECC_STATE_SHARED_SEC_GEN; err = wc_ecc_shared_secret_gen(private_key, point, out, outlen); if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_SHARED_SEC_RES: private_key->state = ECC_STATE_SHARED_SEC_RES; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (private_key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #ifdef HAVE_CAVIUM_V /* verify the curve is supported by hardware */ if (NitroxEccIsCurveSupported(private_key)) { /* copy output */ *outlen = private_key->dp->size; XMEMCPY(out, private_key->e->raw.buf, *outlen); } #endif /* HAVE_CAVIUM_V */ } #endif /* WOLFSSL_ASYNC_CRYPT */ err = 0; break; default: err = BAD_STATE_E; } /* switch */ /* if async pending then return and skip done cleanup below */ if (err == WC_PENDING_E) { private_key->state++; return err; } /* cleanup */ #ifdef WOLFSSL_ASYNC_CRYPT wc_ecc_free_async(private_key); #endif private_key->state = ECC_STATE_NONE; return err; } #endif /* !WOLFSSL_ATECC508A */ #endif /* HAVE_ECC_DHE */ #ifndef WOLFSSL_ATECC508A /* return 1 if point is at infinity, 0 if not, < 0 on error */ int wc_ecc_point_is_at_infinity(ecc_point* p) { if (p == NULL) return BAD_FUNC_ARG; if (get_digit_count(p->x) == 0 && get_digit_count(p->y) == 0) return 1; return 0; } #ifndef WOLFSSL_SP_MATH /* generate random and ensure its greater than 0 and less than order */ static int wc_ecc_gen_k(WC_RNG* rng, int size, mp_int* k, mp_int* order) { int err; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_MAXSIZE_GEN]; #endif #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_MAXSIZE_GEN, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /*generate 8 extra bytes to mitigate bias from the modulo operation below*/ /*see section A.1.2 in 'Suite B Implementor's Guide to FIPS 186-3 (ECDSA)'*/ size += 8; /* make up random string */ err = wc_RNG_GenerateBlock(rng, buf, size); /* load random buffer data into k */ if (err == 0) err = mp_read_unsigned_bin(k, (byte*)buf, size); /* the key should be smaller than the order of base point */ if (err == MP_OKAY) { if (mp_cmp(k, order) != MP_LT) { err = mp_mod(k, order, k); } } /* quick sanity check to make sure we're not dealing with a 0 key */ if (err == MP_OKAY) { if (mp_iszero(k) == MP_YES) err = MP_ZERO_E; } ForceZero(buf, ECC_MAXSIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return err; } #endif #endif /* !WOLFSSL_ATECC508A */ static INLINE void wc_ecc_reset(ecc_key* key) { /* make sure required key variables are reset */ key->state = ECC_STATE_NONE; } /* create the public ECC key from a private key * * key an initialized private key to generate public part from * curveIn [in]curve for key, can be NULL * pubOut [out]ecc_point holding the public key, if NULL then public key part * is cached in key instead. * * Note this function is local to the file because of the argument type * ecc_curve_spec. Having this argument allows for not having to load the * curve type multiple times when generating a key with wc_ecc_make_key(). * * returns MP_OKAY on success */ static int wc_ecc_make_pub_ex(ecc_key* key, ecc_curve_spec* curveIn, ecc_point* pubOut) { int err = MP_OKAY; #ifndef WOLFSSL_ATECC508A #ifndef WOLFSSL_SP_MATH ecc_point* base = NULL; #endif ecc_point* pub; DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT) #endif if (key == NULL) { return BAD_FUNC_ARG; } #ifndef WOLFSSL_ATECC508A /* if ecc_point passed in then use it as output for public key point */ if (pubOut != NULL) { pub = pubOut; } else { /* caching public key making it a ECC_PRIVATEKEY instead of ECC_PRIVATEKEY_ONLY */ pub = &key->pubkey; key->type = ECC_PRIVATEKEY_ONLY; } /* avoid loading the curve unless it is not passed in */ if (curveIn != NULL) { curve = curveIn; } else { /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); } if (err == MP_OKAY) { #ifndef ALT_ECC_SIZE err = mp_init_multi(pub->x, pub->y, pub->z, NULL, NULL, NULL); #else pub->x = (mp_int*)&pub->xyz[0]; pub->y = (mp_int*)&pub->xyz[1]; pub->z = (mp_int*)&pub->xyz[2]; alt_fp_init(pub->x); alt_fp_init(pub->y); alt_fp_init(pub->z); #endif } #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { if (err == MP_OKAY) err = sp_ecc_mulmod_base_256(&key->k, pub, 1, key->heap); } else #endif #endif #ifdef WOLFSSL_SP_MATH err = WC_KEY_SIZE_E; #else { if (err == MP_OKAY) { base = wc_ecc_new_point_h(key->heap); if (base == NULL) err = MEMORY_E; } /* read in the x/y for this key */ if (err == MP_OKAY) err = mp_copy(curve->Gx, base->x); if (err == MP_OKAY) err = mp_copy(curve->Gy, base->y); if (err == MP_OKAY) err = mp_set(base->z, 1); /* make the public key */ if (err == MP_OKAY) { err = wc_ecc_mulmod_ex(&key->k, base, pub, curve->Af, curve->prime, 1, key->heap); } wc_ecc_del_point_h(base, key->heap); } #endif #ifdef WOLFSSL_VALIDATE_ECC_KEYGEN /* validate the public key, order * pubkey = point at infinity */ if (err == MP_OKAY) err = ecc_check_pubkey_order(key, pub, curve->Af, curve->prime, curve->order); #endif /* WOLFSSL_VALIDATE_KEYGEN */ if (err != MP_OKAY) { /* clean up if failed */ #ifndef ALT_ECC_SIZE mp_clear(pub->x); mp_clear(pub->y); mp_clear(pub->z); #endif } /* free up local curve */ if (curveIn == NULL) { wc_ecc_curve_free(curve); } #endif /* WOLFSSL_ATECC508A */ /* change key state if public part is cached */ if (key->type == ECC_PRIVATEKEY_ONLY && pubOut == NULL) { key->type = ECC_PRIVATEKEY; } return err; } /* create the public ECC key from a private key * * key an initialized private key to generate public part from * pubOut [out]ecc_point holding the public key, if NULL then public key part * is cached in key instead. * * * returns MP_OKAY on success */ int wc_ecc_make_pub(ecc_key* key, ecc_point* pubOut) { WOLFSSL_ENTER("wc_ecc_make_pub"); return wc_ecc_make_pub_ex(key, NULL, pubOut); } int wc_ecc_make_key_ex(WC_RNG* rng, int keysize, ecc_key* key, int curve_id) { int err; #ifndef WOLFSSL_ATECC508A DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT) #endif if (key == NULL || rng == NULL) { return BAD_FUNC_ARG; } /* make sure required variables are reset */ wc_ecc_reset(key); err = wc_ecc_set_curve(key, keysize, curve_id); if (err != 0) { return err; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #ifdef HAVE_CAVIUM /* TODO: Not implemented */ #elif defined(HAVE_INTEL_QA) /* TODO: Not implemented */ #else if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_MAKE)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->eccMake.rng = rng; testDev->eccMake.key = key; testDev->eccMake.size = keysize; testDev->eccMake.curve_id = curve_id; return WC_PENDING_E; } #endif } #endif /* WOLFSSL_ASYNC_CRYPT */ #ifdef WOLFSSL_ATECC508A key->type = ECC_PRIVATEKEY; err = atcatls_create_key(key->slot, key->pubkey_raw); if (err != ATCA_SUCCESS) { err = BAD_COND_E; } /* populate key->pubkey */ err = mp_read_unsigned_bin(key->pubkey.x, key->pubkey_raw, ECC_MAX_CRYPTO_HW_SIZE); if (err = MP_OKAY) err = mp_read_unsigned_bin(key->pubkey.y, key->pubkey_raw + ECC_MAX_CRYPTO_HW_SIZE, ECC_MAX_CRYPTO_HW_SIZE); #else #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { err = sp_ecc_make_key_256(rng, &key->k, &key->pubkey, key->heap); if (err == MP_OKAY) key->type = ECC_PRIVATEKEY; } else #endif #endif #ifdef WOLFSSL_SP_MATH err = WC_KEY_SIZE_E; #else { /* setup the key variables */ err = mp_init(&key->k); /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); /* generate k */ if (err == MP_OKAY) err = wc_ecc_gen_k(rng, key->dp->size, &key->k, curve->order); /* generate public key from k */ if (err == MP_OKAY) err = wc_ecc_make_pub_ex(key, curve, NULL); if (err == MP_OKAY) key->type = ECC_PRIVATEKEY; /* cleanup these on failure case only */ if (err != MP_OKAY) { /* clean up */ mp_forcezero(&key->k); } /* cleanup allocations */ wc_ecc_curve_free(curve); } #endif #endif /* WOLFSSL_ATECC508A */ return err; } #ifdef ECC_DUMP_OID /* Optional dump of encoded OID for adding new curves */ static int mOidDumpDone; static void wc_ecc_dump_oids(void) { int x; if (mOidDumpDone) { return; } /* find matching OID sum (based on encoded value) */ for (x = 0; ecc_sets[x].size != 0; x++) { int i; byte* oid; word32 oidSz, sum = 0; printf("ECC %s (%d):\n", ecc_sets[x].name, x); #ifdef HAVE_OID_ENCODING byte oidEnc[ECC_MAX_OID_LEN]; oid = oidEnc; oidSz = ECC_MAX_OID_LEN; printf("OID: "); for (i = 0; i < (int)ecc_sets[x].oidSz; i++) { printf("%d.", ecc_sets[x].oid[i]); } printf("\n"); EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz, oidEnc, &oidSz); #else oid = (byte*)ecc_sets[x].oid; oidSz = ecc_sets[x].oidSz; #endif printf("OID Encoded: "); for (i = 0; i < (int)oidSz; i++) { printf("0x%02X,", oid[i]); } printf("\n"); for (i = 0; i < (int)oidSz; i++) { sum += oid[i]; } printf("Sum: %d\n", sum); /* validate sum */ if (ecc_sets[x].oidSum != sum) { printf(" Sum %d Not Valid!\n", ecc_sets[x].oidSum); } } mOidDumpDone = 1; } #endif /* ECC_DUMP_OID */ /** Make a new ECC key rng An active RNG state keysize The keysize for the new key (in octets from 20 to 65 bytes) key [out] Destination of the newly created key return MP_OKAY if successful, upon error all allocated memory will be freed */ int wc_ecc_make_key(WC_RNG* rng, int keysize, ecc_key* key) { return wc_ecc_make_key_ex(rng, keysize, key, ECC_CURVE_DEF); } /* Setup dynamic pointers if using normal math for proper freeing */ int wc_ecc_init_ex(ecc_key* key, void* heap, int devId) { int ret = 0; if (key == NULL) { return BAD_FUNC_ARG; } #ifdef ECC_DUMP_OID wc_ecc_dump_oids(); #endif XMEMSET(key, 0, sizeof(ecc_key)); key->state = ECC_STATE_NONE; #if defined(PLUTON_CRYPTO_ECC) || defined(WOLF_CRYPTO_DEV) key->devId = devId; #else (void)devId; #endif #ifdef WOLFSSL_ATECC508A key->slot = atmel_ecc_alloc(); if (key->slot == ATECC_INVALID_SLOT) { return ECC_BAD_ARG_E; } #else #ifdef ALT_ECC_SIZE key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); ret = mp_init(&key->k); #else ret = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif /* ALT_ECC_SIZE */ if (ret != MP_OKAY) { return MEMORY_E; } #endif /* WOLFSSL_ATECC508A */ #ifdef WOLFSSL_HEAP_TEST key->heap = (void*)WOLFSSL_HEAP_TEST; #else key->heap = heap; #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) /* handle as async */ ret = wolfAsync_DevCtxInit(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC, key->heap, devId); #endif return ret; } int wc_ecc_init(ecc_key* key) { return wc_ecc_init_ex(key, NULL, INVALID_DEVID); } int wc_ecc_set_flags(ecc_key* key, word32 flags) { if (key == NULL) { return BAD_FUNC_ARG; } key->flags |= flags; return 0; } #ifdef HAVE_ECC_SIGN #ifndef NO_ASN #if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) static int wc_ecc_sign_hash_hw(const byte* in, word32 inlen, mp_int* r, mp_int* s, byte* out, word32 *outlen, WC_RNG* rng, ecc_key* key) { int err; #ifdef PLUTON_CRYPTO_ECC if (key->devId != INVALID_DEVID) /* use hardware */ #endif { int keysize = key->dp->size; /* Check args */ if (keysize > ECC_MAX_CRYPTO_HW_SIZE || inlen != keysize || *outlen < keysize*2) { return ECC_BAD_ARG_E; } #if defined(WOLFSSL_ATECC508A) /* Sign: Result is 32-bytes of R then 32-bytes of S */ err = atcatls_sign(key->slot, in, out); if (err != ATCA_SUCCESS) { return BAD_COND_E; } #elif defined(PLUTON_CRYPTO_ECC) { /* perform ECC sign */ word32 raw_sig_size = *outlen; err = Crypto_EccSign(in, inlen, out, &raw_sig_size); if (err != CRYPTO_RES_SUCCESS || raw_sig_size != keysize*2){ return BAD_COND_E; } } #endif /* Load R and S */ err = mp_read_unsigned_bin(r, &out[0], keysize); if (err != MP_OKAY) { return err; } err = mp_read_unsigned_bin(s, &out[keysize], keysize); if (err != MP_OKAY) { return err; } /* Check for zeros */ if (mp_iszero(r) || mp_iszero(s)) { return MP_ZERO_E; } } #ifdef PLUTON_CRYPTO_ECC else { err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s); } #endif return err; } #endif /* WOLFSSL_ATECC508A || PLUTON_CRYPTO_ECC */ /** Sign a message digest in The message digest to sign inlen The length of the digest out [out] The destination for the signature outlen [in/out] The max size and resulting size of the signature key A private ECC key return MP_OKAY if successful */ int wc_ecc_sign_hash(const byte* in, word32 inlen, byte* out, word32 *outlen, WC_RNG* rng, ecc_key* key) { int err; mp_int *r = NULL, *s = NULL; #ifndef WOLFSSL_ASYNC_CRYPT mp_int r_lcl, s_lcl; #endif if (in == NULL || out == NULL || outlen == NULL || key == NULL || rng == NULL) { return ECC_BAD_ARG_E; } #ifdef WOLF_CRYPTO_DEV if (key->devId != INVALID_DEVID) { err = wc_CryptoDev_EccSign(in, inlen, out, outlen, rng, key); if (err != NOT_COMPILED_IN) return err; } #endif #ifdef WOLFSSL_ASYNC_CRYPT err = wc_ecc_alloc_async(key); if (err != 0) return err; r = key->r; s = key->s; #else r = &r_lcl; s = &s_lcl; #endif switch(key->state) { case ECC_STATE_NONE: case ECC_STATE_SIGN_DO: key->state = ECC_STATE_SIGN_DO; if ((err = mp_init_multi(r, s, NULL, NULL, NULL, NULL)) != MP_OKAY){ break; } /* hardware crypto */ #if defined(WOLFSSL_ATECC508A) || defined(PLUTON_CRYPTO_ECC) err = wc_ecc_sign_hash_hw(in, inlen, r, s, out, outlen, rng, key); #else err = wc_ecc_sign_hash_ex(in, inlen, rng, key, r, s); #endif if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_SIGN_ENCODE: key->state = ECC_STATE_SIGN_ENCODE; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #ifdef HAVE_CAVIUM_V /* Nitrox requires r and s in sep buffer, so split it */ NitroxEccRsSplit(key, &r->raw, &s->raw); #endif #ifndef WOLFSSL_ASYNC_CRYPT_TEST /* only do this if not simulator, since it overwrites result */ wc_bigint_to_mp(&r->raw, r); wc_bigint_to_mp(&s->raw, s); #endif } #endif /* WOLFSSL_ASYNC_CRYPT */ /* encoded with DSA header */ err = StoreECC_DSA_Sig(out, outlen, r, s); /* done with R/S */ mp_clear(r); mp_clear(s); break; default: err = BAD_STATE_E; break; } /* if async pending then return and skip done cleanup below */ if (err == WC_PENDING_E) { key->state++; return err; } /* cleanup */ #ifdef WOLFSSL_ASYNC_CRYPT wc_ecc_free_async(key); #endif key->state = ECC_STATE_NONE; return err; } #endif /* !NO_ASN */ #ifndef WOLFSSL_ATECC508A /** Sign a message digest in The message digest to sign inlen The length of the digest key A private ECC key r [out] The destination for r component of the signature s [out] The destination for s component of the signature return MP_OKAY if successful */ int wc_ecc_sign_hash_ex(const byte* in, word32 inlen, WC_RNG* rng, ecc_key* key, mp_int *r, mp_int *s) { int err; #ifndef WOLFSSL_SP_MATH mp_int* e; #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) mp_int e_lcl; #endif #endif /* !WOLFSSL_SP_MATH */ DECLARE_CURVE_SPECS(1) if (in == NULL || r == NULL || s == NULL || key == NULL || rng == NULL) return ECC_BAD_ARG_E; /* is this a private key? */ if (key->type != ECC_PRIVATEKEY && key->type != ECC_PRIVATEKEY_ONLY) { return ECC_BAD_ARG_E; } /* is the IDX valid ? */ if (wc_ecc_is_valid_idx(key->idx) != 1) { return ECC_BAD_ARG_E; } #ifdef WOLFSSL_SP_MATH if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->heap); else return WC_KEY_SIZE_E; #else #ifdef WOLFSSL_HAVE_SP_ECC #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC) #endif { #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) return sp_ecc_sign_256(in, inlen, rng, &key->k, r, s, key->heap); #endif } #endif /* WOLFSSL_HAVE_SP_ECC */ #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_SIGN)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->eccSign.in = in; testDev->eccSign.inSz = inlen; testDev->eccSign.rng = rng; testDev->eccSign.key = key; testDev->eccSign.r = r; testDev->eccSign.s = s; return WC_PENDING_E; } } #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) err = wc_ecc_alloc_mpint(key, &key->e); if (err != 0) return err; e = key->e; #else e = &e_lcl; #endif /* get the hash and load it as a bignum into 'e' */ /* init the bignums */ if ((err = mp_init(e)) != MP_OKAY) { return err; } /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ORDER); /* load digest into e */ if (err == MP_OKAY) { /* we may need to truncate if hash is longer than key size */ word32 orderBits = mp_count_bits(curve->order); /* truncate down to byte size, may be all that's needed */ if ((WOLFSSL_BIT_SIZE * inlen) > orderBits) inlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE; err = mp_read_unsigned_bin(e, (byte*)in, inlen); /* may still need bit truncation too */ if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * inlen) > orderBits) mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); } /* make up a key and export the public copy */ if (err == MP_OKAY) { int loop_check = 0; ecc_key pubkey; #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) #ifdef HAVE_CAVIUM_V if (NitroxEccIsCurveSupported(key)) #endif { word32 keySz = key->dp->size; mp_int* k; #ifdef HAVE_CAVIUM_V err = wc_ecc_alloc_mpint(key, &key->signK); if (err != 0) return err; k = key->signK; #else mp_int k_lcl; k = &k_lcl; #endif err = mp_init(k); /* make sure r and s are allocated */ #ifdef HAVE_CAVIUM_V /* Nitrox V needs single buffer for R and S */ if (err == MP_OKAY) err = wc_bigint_alloc(&key->r->raw, NitroxEccGetSize(key)*2); /* Nitrox V only needs Prime and Order */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_ORDER)); #else if (err == MP_OKAY) err = wc_bigint_alloc(&key->r->raw, key->dp->size); if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); #endif if (err == MP_OKAY) err = wc_bigint_alloc(&key->s->raw, key->dp->size); /* load e and k */ if (err == MP_OKAY) err = wc_mp_to_bigint_sz(e, &e->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(&key->k, &key->k.raw, keySz); if (err == MP_OKAY) err = wc_ecc_gen_k(rng, key->dp->size, k, curve->order); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(k, &k->raw, keySz); #ifdef HAVE_CAVIUM_V if (err == MP_OKAY) err = NitroxEcdsaSign(key, &e->raw, &key->k.raw, &k->raw, &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw); #else if (err == MP_OKAY) err = IntelQaEcdsaSign(&key->asyncDev, &e->raw, &key->k.raw, &k->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, &curve->Gy->raw); #endif #ifndef HAVE_CAVIUM_V mp_clear(e); mp_clear(k); #endif wc_ecc_curve_free(curve); return err; } #endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */ } #endif /* WOLFSSL_ASYNC_CRYPT */ /* don't use async for key, since we don't support async return here */ if ((err = wc_ecc_init_ex(&pubkey, key->heap, INVALID_DEVID)) == MP_OKAY) { mp_int b; if (err == MP_OKAY) { err = mp_init(&b); } #ifdef WOLFSSL_CUSTOM_CURVES /* if custom curve, apply params to pubkey */ if (err == MP_OKAY && key->idx == ECC_CUSTOM_IDX) { err = wc_ecc_set_custom_curve(&pubkey, key->dp); } #endif if (err == MP_OKAY) { /* Generate blinding value - non-zero value. */ do { if (++loop_check > 64) { err = RNG_FAILURE_E; break; } err = wc_ecc_gen_k(rng, key->dp->size, &b, curve->order); } while (err == MP_ZERO_E); loop_check = 0; } for (; err == MP_OKAY;) { if (++loop_check > 64) { err = RNG_FAILURE_E; break; } err = wc_ecc_make_key_ex(rng, key->dp->size, &pubkey, key->dp->id); if (err != MP_OKAY) break; /* find r = x1 mod n */ err = mp_mod(pubkey.pubkey.x, curve->order, r); if (err != MP_OKAY) break; if (mp_iszero(r) == MP_YES) { #ifndef ALT_ECC_SIZE mp_clear(pubkey.pubkey.x); mp_clear(pubkey.pubkey.y); mp_clear(pubkey.pubkey.z); #endif mp_forcezero(&pubkey.k); } else { /* find s = (e + xr)/k = b.(e/k.b + x.r/k.b) */ /* k = k.b */ err = mp_mulmod(&pubkey.k, &b, curve->order, &pubkey.k); if (err != MP_OKAY) break; /* k = 1/k.b */ err = mp_invmod(&pubkey.k, curve->order, &pubkey.k); if (err != MP_OKAY) break; /* s = x.r */ err = mp_mulmod(&key->k, r, curve->order, s); if (err != MP_OKAY) break; /* s = x.r/k.b */ err = mp_mulmod(&pubkey.k, s, curve->order, s); if (err != MP_OKAY) break; /* e = e/k.b */ err = mp_mulmod(&pubkey.k, e, curve->order, e); if (err != MP_OKAY) break; /* s = e/k.b + x.r/k.b = (e + x.r)/k.b */ err = mp_add(e, s, s); if (err != MP_OKAY) break; /* s = b.(e + x.r)/k.b = (e + x.r)/k */ err = mp_mulmod(s, &b, curve->order, s); if (err != MP_OKAY) break; /* s = (e + xr)/k */ err = mp_mod(s, curve->order, s); if (err != MP_OKAY) break; if (mp_iszero(s) == MP_NO) break; } } wc_ecc_free(&pubkey); mp_clear(&b); mp_free(&b); } } mp_clear(e); wc_ecc_curve_free(curve); #endif /* WOLFSSL_SP_MATH */ return err; } #endif /* WOLFSSL_ATECC508A */ #endif /* HAVE_ECC_SIGN */ #ifdef WOLFSSL_CUSTOM_CURVES void wc_ecc_free_curve(const ecc_set_type* curve, void* heap) { if (curve->prime != NULL) XFREE((void*)curve->prime, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Af != NULL) XFREE((void*)curve->Af, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Bf != NULL) XFREE((void*)curve->Bf, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->order != NULL) XFREE((void*)curve->order, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Gx != NULL) XFREE((void*)curve->Gx, heap, DYNAMIC_TYPE_ECC_BUFFER); if (curve->Gy != NULL) XFREE((void*)curve->Gy, heap, DYNAMIC_TYPE_ECC_BUFFER); XFREE((void*)curve, heap, DYNAMIC_TYPE_ECC_BUFFER); (void)heap; } #endif /* WOLFSSL_CUSTOM_CURVES */ /** Free an ECC key from memory key The key you wish to free */ int wc_ecc_free(ecc_key* key) { if (key == NULL) { return 0; } #ifdef WOLFSSL_ASYNC_CRYPT #ifdef WC_ASYNC_ENABLE_ECC wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_ECC); #endif wc_ecc_free_async(key); #endif #ifdef WOLFSSL_ATECC508A atmel_ecc_free(key->slot); key->slot = -1; #else mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); mp_forcezero(&key->k); #endif /* WOLFSSL_ATECC508A */ #ifdef WOLFSSL_CUSTOM_CURVES if (key->deallocSet && key->dp != NULL) wc_ecc_free_curve(key->dp, key->heap); #endif return 0; } #ifndef WOLFSSL_SP_MATH #ifdef ECC_SHAMIR /** Computes kA*A + kB*B = C using Shamir's Trick A First point to multiply kA What to multiple A by B Second point to multiply kB What to multiple B by C [out] Destination point (can overlap with A or B) a ECC curve parameter a modulus Modulus for curve return MP_OKAY on success */ #ifdef FP_ECC static int normal_ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point* B, mp_int* kB, ecc_point* C, mp_int* a, mp_int* modulus, void* heap) #else int ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point* B, mp_int* kB, ecc_point* C, mp_int* a, mp_int* modulus, void* heap) #endif { ecc_point* precomp[16]; unsigned bitbufA, bitbufB, lenA, lenB, len, nA, nB, nibble; unsigned char* tA; unsigned char* tB; int err = MP_OKAY, first, x, y; mp_digit mp = 0; /* argchks */ if (A == NULL || kA == NULL || B == NULL || kB == NULL || C == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } /* allocate memory */ tA = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER); if (tA == NULL) { return GEN_MEM_ERR; } tB = (unsigned char*)XMALLOC(ECC_BUFSIZE, heap, DYNAMIC_TYPE_ECC_BUFFER); if (tB == NULL) { XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER); return GEN_MEM_ERR; } /* init variables */ XMEMSET(tA, 0, ECC_BUFSIZE); XMEMSET(tB, 0, ECC_BUFSIZE); XMEMSET(precomp, 0, sizeof(precomp)); /* get sizes */ lenA = mp_unsigned_bin_size(kA); lenB = mp_unsigned_bin_size(kB); len = MAX(lenA, lenB); /* sanity check */ if ((lenA > ECC_BUFSIZE) || (lenB > ECC_BUFSIZE)) { err = BAD_FUNC_ARG; } if (err == MP_OKAY) { /* extract and justify kA */ err = mp_to_unsigned_bin(kA, (len - lenA) + tA); /* extract and justify kB */ if (err == MP_OKAY) err = mp_to_unsigned_bin(kB, (len - lenB) + tB); /* allocate the table */ if (err == MP_OKAY) { for (x = 0; x < 16; x++) { precomp[x] = wc_ecc_new_point_h(heap); if (precomp[x] == NULL) { err = GEN_MEM_ERR; break; } } } } if (err == MP_OKAY) /* init montgomery reduction */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { mp_int mu; err = mp_init(&mu); if (err == MP_OKAY) { err = mp_montgomery_calc_normalization(&mu, modulus); if (err == MP_OKAY) /* copy ones ... */ err = mp_mulmod(A->x, &mu, modulus, precomp[1]->x); if (err == MP_OKAY) err = mp_mulmod(A->y, &mu, modulus, precomp[1]->y); if (err == MP_OKAY) err = mp_mulmod(A->z, &mu, modulus, precomp[1]->z); if (err == MP_OKAY) err = mp_mulmod(B->x, &mu, modulus, precomp[1<<2]->x); if (err == MP_OKAY) err = mp_mulmod(B->y, &mu, modulus, precomp[1<<2]->y); if (err == MP_OKAY) err = mp_mulmod(B->z, &mu, modulus, precomp[1<<2]->z); /* done with mu */ mp_clear(&mu); } } if (err == MP_OKAY) /* precomp [i,0](A + B) table */ err = ecc_projective_dbl_point(precomp[1], precomp[2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_add_point(precomp[1], precomp[2], precomp[3], a, modulus, mp); if (err == MP_OKAY) /* precomp [0,i](A + B) table */ err = ecc_projective_dbl_point(precomp[1<<2], precomp[2<<2], a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_add_point(precomp[1<<2], precomp[2<<2], precomp[3<<2], a, modulus, mp); if (err == MP_OKAY) { /* precomp [i,j](A + B) table (i != 0, j != 0) */ for (x = 1; x < 4; x++) { for (y = 1; y < 4; y++) { if (err == MP_OKAY) err = ecc_projective_add_point(precomp[x], precomp[(y<<2)], precomp[x+(y<<2)], a, modulus, mp); } } } if (err == MP_OKAY) { nibble = 3; first = 1; bitbufA = tA[0]; bitbufB = tB[0]; /* for every byte of the multiplicands */ for (x = 0;; ) { /* grab a nibble */ if (++nibble == 4) { if (x == (int)len) break; bitbufA = tA[x]; bitbufB = tB[x]; nibble = 0; x++; } /* extract two bits from both, shift/update */ nA = (bitbufA >> 6) & 0x03; nB = (bitbufB >> 6) & 0x03; bitbufA = (bitbufA << 2) & 0xFF; bitbufB = (bitbufB << 2) & 0xFF; /* if both zero, if first, continue */ if ((nA == 0) && (nB == 0) && (first == 1)) { continue; } /* double twice, only if this isn't the first */ if (first == 0) { /* double twice */ if (err == MP_OKAY) err = ecc_projective_dbl_point(C, C, a, modulus, mp); if (err == MP_OKAY) err = ecc_projective_dbl_point(C, C, a, modulus, mp); else break; } /* if not both zero */ if ((nA != 0) || (nB != 0)) { if (first == 1) { /* if first, copy from table */ first = 0; if (err == MP_OKAY) err = mp_copy(precomp[nA + (nB<<2)]->x, C->x); if (err == MP_OKAY) err = mp_copy(precomp[nA + (nB<<2)]->y, C->y); if (err == MP_OKAY) err = mp_copy(precomp[nA + (nB<<2)]->z, C->z); else break; } else { /* if not first, add from table */ if (err == MP_OKAY) err = ecc_projective_add_point(C, precomp[nA + (nB<<2)], C, a, modulus, mp); else break; } } } } /* reduce to affine */ if (err == MP_OKAY) err = ecc_map(C, modulus, mp); /* clean up */ for (x = 0; x < 16; x++) { wc_ecc_del_point_h(precomp[x], heap); } ForceZero(tA, ECC_BUFSIZE); ForceZero(tB, ECC_BUFSIZE); XFREE(tA, heap, DYNAMIC_TYPE_ECC_BUFFER); XFREE(tB, heap, DYNAMIC_TYPE_ECC_BUFFER); return err; } #endif /* ECC_SHAMIR */ #endif #ifdef HAVE_ECC_VERIFY #ifndef NO_ASN /* verify * * w = s^-1 mod n * u1 = xw * u2 = rw * X = u1*G + u2*Q * v = X_x1 mod n * accept if v == r */ /** Verify an ECC signature sig The signature to verify siglen The length of the signature (octets) hash The hash (message digest) that was signed hashlen The length of the hash (octets) res Result of signature, 1==valid, 0==invalid key The corresponding public ECC key return MP_OKAY if successful (even if the signature is not valid) */ int wc_ecc_verify_hash(const byte* sig, word32 siglen, const byte* hash, word32 hashlen, int* res, ecc_key* key) { int err; mp_int *r = NULL, *s = NULL; #ifndef WOLFSSL_ASYNC_CRYPT mp_int r_lcl, s_lcl; #endif if (sig == NULL || hash == NULL || res == NULL || key == NULL) { return ECC_BAD_ARG_E; } #ifdef WOLF_CRYPTO_DEV if (key->devId != INVALID_DEVID) { err = wc_CryptoDev_EccVerify(sig, siglen, hash, hashlen, res, key); if (err != NOT_COMPILED_IN) return err; } #endif #ifdef WOLFSSL_ASYNC_CRYPT err = wc_ecc_alloc_async(key); if (err != 0) return err; r = key->r; s = key->s; #else r = &r_lcl; s = &s_lcl; #endif switch(key->state) { case ECC_STATE_NONE: case ECC_STATE_VERIFY_DECODE: key->state = ECC_STATE_VERIFY_DECODE; /* default to invalid signature */ *res = 0; /* Note, DecodeECC_DSA_Sig() calls mp_init() on r and s. * If either of those don't allocate correctly, none of * the rest of this function will execute, and everything * gets cleaned up at the end. */ /* decode DSA header */ err = DecodeECC_DSA_Sig(sig, siglen, r, s); if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_VERIFY_DO: key->state = ECC_STATE_VERIFY_DO; err = wc_ecc_verify_hash_ex(r, s, hash, hashlen, res, key); #ifndef WOLFSSL_ASYNC_CRYPT /* done with R/S */ mp_clear(r); mp_clear(s); #endif if (err < 0) { break; } FALL_THROUGH; case ECC_STATE_VERIFY_RES: key->state = ECC_STATE_VERIFY_RES; err = 0; break; default: err = BAD_STATE_E; } /* if async pending then return and skip done cleanup below */ if (err == WC_PENDING_E) { key->state++; return err; } /* cleanup */ #ifdef WOLFSSL_ASYNC_CRYPT wc_ecc_free_async(key); #endif key->state = ECC_STATE_NONE; return err; } #endif /* !NO_ASN */ /** Verify an ECC signature r The signature R component to verify s The signature S component to verify hash The hash (message digest) that was signed hashlen The length of the hash (octets) res Result of signature, 1==valid, 0==invalid key The corresponding public ECC key return MP_OKAY if successful (even if the signature is not valid) */ int wc_ecc_verify_hash_ex(mp_int *r, mp_int *s, const byte* hash, word32 hashlen, int* res, ecc_key* key) { int err; #ifdef WOLFSSL_ATECC508A byte sigRS[ATECC_KEY_SIZE*2]; #elif !defined(WOLFSSL_SP_MATH) int did_init = 0; ecc_point *mG = NULL, *mQ = NULL; mp_int v; mp_int w; mp_int u1; mp_int u2; mp_int* e; #if !defined(WOLFSSL_ASYNC_CRYPT) || !defined(HAVE_CAVIUM_V) mp_int e_lcl; #endif DECLARE_CURVE_SPECS(ECC_CURVE_FIELD_COUNT) #endif if (r == NULL || s == NULL || hash == NULL || res == NULL || key == NULL) return ECC_BAD_ARG_E; /* default to invalid signature */ *res = 0; /* is the IDX valid ? */ if (wc_ecc_is_valid_idx(key->idx) != 1) { return ECC_BAD_ARG_E; } #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { if (wc_AsyncTestInit(&key->asyncDev, ASYNC_TEST_ECC_VERIFY)) { WC_ASYNC_TEST* testDev = &key->asyncDev.test; testDev->eccVerify.r = r; testDev->eccVerify.s = s; testDev->eccVerify.hash = hash; testDev->eccVerify.hashlen = hashlen; testDev->eccVerify.stat = res; testDev->eccVerify.key = key; return WC_PENDING_E; } } #endif #ifdef WOLFSSL_ATECC508A /* Extract R and S */ err = mp_to_unsigned_bin(r, &sigRS[0]); if (err != MP_OKAY) { return err; } err = mp_to_unsigned_bin(s, &sigRS[ATECC_KEY_SIZE]); if (err != MP_OKAY) { return err; } err = atcatls_verify(hash, sigRS, key->pubkey_raw, (bool*)res); if (err != ATCA_SUCCESS) { return BAD_COND_E; } #else /* checking if private key with no public part */ if (key->type == ECC_PRIVATEKEY_ONLY) { WOLFSSL_MSG("Verify called with private key, generating public part"); err = wc_ecc_make_pub_ex(key, NULL, NULL); if (err != MP_OKAY) { WOLFSSL_MSG("Unable to extract public key"); return err; } } #ifdef WOLFSSL_SP_MATH if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { return sp_ecc_verify_256(hash, hashlen, key->pubkey.x, key->pubkey.y, key->pubkey.z, r, s, res, key->heap); } else return WC_KEY_SIZE_E; #else #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) && \ defined(WOLFSSL_ASYNC_CRYPT_TEST) if (key->asyncDev.marker != WOLFSSL_ASYNC_MARKER_ECC) #endif { if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) return sp_ecc_verify_256(hash, hashlen, key->pubkey.x, key->pubkey.y, key->pubkey.z,r, s, res, key->heap); } #endif #endif #if defined(WOLFSSL_ASYNC_CRYPT) && defined(HAVE_CAVIUM_V) err = wc_ecc_alloc_mpint(key, &key->e); if (err != 0) return err; e = key->e; #else e = &e_lcl; #endif err = mp_init(e); if (err != MP_OKAY) return MEMORY_E; /* read in the specs for this curve */ err = wc_ecc_curve_load(key->dp, &curve, ECC_CURVE_FIELD_ALL); /* check for zero */ if (err == MP_OKAY) { if (mp_iszero(r) == MP_YES || mp_iszero(s) == MP_YES || mp_cmp(r, curve->order) != MP_LT || mp_cmp(s, curve->order) != MP_LT) { err = MP_ZERO_E; } } /* read hash */ if (err == MP_OKAY) { /* we may need to truncate if hash is longer than key size */ unsigned int orderBits = mp_count_bits(curve->order); /* truncate down to byte size, may be all that's needed */ if ( (WOLFSSL_BIT_SIZE * hashlen) > orderBits) hashlen = (orderBits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE; err = mp_read_unsigned_bin(e, hash, hashlen); /* may still need bit truncation too */ if (err == MP_OKAY && (WOLFSSL_BIT_SIZE * hashlen) > orderBits) mp_rshb(e, WOLFSSL_BIT_SIZE - (orderBits & 0x7)); } /* check for async hardware acceleration */ #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_ECC) if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_ECC) { #if defined(HAVE_CAVIUM_V) || defined(HAVE_INTEL_QA) #ifdef HAVE_CAVIUM_V if (NitroxEccIsCurveSupported(key)) #endif { word32 keySz = key->dp->size; err = wc_mp_to_bigint_sz(e, &e->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(key->pubkey.x, &key->pubkey.x->raw, keySz); if (err == MP_OKAY) err = wc_mp_to_bigint_sz(key->pubkey.y, &key->pubkey.y->raw, keySz); if (err == MP_OKAY) #ifdef HAVE_CAVIUM_V err = NitroxEcdsaVerify(key, &e->raw, &key->pubkey.x->raw, &key->pubkey.y->raw, &r->raw, &s->raw, &curve->prime->raw, &curve->order->raw, res); #else err = IntelQaEcdsaVerify(&key->asyncDev, &e->raw, &key->pubkey.x->raw, &key->pubkey.y->raw, &r->raw, &s->raw, &curve->Af->raw, &curve->Bf->raw, &curve->prime->raw, &curve->order->raw, &curve->Gx->raw, &curve->Gy->raw, res); #endif #ifndef HAVE_CAVIUM_V mp_clear(e); #endif wc_ecc_curve_free(curve); return err; } #endif /* HAVE_CAVIUM_V || HAVE_INTEL_QA */ } #endif /* WOLFSSL_ASYNC_CRYPT */ /* allocate ints */ if (err == MP_OKAY) { if ((err = mp_init_multi(&v, &w, &u1, &u2, NULL, NULL)) != MP_OKAY) { err = MEMORY_E; } did_init = 1; } /* allocate points */ if (err == MP_OKAY) { mG = wc_ecc_new_point_h(key->heap); mQ = wc_ecc_new_point_h(key->heap); if (mQ == NULL || mG == NULL) err = MEMORY_E; } /* w = s^-1 mod n */ if (err == MP_OKAY) err = mp_invmod(s, curve->order, &w); /* u1 = ew */ if (err == MP_OKAY) err = mp_mulmod(e, &w, curve->order, &u1); /* u2 = rw */ if (err == MP_OKAY) err = mp_mulmod(r, &w, curve->order, &u2); /* find mG and mQ */ if (err == MP_OKAY) err = mp_copy(curve->Gx, mG->x); if (err == MP_OKAY) err = mp_copy(curve->Gy, mG->y); if (err == MP_OKAY) err = mp_set(mG->z, 1); if (err == MP_OKAY) err = mp_copy(key->pubkey.x, mQ->x); if (err == MP_OKAY) err = mp_copy(key->pubkey.y, mQ->y); if (err == MP_OKAY) err = mp_copy(key->pubkey.z, mQ->z); #ifdef FREESCALE_LTC_ECC /* use PKHA to compute u1*mG + u2*mQ */ if (err == MP_OKAY) err = wc_ecc_mulmod_ex(&u1, mG, mG, curve->Af, curve->prime, 0, key->heap); if (err == MP_OKAY) err = wc_ecc_mulmod_ex(&u2, mQ, mQ, curve->Af, curve->prime, 0, key->heap); if (err == MP_OKAY) err = wc_ecc_point_add(mG, mQ, mG, curve->prime); #else #ifndef ECC_SHAMIR { mp_digit mp = 0; /* compute u1*mG + u2*mQ = mG */ if (err == MP_OKAY) { err = wc_ecc_mulmod_ex(&u1, mG, mG, curve->Af, curve->prime, 0, key->heap); } if (err == MP_OKAY) { err = wc_ecc_mulmod_ex(&u2, mQ, mQ, curve->Af, curve->prime, 0, key->heap); } /* find the montgomery mp */ if (err == MP_OKAY) err = mp_montgomery_setup(curve->prime, &mp); /* add them */ if (err == MP_OKAY) err = ecc_projective_add_point(mQ, mG, mG, curve->Af, curve->prime, mp); /* reduce */ if (err == MP_OKAY) err = ecc_map(mG, curve->prime, mp); } #else /* use Shamir's trick to compute u1*mG + u2*mQ using half the doubles */ if (err == MP_OKAY) { err = ecc_mul2add(mG, &u1, mQ, &u2, mG, curve->Af, curve->prime, key->heap); } #endif /* ECC_SHAMIR */ #endif /* FREESCALE_LTC_ECC */ /* v = X_x1 mod n */ if (err == MP_OKAY) err = mp_mod(mG->x, curve->order, &v); /* does v == r */ if (err == MP_OKAY) { if (mp_cmp(&v, r) == MP_EQ) *res = 1; } /* cleanup */ wc_ecc_del_point_h(mG, key->heap); wc_ecc_del_point_h(mQ, key->heap); mp_clear(e); if (did_init) { mp_clear(&v); mp_clear(&w); mp_clear(&u1); mp_clear(&u2); } wc_ecc_curve_free(curve); #endif /* WOLFSSL_SP_MATH */ #endif /* WOLFSSL_ATECC508A */ return err; } #endif /* HAVE_ECC_VERIFY */ #ifdef HAVE_ECC_KEY_IMPORT #ifndef WOLFSSL_ATECC508A /* import point from der */ int wc_ecc_import_point_der(byte* in, word32 inLen, const int curve_idx, ecc_point* point) { int err = 0; int compressed = 0; int keysize; byte pointType; if (in == NULL || point == NULL || (curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0)) return ECC_BAD_ARG_E; /* must be odd */ if ((inLen & 1) == 0) { return ECC_BAD_ARG_E; } /* init point */ #ifdef ALT_ECC_SIZE point->x = (mp_int*)&point->xyz[0]; point->y = (mp_int*)&point->xyz[1]; point->z = (mp_int*)&point->xyz[2]; alt_fp_init(point->x); alt_fp_init(point->y); alt_fp_init(point->z); #else err = mp_init_multi(point->x, point->y, point->z, NULL, NULL, NULL); #endif if (err != MP_OKAY) return MEMORY_E; /* check for point type (4, 2, or 3) */ pointType = in[0]; if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN && pointType != ECC_POINT_COMP_ODD) { err = ASN_PARSE_E; } if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) { #ifdef HAVE_COMP_KEY compressed = 1; #else err = NOT_COMPILED_IN; #endif } /* adjust to skip first byte */ inLen -= 1; in += 1; /* calculate key size based on inLen / 2 */ keysize = inLen>>1; #ifdef WOLFSSL_ATECC508A /* populate key->pubkey_raw */ XMEMCPY(key->pubkey_raw, (byte*)in, sizeof(key->pubkey_raw)); #endif /* read data */ if (err == MP_OKAY) err = mp_read_unsigned_bin(point->x, (byte*)in, keysize); #ifdef HAVE_COMP_KEY if (err == MP_OKAY && compressed == 1) { /* build y */ #ifndef WOLFSSL_SP_MATH int did_init = 0; mp_int t1, t2; DECLARE_CURVE_SPECS(3) if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY) err = MEMORY_E; else did_init = 1; /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(&ecc_sets[curve_idx], &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_BF)); /* compute x^3 */ if (err == MP_OKAY) err = mp_sqr(point->x, &t1); if (err == MP_OKAY) err = mp_mulmod(&t1, point->x, curve->prime, &t1); /* compute x^3 + a*x */ if (err == MP_OKAY) err = mp_mulmod(curve->Af, point->x, curve->prime, &t2); if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); /* compute x^3 + a*x + b */ if (err == MP_OKAY) err = mp_add(&t1, curve->Bf, &t1); /* compute sqrt(x^3 + a*x + b) */ if (err == MP_OKAY) err = mp_sqrtmod_prime(&t1, curve->prime, &t2); /* adjust y */ if (err == MP_OKAY) { if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) || (mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) { err = mp_mod(&t2, curve->prime, point->y); } else { err = mp_submod(curve->prime, &t2, curve->prime, point->y); } } if (did_init) { mp_clear(&t2); mp_clear(&t1); } wc_ecc_curve_free(curve); #else sp_ecc_uncompress_256(point->x, pointType, point->y); #endif } #endif if (err == MP_OKAY && compressed == 0) err = mp_read_unsigned_bin(point->y, (byte*)in + keysize, keysize); if (err == MP_OKAY) err = mp_set(point->z, 1); if (err != MP_OKAY) { mp_clear(point->x); mp_clear(point->y); mp_clear(point->z); } return err; } #endif /* !WOLFSSL_ATECC508A */ #endif /* HAVE_ECC_KEY_IMPORT */ #ifdef HAVE_ECC_KEY_EXPORT /* export point to der */ int wc_ecc_export_point_der(const int curve_idx, ecc_point* point, byte* out, word32* outLen) { int ret = MP_OKAY; word32 numlen; #ifndef WOLFSSL_ATECC508A #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_BUFSIZE]; #endif #endif /* !WOLFSSL_ATECC508A */ if ((curve_idx < 0) || (wc_ecc_is_valid_idx(curve_idx) == 0)) return ECC_BAD_ARG_E; /* return length needed only */ if (point != NULL && out == NULL && outLen != NULL) { numlen = ecc_sets[curve_idx].size; *outLen = 1 + 2*numlen; return LENGTH_ONLY_E; } if (point == NULL || out == NULL || outLen == NULL) return ECC_BAD_ARG_E; numlen = ecc_sets[curve_idx].size; if (*outLen < (1 + 2*numlen)) { *outLen = 1 + 2*numlen; return BUFFER_E; } #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ ret = BAD_COND_E; #else /* store byte point type */ out[0] = ECC_POINT_UNCOMP; #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /* pad and store x */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->x, buf + (numlen - mp_unsigned_bin_size(point->x))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1, buf, numlen); /* pad and store y */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(point->y, buf + (numlen - mp_unsigned_bin_size(point->y))); if (ret != MP_OKAY) goto done; XMEMCPY(out+1+numlen, buf, numlen); *outLen = 1 + 2*numlen; done: #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif #endif /* WOLFSSL_ATECC508A */ return ret; } /* export public ECC key in ANSI X9.63 format */ int wc_ecc_export_x963(ecc_key* key, byte* out, word32* outLen) { int ret = MP_OKAY; word32 numlen; #ifdef WOLFSSL_SMALL_STACK byte* buf; #else byte buf[ECC_BUFSIZE]; #endif word32 pubxlen, pubylen; /* return length needed only */ if (key != NULL && out == NULL && outLen != NULL) { numlen = key->dp->size; *outLen = 1 + 2*numlen; return LENGTH_ONLY_E; } if (key == NULL || out == NULL || outLen == NULL) return ECC_BAD_ARG_E; if (key->type == ECC_PRIVATEKEY_ONLY) return ECC_PRIVATEONLY_E; if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numlen = key->dp->size; /* verify room in out buffer */ if (*outLen < (1 + 2*numlen)) { *outLen = 1 + 2*numlen; return BUFFER_E; } /* verify public key length is less than key size */ pubxlen = mp_unsigned_bin_size(key->pubkey.x); pubylen = mp_unsigned_bin_size(key->pubkey.y); if ((pubxlen > numlen) || (pubylen > numlen)) { WOLFSSL_MSG("Public key x/y invalid!"); return BUFFER_E; } /* store byte point type */ out[0] = ECC_POINT_UNCOMP; #ifdef WOLFSSL_SMALL_STACK buf = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (buf == NULL) return MEMORY_E; #endif /* pad and store x */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(key->pubkey.x, buf + (numlen - pubxlen)); if (ret != MP_OKAY) goto done; XMEMCPY(out+1, buf, numlen); /* pad and store y */ XMEMSET(buf, 0, ECC_BUFSIZE); ret = mp_to_unsigned_bin(key->pubkey.y, buf + (numlen - pubylen)); if (ret != MP_OKAY) goto done; XMEMCPY(out+1+numlen, buf, numlen); *outLen = 1 + 2*numlen; done: #ifdef WOLFSSL_SMALL_STACK XFREE(buf, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return ret; } /* export public ECC key in ANSI X9.63 format, extended with * compression option */ int wc_ecc_export_x963_ex(ecc_key* key, byte* out, word32* outLen, int compressed) { if (compressed == 0) return wc_ecc_export_x963(key, out, outLen); #ifdef HAVE_COMP_KEY else return wc_ecc_export_x963_compressed(key, out, outLen); #else return NOT_COMPILED_IN; #endif } #endif /* HAVE_ECC_KEY_EXPORT */ #ifndef WOLFSSL_ATECC508A /* is ecc point on curve described by dp ? */ int wc_ecc_is_point(ecc_point* ecp, mp_int* a, mp_int* b, mp_int* prime) { #ifndef WOLFSSL_SP_MATH int err; mp_int t1, t2; if ((err = mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL)) != MP_OKAY) { return err; } /* compute y^2 */ if (err == MP_OKAY) err = mp_sqr(ecp->y, &t1); /* compute x^3 */ if (err == MP_OKAY) err = mp_sqr(ecp->x, &t2); if (err == MP_OKAY) err = mp_mod(&t2, prime, &t2); if (err == MP_OKAY) err = mp_mul(ecp->x, &t2, &t2); /* compute y^2 - x^3 */ if (err == MP_OKAY) err = mp_sub(&t1, &t2, &t1); /* Determine if curve "a" should be used in calc */ #ifdef WOLFSSL_CUSTOM_CURVES if (err == MP_OKAY) { /* Use a and prime to determine if a == 3 */ err = mp_set(&t2, 0); if (err == MP_OKAY) err = mp_submod(prime, a, prime, &t2); } if (err == MP_OKAY && mp_cmp_d(&t2, 3) != MP_EQ) { /* compute y^2 - x^3 + a*x */ if (err == MP_OKAY) err = mp_mulmod(&t2, ecp->x, prime, &t2); if (err == MP_OKAY) err = mp_addmod(&t1, &t2, prime, &t1); } else #endif /* WOLFSSL_CUSTOM_CURVES */ { /* assumes "a" == 3 */ (void)a; /* compute y^2 - x^3 + 3x */ if (err == MP_OKAY) err = mp_add(&t1, ecp->x, &t1); if (err == MP_OKAY) err = mp_add(&t1, ecp->x, &t1); if (err == MP_OKAY) err = mp_add(&t1, ecp->x, &t1); if (err == MP_OKAY) err = mp_mod(&t1, prime, &t1); } /* adjust range (0, prime) */ while (err == MP_OKAY && mp_isneg(&t1)) { err = mp_add(&t1, prime, &t1); } while (err == MP_OKAY && mp_cmp(&t1, prime) != MP_LT) { err = mp_sub(&t1, prime, &t1); } /* compare to b */ if (err == MP_OKAY) { if (mp_cmp(&t1, b) != MP_EQ) { err = MP_VAL; } else { err = MP_OKAY; } } mp_clear(&t1); mp_clear(&t2); return err; #else (void)a; (void)b; (void)prime; return sp_ecc_is_point_256(ecp->x, ecp->y); #endif } #ifndef WOLFSSL_SP_MATH /* validate privkey * generator == pubkey, 0 on success */ static int ecc_check_privkey_gen(ecc_key* key, mp_int* a, mp_int* prime) { int err = MP_OKAY; ecc_point* base = NULL; ecc_point* res = NULL; DECLARE_CURVE_SPECS(2) if (key == NULL) return BAD_FUNC_ARG; res = wc_ecc_new_point_h(key->heap); if (res == NULL) err = MEMORY_E; #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { if (err == MP_OKAY) err = sp_ecc_mulmod_base_256(&key->k, res, 1, key->heap); } else #endif #endif { base = wc_ecc_new_point_h(key->heap); if (base == NULL) err = MEMORY_E; if (err == MP_OKAY) { /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_GX | ECC_CURVE_FIELD_GY)); } /* set up base generator */ if (err == MP_OKAY) err = mp_copy(curve->Gx, base->x); if (err == MP_OKAY) err = mp_copy(curve->Gy, base->y); if (err == MP_OKAY) err = mp_set(base->z, 1); if (err == MP_OKAY) err = wc_ecc_mulmod_ex(&key->k, base, res, a, prime, 1, key->heap); } if (err == MP_OKAY) { /* compare result to public key */ if (mp_cmp(res->x, key->pubkey.x) != MP_EQ || mp_cmp(res->y, key->pubkey.y) != MP_EQ || mp_cmp(res->z, key->pubkey.z) != MP_EQ) { /* didn't match */ err = ECC_PRIV_KEY_E; } } wc_ecc_curve_free(curve); wc_ecc_del_point_h(res, key->heap); wc_ecc_del_point_h(base, key->heap); return err; } #endif #ifdef WOLFSSL_VALIDATE_ECC_IMPORT /* check privkey generator helper, creates prime needed */ static int ecc_check_privkey_gen_helper(ecc_key* key) { int err; #ifndef WOLFSSL_ATECC508A DECLARE_CURVE_SPECS(2) #endif if (key == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ err = BAD_COND_E; #else /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF)); if (err == MP_OKAY) err = ecc_check_privkey_gen(key, curve->Af, curve->prime); wc_ecc_curve_free(curve); #endif /* WOLFSSL_ATECC508A */ return err; } #endif /* WOLFSSL_VALIDATE_ECC_IMPORT */ #if defined(WOLFSSL_VALIDATE_ECC_KEYGEN) || !defined(WOLFSSL_SP_MATH) /* validate order * pubkey = point at infinity, 0 on success */ static int ecc_check_pubkey_order(ecc_key* key, ecc_point* pubkey, mp_int* a, mp_int* prime, mp_int* order) { ecc_point* inf = NULL; int err; if (key == NULL) return BAD_FUNC_ARG; inf = wc_ecc_new_point_h(key->heap); if (inf == NULL) err = MEMORY_E; else { #ifdef WOLFSSL_HAVE_SP_ECC #ifndef WOLFSSL_SP_NO_256 if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { err = sp_ecc_mulmod_256(order, pubkey, inf, 1, key->heap); } else #endif #endif #ifndef WOLFSSL_SP_MATH err = wc_ecc_mulmod_ex(order, pubkey, inf, a, prime, 1, key->heap); if (err == MP_OKAY && !wc_ecc_point_is_at_infinity(inf)) err = ECC_INF_E; #else (void)a; (void)prime; err = WC_KEY_SIZE_E; #endif } wc_ecc_del_point_h(inf, key->heap); return err; } #endif #endif /* !WOLFSSL_ATECC508A */ /* perform sanity checks on ecc key validity, 0 on success */ int wc_ecc_check_key(ecc_key* key) { int err; #ifndef WOLFSSL_SP_MATH #ifndef WOLFSSL_ATECC508A mp_int* b; #ifdef USE_ECC_B_PARAM DECLARE_CURVE_SPECS(4) #else mp_int b_lcl; DECLARE_CURVE_SPECS(3) b = &b_lcl; XMEMSET(b, 0, sizeof(mp_int)); #endif #endif /* WOLFSSL_ATECC508A */ if (key == NULL) return BAD_FUNC_ARG; #ifdef WOLFSSL_ATECC508A if (key->slot == ATECC_INVALID_SLOT) return ECC_BAD_ARG_E; err = 0; /* consider key check success on ECC508A */ #else /* pubkey point cannot be at infinity */ if (wc_ecc_point_is_at_infinity(&key->pubkey)) return ECC_INF_E; /* load curve info */ err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_ORDER #ifdef USE_ECC_B_PARAM | ECC_CURVE_FIELD_BF #endif )); #ifndef USE_ECC_B_PARAM /* load curve b parameter */ if (err == MP_OKAY) err = mp_init(b); if (err == MP_OKAY) err = mp_read_radix(b, key->dp->Bf, MP_RADIX_HEX); #else b = curve->Bf; #endif /* Qx must be in the range [0, p-1] */ if (mp_cmp(key->pubkey.x, curve->prime) != MP_LT) err = ECC_OUT_OF_RANGE_E; /* Qy must be in the range [0, p-1] */ if (mp_cmp(key->pubkey.y, curve->prime) != MP_LT) err = ECC_OUT_OF_RANGE_E; /* make sure point is actually on curve */ if (err == MP_OKAY) err = wc_ecc_is_point(&key->pubkey, curve->Af, b, curve->prime); /* pubkey * order must be at infinity */ if (err == MP_OKAY) err = ecc_check_pubkey_order(key, &key->pubkey, curve->Af, curve->prime, curve->order); /* private * base generator must equal pubkey */ if (err == MP_OKAY && key->type == ECC_PRIVATEKEY) err = ecc_check_privkey_gen(key, curve->Af, curve->prime); wc_ecc_curve_free(curve); #ifndef USE_ECC_B_PARAM mp_clear(b); #endif #endif /* WOLFSSL_ATECC508A */ #else if (key == NULL) return BAD_FUNC_ARG; /* pubkey point cannot be at infinity */ if (key->idx != ECC_CUSTOM_IDX && ecc_sets[key->idx].id == ECC_SECP256R1) { err = sp_ecc_check_key_256(key->pubkey.x, key->pubkey.y, &key->k, key->heap); } else err = WC_KEY_SIZE_E; #endif return err; } #ifdef HAVE_ECC_KEY_IMPORT /* import public ECC key in ANSI X9.63 format */ int wc_ecc_import_x963_ex(const byte* in, word32 inLen, ecc_key* key, int curve_id) { int err = MP_OKAY; int compressed = 0; int keysize = 0; byte pointType; if (in == NULL || key == NULL) return BAD_FUNC_ARG; /* must be odd */ if ((inLen & 1) == 0) { return ECC_BAD_ARG_E; } /* make sure required variables are reset */ wc_ecc_reset(key); /* init key */ #ifdef ALT_ECC_SIZE key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); err = mp_init(&key->k); #else err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif if (err != MP_OKAY) return MEMORY_E; /* check for point type (4, 2, or 3) */ pointType = in[0]; if (pointType != ECC_POINT_UNCOMP && pointType != ECC_POINT_COMP_EVEN && pointType != ECC_POINT_COMP_ODD) { err = ASN_PARSE_E; } if (pointType == ECC_POINT_COMP_EVEN || pointType == ECC_POINT_COMP_ODD) { #ifdef HAVE_COMP_KEY compressed = 1; #else err = NOT_COMPILED_IN; #endif } /* adjust to skip first byte */ inLen -= 1; in += 1; if (err == MP_OKAY) { #ifdef HAVE_COMP_KEY /* adjust inLen if compressed */ if (compressed) inLen = inLen*2 + 1; /* used uncompressed len */ #endif /* determine key size */ keysize = (inLen>>1); err = wc_ecc_set_curve(key, keysize, curve_id); key->type = ECC_PUBLICKEY; } /* read data */ if (err == MP_OKAY) err = mp_read_unsigned_bin(key->pubkey.x, (byte*)in, keysize); #ifdef HAVE_COMP_KEY if (err == MP_OKAY && compressed == 1) { /* build y */ #ifndef WOLFSSL_SP_MATH mp_int t1, t2; int did_init = 0; DECLARE_CURVE_SPECS(3) if (mp_init_multi(&t1, &t2, NULL, NULL, NULL, NULL) != MP_OKAY) err = MEMORY_E; else did_init = 1; /* load curve info */ if (err == MP_OKAY) err = wc_ecc_curve_load(key->dp, &curve, (ECC_CURVE_FIELD_PRIME | ECC_CURVE_FIELD_AF | ECC_CURVE_FIELD_BF)); /* compute x^3 */ if (err == MP_OKAY) err = mp_sqr(key->pubkey.x, &t1); if (err == MP_OKAY) err = mp_mulmod(&t1, key->pubkey.x, curve->prime, &t1); /* compute x^3 + a*x */ if (err == MP_OKAY) err = mp_mulmod(curve->Af, key->pubkey.x, curve->prime, &t2); if (err == MP_OKAY) err = mp_add(&t1, &t2, &t1); /* compute x^3 + a*x + b */ if (err == MP_OKAY) err = mp_add(&t1, curve->Bf, &t1); /* compute sqrt(x^3 + a*x + b) */ if (err == MP_OKAY) err = mp_sqrtmod_prime(&t1, curve->prime, &t2); /* adjust y */ if (err == MP_OKAY) { if ((mp_isodd(&t2) == MP_YES && pointType == ECC_POINT_COMP_ODD) || (mp_isodd(&t2) == MP_NO && pointType == ECC_POINT_COMP_EVEN)) { err = mp_mod(&t2, curve->prime, &t2); } else { err = mp_submod(curve->prime, &t2, curve->prime, &t2); } if (err == MP_OKAY) err = mp_copy(&t2, key->pubkey.y); } if (did_init) { mp_clear(&t2); mp_clear(&t1); } wc_ecc_curve_free(curve); #else sp_ecc_uncompress_256(key->pubkey.x, pointType, key->pubkey.y); #endif } #endif /* HAVE_COMP_KEY */ if (err == MP_OKAY && compressed == 0) err = mp_read_unsigned_bin(key->pubkey.y, (byte*)in + keysize, keysize); if (err == MP_OKAY) err = mp_set(key->pubkey.z, 1); #ifdef WOLFSSL_VALIDATE_ECC_IMPORT if (err == MP_OKAY) err = wc_ecc_check_key(key); #endif if (err != MP_OKAY) { mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); mp_clear(&key->k); } return err; } int wc_ecc_import_x963(const byte* in, word32 inLen, ecc_key* key) { return wc_ecc_import_x963_ex(in, inLen, key, ECC_CURVE_DEF); } #endif /* HAVE_ECC_KEY_IMPORT */ #ifdef HAVE_ECC_KEY_EXPORT /* export ecc private key only raw, outLen is in/out size return MP_OKAY on success */ int wc_ecc_export_private_only(ecc_key* key, byte* out, word32* outLen) { word32 numlen; if (key == NULL || out == NULL || outLen == NULL) { return BAD_FUNC_ARG; } if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numlen = key->dp->size; if (*outLen < numlen) { *outLen = numlen; return BUFFER_E; } *outLen = numlen; XMEMSET(out, 0, *outLen); #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ return BAD_COND_E; #else return mp_to_unsigned_bin(&key->k, out + (numlen - mp_unsigned_bin_size(&key->k))); #endif /* WOLFSSL_ATECC508A */ } /* export ecc key to component form, d is optional if only exporting public * return MP_OKAY on success */ static int wc_ecc_export_raw(ecc_key* key, byte* qx, word32* qxLen, byte* qy, word32* qyLen, byte* d, word32* dLen) { int err; byte exportPriv = 0; word32 numLen; if (key == NULL || qx == NULL || qxLen == NULL || qy == NULL || qyLen == NULL) { return BAD_FUNC_ARG; } if (key->type == ECC_PRIVATEKEY_ONLY) { return ECC_PRIVATEONLY_E; } if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numLen = key->dp->size; if (d != NULL) { if (dLen == NULL || key->type != ECC_PRIVATEKEY) return BAD_FUNC_ARG; exportPriv = 1; } /* check public buffer sizes */ if ((*qxLen < numLen) || (*qyLen < numLen)) { *qxLen = numLen; *qyLen = numLen; return BUFFER_E; } *qxLen = numLen; *qyLen = numLen; XMEMSET(qx, 0, *qxLen); XMEMSET(qy, 0, *qyLen); /* private d component */ if (exportPriv == 1) { /* check private buffer size */ if (*dLen < numLen) { *dLen = numLen; return BUFFER_E; } *dLen = numLen; XMEMSET(d, 0, *dLen); #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ return BAD_COND_E; #else /* private key, d */ err = mp_to_unsigned_bin(&key->k, d + (numLen - mp_unsigned_bin_size(&key->k))); if (err != MP_OKAY) return err; #endif /* WOLFSSL_ATECC508A */ } /* public x component */ err = mp_to_unsigned_bin(key->pubkey.x, qx + (numLen - mp_unsigned_bin_size(key->pubkey.x))); if (err != MP_OKAY) return err; /* public y component */ err = mp_to_unsigned_bin(key->pubkey.y, qy + (numLen - mp_unsigned_bin_size(key->pubkey.y))); if (err != MP_OKAY) return err; return 0; } /* export public key to raw elements including public (Qx,Qy) * return MP_OKAY on success, negative on error */ int wc_ecc_export_public_raw(ecc_key* key, byte* qx, word32* qxLen, byte* qy, word32* qyLen) { return wc_ecc_export_raw(key, qx, qxLen, qy, qyLen, NULL, NULL); } /* export ecc key to raw elements including public (Qx,Qy) and private (d) * return MP_OKAY on success, negative on error */ int wc_ecc_export_private_raw(ecc_key* key, byte* qx, word32* qxLen, byte* qy, word32* qyLen, byte* d, word32* dLen) { /* sanitize d and dLen, other args are checked later */ if (d == NULL || dLen == NULL) return BAD_FUNC_ARG; return wc_ecc_export_raw(key, qx, qxLen, qy, qyLen, d, dLen); } #endif /* HAVE_ECC_KEY_EXPORT */ #ifdef HAVE_ECC_KEY_IMPORT /* import private key, public part optional if (pub) passed as NULL */ int wc_ecc_import_private_key_ex(const byte* priv, word32 privSz, const byte* pub, word32 pubSz, ecc_key* key, int curve_id) { int ret; word32 idx = 0; if (key == NULL || priv == NULL) return BAD_FUNC_ARG; /* public optional, NULL if only importing private */ if (pub != NULL) { ret = wc_ecc_import_x963_ex(pub, pubSz, key, curve_id); if (ret < 0) ret = wc_EccPublicKeyDecode(pub, &idx, key, pubSz); key->type = ECC_PRIVATEKEY; } else { /* make sure required variables are reset */ wc_ecc_reset(key); /* set key size */ ret = wc_ecc_set_curve(key, privSz, curve_id); key->type = ECC_PRIVATEKEY_ONLY; } if (ret != 0) return ret; #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ return BAD_COND_E; #else ret = mp_read_unsigned_bin(&key->k, priv, privSz); #endif /* WOLFSSL_ATECC508A */ #ifdef WOLFSSL_VALIDATE_ECC_IMPORT if ((pub != NULL) && (ret == MP_OKAY)) /* public key needed to perform key validation */ ret = ecc_check_privkey_gen_helper(key); #endif return ret; } /* ecc private key import, public key in ANSI X9.63 format, private raw */ int wc_ecc_import_private_key(const byte* priv, word32 privSz, const byte* pub, word32 pubSz, ecc_key* key) { return wc_ecc_import_private_key_ex(priv, privSz, pub, pubSz, key, ECC_CURVE_DEF); } #endif /* HAVE_ECC_KEY_IMPORT */ #ifndef NO_ASN /** Convert ECC R,S to signature r R component of signature s S component of signature out DER-encoded ECDSA signature outlen [in/out] output buffer size, output signature size return MP_OKAY on success */ int wc_ecc_rs_to_sig(const char* r, const char* s, byte* out, word32* outlen) { int err; mp_int rtmp; mp_int stmp; if (r == NULL || s == NULL || out == NULL || outlen == NULL) return ECC_BAD_ARG_E; err = mp_init_multi(&rtmp, &stmp, NULL, NULL, NULL, NULL); if (err != MP_OKAY) return err; err = mp_read_radix(&rtmp, r, MP_RADIX_HEX); if (err == MP_OKAY) err = mp_read_radix(&stmp, s, MP_RADIX_HEX); /* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */ if (err == MP_OKAY) err = StoreECC_DSA_Sig(out, outlen, &rtmp, &stmp); if (err == MP_OKAY) { if (mp_iszero(&rtmp) == MP_YES || mp_iszero(&stmp) == MP_YES) err = MP_ZERO_E; } mp_clear(&rtmp); mp_clear(&stmp); return err; } /** Convert ECC R,S raw unsigned bin to signature r R component of signature rSz R size s S component of signature sSz S size out DER-encoded ECDSA signature outlen [in/out] output buffer size, output signature size return MP_OKAY on success */ int wc_ecc_rs_raw_to_sig(const byte* r, word32 rSz, const byte* s, word32 sSz, byte* out, word32* outlen) { int err; mp_int rtmp; mp_int stmp; if (r == NULL || s == NULL || out == NULL || outlen == NULL) return ECC_BAD_ARG_E; err = mp_init_multi(&rtmp, &stmp, NULL, NULL, NULL, NULL); if (err != MP_OKAY) return err; err = mp_read_unsigned_bin(&rtmp, r, rSz); if (err == MP_OKAY) err = mp_read_unsigned_bin(&stmp, s, sSz); /* convert mp_ints to ECDSA sig, initializes rtmp and stmp internally */ if (err == MP_OKAY) err = StoreECC_DSA_Sig(out, outlen, &rtmp, &stmp); if (err == MP_OKAY) { if (mp_iszero(&rtmp) == MP_YES || mp_iszero(&stmp) == MP_YES) err = MP_ZERO_E; } mp_clear(&rtmp); mp_clear(&stmp); return err; } /** Convert ECC signature to R,S sig DER-encoded ECDSA signature sigLen length of signature in octets r R component of signature rLen [in/out] output "r" buffer size, output "r" size s S component of signature sLen [in/out] output "s" buffer size, output "s" size return MP_OKAY on success, negative on error */ int wc_ecc_sig_to_rs(const byte* sig, word32 sigLen, byte* r, word32* rLen, byte* s, word32* sLen) { int err; word32 x = 0; mp_int rtmp; mp_int stmp; if (sig == NULL || r == NULL || rLen == NULL || s == NULL || sLen == NULL) return ECC_BAD_ARG_E; err = DecodeECC_DSA_Sig(sig, sigLen, &rtmp, &stmp); /* extract r */ if (err == MP_OKAY) { x = mp_unsigned_bin_size(&rtmp); if (*rLen < x) err = BUFFER_E; if (err == MP_OKAY) { *rLen = x; err = mp_to_unsigned_bin(&rtmp, r); } } /* extract s */ if (err == MP_OKAY) { x = mp_unsigned_bin_size(&stmp); if (*sLen < x) err = BUFFER_E; if (err == MP_OKAY) { *sLen = x; err = mp_to_unsigned_bin(&stmp, s); } } mp_clear(&rtmp); mp_clear(&stmp); return err; } #endif /* !NO_ASN */ #ifdef HAVE_ECC_KEY_IMPORT static int wc_ecc_import_raw_private(ecc_key* key, const char* qx, const char* qy, const char* d, int curve_id, int encType) { int err = MP_OKAY; /* if d is NULL, only import as public key using Qx,Qy */ if (key == NULL || qx == NULL || qy == NULL) { return BAD_FUNC_ARG; } /* make sure required variables are reset */ wc_ecc_reset(key); /* set curve type and index */ err = wc_ecc_set_curve(key, 0, curve_id); if (err != 0) { return err; } #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ err = BAD_COND_E; #else /* init key */ #ifdef ALT_ECC_SIZE key->pubkey.x = (mp_int*)&key->pubkey.xyz[0]; key->pubkey.y = (mp_int*)&key->pubkey.xyz[1]; key->pubkey.z = (mp_int*)&key->pubkey.xyz[2]; alt_fp_init(key->pubkey.x); alt_fp_init(key->pubkey.y); alt_fp_init(key->pubkey.z); err = mp_init(&key->k); #else err = mp_init_multi(&key->k, key->pubkey.x, key->pubkey.y, key->pubkey.z, NULL, NULL); #endif if (err != MP_OKAY) return MEMORY_E; /* read Qx */ if (err == MP_OKAY) { if (encType == ECC_TYPE_HEX_STR) err = mp_read_radix(key->pubkey.x, qx, MP_RADIX_HEX); else err = mp_read_unsigned_bin(key->pubkey.x, (const byte*)qx, key->dp->size); } /* read Qy */ if (err == MP_OKAY) { if (encType == ECC_TYPE_HEX_STR) err = mp_read_radix(key->pubkey.y, qy, MP_RADIX_HEX); else err = mp_read_unsigned_bin(key->pubkey.y, (const byte*)qy, key->dp->size); } if (err == MP_OKAY) err = mp_set(key->pubkey.z, 1); /* import private key */ if (err == MP_OKAY) { if (d != NULL) { key->type = ECC_PRIVATEKEY; if (encType == ECC_TYPE_HEX_STR) err = mp_read_radix(&key->k, d, MP_RADIX_HEX); else err = mp_read_unsigned_bin(&key->k, (const byte*)d, key->dp->size); } else { key->type = ECC_PUBLICKEY; } } #ifdef WOLFSSL_VALIDATE_ECC_IMPORT if (err == MP_OKAY) err = wc_ecc_check_key(key); #endif if (err != MP_OKAY) { mp_clear(key->pubkey.x); mp_clear(key->pubkey.y); mp_clear(key->pubkey.z); mp_clear(&key->k); } #endif /* WOLFSSL_ATECC508A */ return err; } /** Import raw ECC key key The destination ecc_key structure qx x component of the public key, as ASCII hex string qy y component of the public key, as ASCII hex string d private key, as ASCII hex string, optional if importing public key only dp Custom ecc_set_type return MP_OKAY on success */ int wc_ecc_import_raw_ex(ecc_key* key, const char* qx, const char* qy, const char* d, int curve_id) { return wc_ecc_import_raw_private(key, qx, qy, d, curve_id, ECC_TYPE_HEX_STR); } /* Import x, y and optional private (d) as unsigned binary */ int wc_ecc_import_unsigned(ecc_key* key, byte* qx, byte* qy, byte* d, int curve_id) { return wc_ecc_import_raw_private(key, (const char*)qx, (const char*)qy, (const char*)d, curve_id, ECC_TYPE_UNSIGNED_BIN); } /** Import raw ECC key key The destination ecc_key structure qx x component of the public key, as ASCII hex string qy y component of the public key, as ASCII hex string d private key, as ASCII hex string, optional if importing public key only curveName ECC curve name, from ecc_sets[] return MP_OKAY on success */ int wc_ecc_import_raw(ecc_key* key, const char* qx, const char* qy, const char* d, const char* curveName) { int err, x; /* if d is NULL, only import as public key using Qx,Qy */ if (key == NULL || qx == NULL || qy == NULL || curveName == NULL) { return BAD_FUNC_ARG; } /* set curve type and index */ for (x = 0; ecc_sets[x].size != 0; x++) { if (XSTRNCMP(ecc_sets[x].name, curveName, XSTRLEN(curveName)) == 0) { break; } } if (ecc_sets[x].size == 0) { WOLFSSL_MSG("ecc_set curve name not found"); err = ASN_PARSE_E; } else { return wc_ecc_import_raw_private(key, qx, qy, d, ecc_sets[x].id, ECC_TYPE_HEX_STR); } return err; } #endif /* HAVE_ECC_KEY_IMPORT */ /* key size in octets */ int wc_ecc_size(ecc_key* key) { if (key == NULL) return 0; return key->dp->size; } int wc_ecc_sig_size_calc(int sz) { return (sz * 2) + SIG_HEADER_SZ + ECC_MAX_PAD_SZ; } /* worst case estimate, check actual return from wc_ecc_sign_hash for actual value of signature size in octets */ int wc_ecc_sig_size(ecc_key* key) { int sz = wc_ecc_size(key); if (sz <= 0) return sz; return wc_ecc_sig_size_calc(sz); } #ifdef FP_ECC /* fixed point ECC cache */ /* number of entries in the cache */ #ifndef FP_ENTRIES #define FP_ENTRIES 15 #endif /* number of bits in LUT */ #ifndef FP_LUT #define FP_LUT 8U #endif #ifdef ECC_SHAMIR /* Sharmir requires a bigger LUT, TAO */ #if (FP_LUT > 12) || (FP_LUT < 4) #error FP_LUT must be between 4 and 12 inclusively #endif #else #if (FP_LUT > 12) || (FP_LUT < 2) #error FP_LUT must be between 2 and 12 inclusively #endif #endif #ifndef WOLFSSL_SP_MATH /** Our FP cache */ typedef struct { ecc_point* g; /* cached COPY of base point */ ecc_point* LUT[1U<<FP_LUT]; /* fixed point lookup */ mp_int mu; /* copy of the montgomery constant */ int lru_count; /* amount of times this entry has been used */ int lock; /* flag to indicate cache eviction */ /* permitted (0) or not (1) */ } fp_cache_t; /* if HAVE_THREAD_LS this cache is per thread, no locking needed */ static THREAD_LS_T fp_cache_t fp_cache[FP_ENTRIES]; #ifndef HAVE_THREAD_LS static volatile int initMutex = 0; /* prevent multiple mutex inits */ static wolfSSL_Mutex ecc_fp_lock; #endif /* HAVE_THREAD_LS */ /* simple table to help direct the generation of the LUT */ static const struct { int ham, terma, termb; } lut_orders[] = { { 0, 0, 0 }, { 1, 0, 0 }, { 1, 0, 0 }, { 2, 1, 2 }, { 1, 0, 0 }, { 2, 1, 4 }, { 2, 2, 4 }, { 3, 3, 4 }, { 1, 0, 0 }, { 2, 1, 8 }, { 2, 2, 8 }, { 3, 3, 8 }, { 2, 4, 8 }, { 3, 5, 8 }, { 3, 6, 8 }, { 4, 7, 8 }, { 1, 0, 0 }, { 2, 1, 16 }, { 2, 2, 16 }, { 3, 3, 16 }, { 2, 4, 16 }, { 3, 5, 16 }, { 3, 6, 16 }, { 4, 7, 16 }, { 2, 8, 16 }, { 3, 9, 16 }, { 3, 10, 16 }, { 4, 11, 16 }, { 3, 12, 16 }, { 4, 13, 16 }, { 4, 14, 16 }, { 5, 15, 16 }, { 1, 0, 0 }, { 2, 1, 32 }, { 2, 2, 32 }, { 3, 3, 32 }, { 2, 4, 32 }, { 3, 5, 32 }, { 3, 6, 32 }, { 4, 7, 32 }, { 2, 8, 32 }, { 3, 9, 32 }, { 3, 10, 32 }, { 4, 11, 32 }, { 3, 12, 32 }, { 4, 13, 32 }, { 4, 14, 32 }, { 5, 15, 32 }, { 2, 16, 32 }, { 3, 17, 32 }, { 3, 18, 32 }, { 4, 19, 32 }, { 3, 20, 32 }, { 4, 21, 32 }, { 4, 22, 32 }, { 5, 23, 32 }, { 3, 24, 32 }, { 4, 25, 32 }, { 4, 26, 32 }, { 5, 27, 32 }, { 4, 28, 32 }, { 5, 29, 32 }, { 5, 30, 32 }, { 6, 31, 32 }, #if FP_LUT > 6 { 1, 0, 0 }, { 2, 1, 64 }, { 2, 2, 64 }, { 3, 3, 64 }, { 2, 4, 64 }, { 3, 5, 64 }, { 3, 6, 64 }, { 4, 7, 64 }, { 2, 8, 64 }, { 3, 9, 64 }, { 3, 10, 64 }, { 4, 11, 64 }, { 3, 12, 64 }, { 4, 13, 64 }, { 4, 14, 64 }, { 5, 15, 64 }, { 2, 16, 64 }, { 3, 17, 64 }, { 3, 18, 64 }, { 4, 19, 64 }, { 3, 20, 64 }, { 4, 21, 64 }, { 4, 22, 64 }, { 5, 23, 64 }, { 3, 24, 64 }, { 4, 25, 64 }, { 4, 26, 64 }, { 5, 27, 64 }, { 4, 28, 64 }, { 5, 29, 64 }, { 5, 30, 64 }, { 6, 31, 64 }, { 2, 32, 64 }, { 3, 33, 64 }, { 3, 34, 64 }, { 4, 35, 64 }, { 3, 36, 64 }, { 4, 37, 64 }, { 4, 38, 64 }, { 5, 39, 64 }, { 3, 40, 64 }, { 4, 41, 64 }, { 4, 42, 64 }, { 5, 43, 64 }, { 4, 44, 64 }, { 5, 45, 64 }, { 5, 46, 64 }, { 6, 47, 64 }, { 3, 48, 64 }, { 4, 49, 64 }, { 4, 50, 64 }, { 5, 51, 64 }, { 4, 52, 64 }, { 5, 53, 64 }, { 5, 54, 64 }, { 6, 55, 64 }, { 4, 56, 64 }, { 5, 57, 64 }, { 5, 58, 64 }, { 6, 59, 64 }, { 5, 60, 64 }, { 6, 61, 64 }, { 6, 62, 64 }, { 7, 63, 64 }, #if FP_LUT > 7 { 1, 0, 0 }, { 2, 1, 128 }, { 2, 2, 128 }, { 3, 3, 128 }, { 2, 4, 128 }, { 3, 5, 128 }, { 3, 6, 128 }, { 4, 7, 128 }, { 2, 8, 128 }, { 3, 9, 128 }, { 3, 10, 128 }, { 4, 11, 128 }, { 3, 12, 128 }, { 4, 13, 128 }, { 4, 14, 128 }, { 5, 15, 128 }, { 2, 16, 128 }, { 3, 17, 128 }, { 3, 18, 128 }, { 4, 19, 128 }, { 3, 20, 128 }, { 4, 21, 128 }, { 4, 22, 128 }, { 5, 23, 128 }, { 3, 24, 128 }, { 4, 25, 128 }, { 4, 26, 128 }, { 5, 27, 128 }, { 4, 28, 128 }, { 5, 29, 128 }, { 5, 30, 128 }, { 6, 31, 128 }, { 2, 32, 128 }, { 3, 33, 128 }, { 3, 34, 128 }, { 4, 35, 128 }, { 3, 36, 128 }, { 4, 37, 128 }, { 4, 38, 128 }, { 5, 39, 128 }, { 3, 40, 128 }, { 4, 41, 128 }, { 4, 42, 128 }, { 5, 43, 128 }, { 4, 44, 128 }, { 5, 45, 128 }, { 5, 46, 128 }, { 6, 47, 128 }, { 3, 48, 128 }, { 4, 49, 128 }, { 4, 50, 128 }, { 5, 51, 128 }, { 4, 52, 128 }, { 5, 53, 128 }, { 5, 54, 128 }, { 6, 55, 128 }, { 4, 56, 128 }, { 5, 57, 128 }, { 5, 58, 128 }, { 6, 59, 128 }, { 5, 60, 128 }, { 6, 61, 128 }, { 6, 62, 128 }, { 7, 63, 128 }, { 2, 64, 128 }, { 3, 65, 128 }, { 3, 66, 128 }, { 4, 67, 128 }, { 3, 68, 128 }, { 4, 69, 128 }, { 4, 70, 128 }, { 5, 71, 128 }, { 3, 72, 128 }, { 4, 73, 128 }, { 4, 74, 128 }, { 5, 75, 128 }, { 4, 76, 128 }, { 5, 77, 128 }, { 5, 78, 128 }, { 6, 79, 128 }, { 3, 80, 128 }, { 4, 81, 128 }, { 4, 82, 128 }, { 5, 83, 128 }, { 4, 84, 128 }, { 5, 85, 128 }, { 5, 86, 128 }, { 6, 87, 128 }, { 4, 88, 128 }, { 5, 89, 128 }, { 5, 90, 128 }, { 6, 91, 128 }, { 5, 92, 128 }, { 6, 93, 128 }, { 6, 94, 128 }, { 7, 95, 128 }, { 3, 96, 128 }, { 4, 97, 128 }, { 4, 98, 128 }, { 5, 99, 128 }, { 4, 100, 128 }, { 5, 101, 128 }, { 5, 102, 128 }, { 6, 103, 128 }, { 4, 104, 128 }, { 5, 105, 128 }, { 5, 106, 128 }, { 6, 107, 128 }, { 5, 108, 128 }, { 6, 109, 128 }, { 6, 110, 128 }, { 7, 111, 128 }, { 4, 112, 128 }, { 5, 113, 128 }, { 5, 114, 128 }, { 6, 115, 128 }, { 5, 116, 128 }, { 6, 117, 128 }, { 6, 118, 128 }, { 7, 119, 128 }, { 5, 120, 128 }, { 6, 121, 128 }, { 6, 122, 128 }, { 7, 123, 128 }, { 6, 124, 128 }, { 7, 125, 128 }, { 7, 126, 128 }, { 8, 127, 128 }, #if FP_LUT > 8 { 1, 0, 0 }, { 2, 1, 256 }, { 2, 2, 256 }, { 3, 3, 256 }, { 2, 4, 256 }, { 3, 5, 256 }, { 3, 6, 256 }, { 4, 7, 256 }, { 2, 8, 256 }, { 3, 9, 256 }, { 3, 10, 256 }, { 4, 11, 256 }, { 3, 12, 256 }, { 4, 13, 256 }, { 4, 14, 256 }, { 5, 15, 256 }, { 2, 16, 256 }, { 3, 17, 256 }, { 3, 18, 256 }, { 4, 19, 256 }, { 3, 20, 256 }, { 4, 21, 256 }, { 4, 22, 256 }, { 5, 23, 256 }, { 3, 24, 256 }, { 4, 25, 256 }, { 4, 26, 256 }, { 5, 27, 256 }, { 4, 28, 256 }, { 5, 29, 256 }, { 5, 30, 256 }, { 6, 31, 256 }, { 2, 32, 256 }, { 3, 33, 256 }, { 3, 34, 256 }, { 4, 35, 256 }, { 3, 36, 256 }, { 4, 37, 256 }, { 4, 38, 256 }, { 5, 39, 256 }, { 3, 40, 256 }, { 4, 41, 256 }, { 4, 42, 256 }, { 5, 43, 256 }, { 4, 44, 256 }, { 5, 45, 256 }, { 5, 46, 256 }, { 6, 47, 256 }, { 3, 48, 256 }, { 4, 49, 256 }, { 4, 50, 256 }, { 5, 51, 256 }, { 4, 52, 256 }, { 5, 53, 256 }, { 5, 54, 256 }, { 6, 55, 256 }, { 4, 56, 256 }, { 5, 57, 256 }, { 5, 58, 256 }, { 6, 59, 256 }, { 5, 60, 256 }, { 6, 61, 256 }, { 6, 62, 256 }, { 7, 63, 256 }, { 2, 64, 256 }, { 3, 65, 256 }, { 3, 66, 256 }, { 4, 67, 256 }, { 3, 68, 256 }, { 4, 69, 256 }, { 4, 70, 256 }, { 5, 71, 256 }, { 3, 72, 256 }, { 4, 73, 256 }, { 4, 74, 256 }, { 5, 75, 256 }, { 4, 76, 256 }, { 5, 77, 256 }, { 5, 78, 256 }, { 6, 79, 256 }, { 3, 80, 256 }, { 4, 81, 256 }, { 4, 82, 256 }, { 5, 83, 256 }, { 4, 84, 256 }, { 5, 85, 256 }, { 5, 86, 256 }, { 6, 87, 256 }, { 4, 88, 256 }, { 5, 89, 256 }, { 5, 90, 256 }, { 6, 91, 256 }, { 5, 92, 256 }, { 6, 93, 256 }, { 6, 94, 256 }, { 7, 95, 256 }, { 3, 96, 256 }, { 4, 97, 256 }, { 4, 98, 256 }, { 5, 99, 256 }, { 4, 100, 256 }, { 5, 101, 256 }, { 5, 102, 256 }, { 6, 103, 256 }, { 4, 104, 256 }, { 5, 105, 256 }, { 5, 106, 256 }, { 6, 107, 256 }, { 5, 108, 256 }, { 6, 109, 256 }, { 6, 110, 256 }, { 7, 111, 256 }, { 4, 112, 256 }, { 5, 113, 256 }, { 5, 114, 256 }, { 6, 115, 256 }, { 5, 116, 256 }, { 6, 117, 256 }, { 6, 118, 256 }, { 7, 119, 256 }, { 5, 120, 256 }, { 6, 121, 256 }, { 6, 122, 256 }, { 7, 123, 256 }, { 6, 124, 256 }, { 7, 125, 256 }, { 7, 126, 256 }, { 8, 127, 256 }, { 2, 128, 256 }, { 3, 129, 256 }, { 3, 130, 256 }, { 4, 131, 256 }, { 3, 132, 256 }, { 4, 133, 256 }, { 4, 134, 256 }, { 5, 135, 256 }, { 3, 136, 256 }, { 4, 137, 256 }, { 4, 138, 256 }, { 5, 139, 256 }, { 4, 140, 256 }, { 5, 141, 256 }, { 5, 142, 256 }, { 6, 143, 256 }, { 3, 144, 256 }, { 4, 145, 256 }, { 4, 146, 256 }, { 5, 147, 256 }, { 4, 148, 256 }, { 5, 149, 256 }, { 5, 150, 256 }, { 6, 151, 256 }, { 4, 152, 256 }, { 5, 153, 256 }, { 5, 154, 256 }, { 6, 155, 256 }, { 5, 156, 256 }, { 6, 157, 256 }, { 6, 158, 256 }, { 7, 159, 256 }, { 3, 160, 256 }, { 4, 161, 256 }, { 4, 162, 256 }, { 5, 163, 256 }, { 4, 164, 256 }, { 5, 165, 256 }, { 5, 166, 256 }, { 6, 167, 256 }, { 4, 168, 256 }, { 5, 169, 256 }, { 5, 170, 256 }, { 6, 171, 256 }, { 5, 172, 256 }, { 6, 173, 256 }, { 6, 174, 256 }, { 7, 175, 256 }, { 4, 176, 256 }, { 5, 177, 256 }, { 5, 178, 256 }, { 6, 179, 256 }, { 5, 180, 256 }, { 6, 181, 256 }, { 6, 182, 256 }, { 7, 183, 256 }, { 5, 184, 256 }, { 6, 185, 256 }, { 6, 186, 256 }, { 7, 187, 256 }, { 6, 188, 256 }, { 7, 189, 256 }, { 7, 190, 256 }, { 8, 191, 256 }, { 3, 192, 256 }, { 4, 193, 256 }, { 4, 194, 256 }, { 5, 195, 256 }, { 4, 196, 256 }, { 5, 197, 256 }, { 5, 198, 256 }, { 6, 199, 256 }, { 4, 200, 256 }, { 5, 201, 256 }, { 5, 202, 256 }, { 6, 203, 256 }, { 5, 204, 256 }, { 6, 205, 256 }, { 6, 206, 256 }, { 7, 207, 256 }, { 4, 208, 256 }, { 5, 209, 256 }, { 5, 210, 256 }, { 6, 211, 256 }, { 5, 212, 256 }, { 6, 213, 256 }, { 6, 214, 256 }, { 7, 215, 256 }, { 5, 216, 256 }, { 6, 217, 256 }, { 6, 218, 256 }, { 7, 219, 256 }, { 6, 220, 256 }, { 7, 221, 256 }, { 7, 222, 256 }, { 8, 223, 256 }, { 4, 224, 256 }, { 5, 225, 256 }, { 5, 226, 256 }, { 6, 227, 256 }, { 5, 228, 256 }, { 6, 229, 256 }, { 6, 230, 256 }, { 7, 231, 256 }, { 5, 232, 256 }, { 6, 233, 256 }, { 6, 234, 256 }, { 7, 235, 256 }, { 6, 236, 256 }, { 7, 237, 256 }, { 7, 238, 256 }, { 8, 239, 256 }, { 5, 240, 256 }, { 6, 241, 256 }, { 6, 242, 256 }, { 7, 243, 256 }, { 6, 244, 256 }, { 7, 245, 256 }, { 7, 246, 256 }, { 8, 247, 256 }, { 6, 248, 256 }, { 7, 249, 256 }, { 7, 250, 256 }, { 8, 251, 256 }, { 7, 252, 256 }, { 8, 253, 256 }, { 8, 254, 256 }, { 9, 255, 256 }, #if FP_LUT > 9 { 1, 0, 0 }, { 2, 1, 512 }, { 2, 2, 512 }, { 3, 3, 512 }, { 2, 4, 512 }, { 3, 5, 512 }, { 3, 6, 512 }, { 4, 7, 512 }, { 2, 8, 512 }, { 3, 9, 512 }, { 3, 10, 512 }, { 4, 11, 512 }, { 3, 12, 512 }, { 4, 13, 512 }, { 4, 14, 512 }, { 5, 15, 512 }, { 2, 16, 512 }, { 3, 17, 512 }, { 3, 18, 512 }, { 4, 19, 512 }, { 3, 20, 512 }, { 4, 21, 512 }, { 4, 22, 512 }, { 5, 23, 512 }, { 3, 24, 512 }, { 4, 25, 512 }, { 4, 26, 512 }, { 5, 27, 512 }, { 4, 28, 512 }, { 5, 29, 512 }, { 5, 30, 512 }, { 6, 31, 512 }, { 2, 32, 512 }, { 3, 33, 512 }, { 3, 34, 512 }, { 4, 35, 512 }, { 3, 36, 512 }, { 4, 37, 512 }, { 4, 38, 512 }, { 5, 39, 512 }, { 3, 40, 512 }, { 4, 41, 512 }, { 4, 42, 512 }, { 5, 43, 512 }, { 4, 44, 512 }, { 5, 45, 512 }, { 5, 46, 512 }, { 6, 47, 512 }, { 3, 48, 512 }, { 4, 49, 512 }, { 4, 50, 512 }, { 5, 51, 512 }, { 4, 52, 512 }, { 5, 53, 512 }, { 5, 54, 512 }, { 6, 55, 512 }, { 4, 56, 512 }, { 5, 57, 512 }, { 5, 58, 512 }, { 6, 59, 512 }, { 5, 60, 512 }, { 6, 61, 512 }, { 6, 62, 512 }, { 7, 63, 512 }, { 2, 64, 512 }, { 3, 65, 512 }, { 3, 66, 512 }, { 4, 67, 512 }, { 3, 68, 512 }, { 4, 69, 512 }, { 4, 70, 512 }, { 5, 71, 512 }, { 3, 72, 512 }, { 4, 73, 512 }, { 4, 74, 512 }, { 5, 75, 512 }, { 4, 76, 512 }, { 5, 77, 512 }, { 5, 78, 512 }, { 6, 79, 512 }, { 3, 80, 512 }, { 4, 81, 512 }, { 4, 82, 512 }, { 5, 83, 512 }, { 4, 84, 512 }, { 5, 85, 512 }, { 5, 86, 512 }, { 6, 87, 512 }, { 4, 88, 512 }, { 5, 89, 512 }, { 5, 90, 512 }, { 6, 91, 512 }, { 5, 92, 512 }, { 6, 93, 512 }, { 6, 94, 512 }, { 7, 95, 512 }, { 3, 96, 512 }, { 4, 97, 512 }, { 4, 98, 512 }, { 5, 99, 512 }, { 4, 100, 512 }, { 5, 101, 512 }, { 5, 102, 512 }, { 6, 103, 512 }, { 4, 104, 512 }, { 5, 105, 512 }, { 5, 106, 512 }, { 6, 107, 512 }, { 5, 108, 512 }, { 6, 109, 512 }, { 6, 110, 512 }, { 7, 111, 512 }, { 4, 112, 512 }, { 5, 113, 512 }, { 5, 114, 512 }, { 6, 115, 512 }, { 5, 116, 512 }, { 6, 117, 512 }, { 6, 118, 512 }, { 7, 119, 512 }, { 5, 120, 512 }, { 6, 121, 512 }, { 6, 122, 512 }, { 7, 123, 512 }, { 6, 124, 512 }, { 7, 125, 512 }, { 7, 126, 512 }, { 8, 127, 512 }, { 2, 128, 512 }, { 3, 129, 512 }, { 3, 130, 512 }, { 4, 131, 512 }, { 3, 132, 512 }, { 4, 133, 512 }, { 4, 134, 512 }, { 5, 135, 512 }, { 3, 136, 512 }, { 4, 137, 512 }, { 4, 138, 512 }, { 5, 139, 512 }, { 4, 140, 512 }, { 5, 141, 512 }, { 5, 142, 512 }, { 6, 143, 512 }, { 3, 144, 512 }, { 4, 145, 512 }, { 4, 146, 512 }, { 5, 147, 512 }, { 4, 148, 512 }, { 5, 149, 512 }, { 5, 150, 512 }, { 6, 151, 512 }, { 4, 152, 512 }, { 5, 153, 512 }, { 5, 154, 512 }, { 6, 155, 512 }, { 5, 156, 512 }, { 6, 157, 512 }, { 6, 158, 512 }, { 7, 159, 512 }, { 3, 160, 512 }, { 4, 161, 512 }, { 4, 162, 512 }, { 5, 163, 512 }, { 4, 164, 512 }, { 5, 165, 512 }, { 5, 166, 512 }, { 6, 167, 512 }, { 4, 168, 512 }, { 5, 169, 512 }, { 5, 170, 512 }, { 6, 171, 512 }, { 5, 172, 512 }, { 6, 173, 512 }, { 6, 174, 512 }, { 7, 175, 512 }, { 4, 176, 512 }, { 5, 177, 512 }, { 5, 178, 512 }, { 6, 179, 512 }, { 5, 180, 512 }, { 6, 181, 512 }, { 6, 182, 512 }, { 7, 183, 512 }, { 5, 184, 512 }, { 6, 185, 512 }, { 6, 186, 512 }, { 7, 187, 512 }, { 6, 188, 512 }, { 7, 189, 512 }, { 7, 190, 512 }, { 8, 191, 512 }, { 3, 192, 512 }, { 4, 193, 512 }, { 4, 194, 512 }, { 5, 195, 512 }, { 4, 196, 512 }, { 5, 197, 512 }, { 5, 198, 512 }, { 6, 199, 512 }, { 4, 200, 512 }, { 5, 201, 512 }, { 5, 202, 512 }, { 6, 203, 512 }, { 5, 204, 512 }, { 6, 205, 512 }, { 6, 206, 512 }, { 7, 207, 512 }, { 4, 208, 512 }, { 5, 209, 512 }, { 5, 210, 512 }, { 6, 211, 512 }, { 5, 212, 512 }, { 6, 213, 512 }, { 6, 214, 512 }, { 7, 215, 512 }, { 5, 216, 512 }, { 6, 217, 512 }, { 6, 218, 512 }, { 7, 219, 512 }, { 6, 220, 512 }, { 7, 221, 512 }, { 7, 222, 512 }, { 8, 223, 512 }, { 4, 224, 512 }, { 5, 225, 512 }, { 5, 226, 512 }, { 6, 227, 512 }, { 5, 228, 512 }, { 6, 229, 512 }, { 6, 230, 512 }, { 7, 231, 512 }, { 5, 232, 512 }, { 6, 233, 512 }, { 6, 234, 512 }, { 7, 235, 512 }, { 6, 236, 512 }, { 7, 237, 512 }, { 7, 238, 512 }, { 8, 239, 512 }, { 5, 240, 512 }, { 6, 241, 512 }, { 6, 242, 512 }, { 7, 243, 512 }, { 6, 244, 512 }, { 7, 245, 512 }, { 7, 246, 512 }, { 8, 247, 512 }, { 6, 248, 512 }, { 7, 249, 512 }, { 7, 250, 512 }, { 8, 251, 512 }, { 7, 252, 512 }, { 8, 253, 512 }, { 8, 254, 512 }, { 9, 255, 512 }, { 2, 256, 512 }, { 3, 257, 512 }, { 3, 258, 512 }, { 4, 259, 512 }, { 3, 260, 512 }, { 4, 261, 512 }, { 4, 262, 512 }, { 5, 263, 512 }, { 3, 264, 512 }, { 4, 265, 512 }, { 4, 266, 512 }, { 5, 267, 512 }, { 4, 268, 512 }, { 5, 269, 512 }, { 5, 270, 512 }, { 6, 271, 512 }, { 3, 272, 512 }, { 4, 273, 512 }, { 4, 274, 512 }, { 5, 275, 512 }, { 4, 276, 512 }, { 5, 277, 512 }, { 5, 278, 512 }, { 6, 279, 512 }, { 4, 280, 512 }, { 5, 281, 512 }, { 5, 282, 512 }, { 6, 283, 512 }, { 5, 284, 512 }, { 6, 285, 512 }, { 6, 286, 512 }, { 7, 287, 512 }, { 3, 288, 512 }, { 4, 289, 512 }, { 4, 290, 512 }, { 5, 291, 512 }, { 4, 292, 512 }, { 5, 293, 512 }, { 5, 294, 512 }, { 6, 295, 512 }, { 4, 296, 512 }, { 5, 297, 512 }, { 5, 298, 512 }, { 6, 299, 512 }, { 5, 300, 512 }, { 6, 301, 512 }, { 6, 302, 512 }, { 7, 303, 512 }, { 4, 304, 512 }, { 5, 305, 512 }, { 5, 306, 512 }, { 6, 307, 512 }, { 5, 308, 512 }, { 6, 309, 512 }, { 6, 310, 512 }, { 7, 311, 512 }, { 5, 312, 512 }, { 6, 313, 512 }, { 6, 314, 512 }, { 7, 315, 512 }, { 6, 316, 512 }, { 7, 317, 512 }, { 7, 318, 512 }, { 8, 319, 512 }, { 3, 320, 512 }, { 4, 321, 512 }, { 4, 322, 512 }, { 5, 323, 512 }, { 4, 324, 512 }, { 5, 325, 512 }, { 5, 326, 512 }, { 6, 327, 512 }, { 4, 328, 512 }, { 5, 329, 512 }, { 5, 330, 512 }, { 6, 331, 512 }, { 5, 332, 512 }, { 6, 333, 512 }, { 6, 334, 512 }, { 7, 335, 512 }, { 4, 336, 512 }, { 5, 337, 512 }, { 5, 338, 512 }, { 6, 339, 512 }, { 5, 340, 512 }, { 6, 341, 512 }, { 6, 342, 512 }, { 7, 343, 512 }, { 5, 344, 512 }, { 6, 345, 512 }, { 6, 346, 512 }, { 7, 347, 512 }, { 6, 348, 512 }, { 7, 349, 512 }, { 7, 350, 512 }, { 8, 351, 512 }, { 4, 352, 512 }, { 5, 353, 512 }, { 5, 354, 512 }, { 6, 355, 512 }, { 5, 356, 512 }, { 6, 357, 512 }, { 6, 358, 512 }, { 7, 359, 512 }, { 5, 360, 512 }, { 6, 361, 512 }, { 6, 362, 512 }, { 7, 363, 512 }, { 6, 364, 512 }, { 7, 365, 512 }, { 7, 366, 512 }, { 8, 367, 512 }, { 5, 368, 512 }, { 6, 369, 512 }, { 6, 370, 512 }, { 7, 371, 512 }, { 6, 372, 512 }, { 7, 373, 512 }, { 7, 374, 512 }, { 8, 375, 512 }, { 6, 376, 512 }, { 7, 377, 512 }, { 7, 378, 512 }, { 8, 379, 512 }, { 7, 380, 512 }, { 8, 381, 512 }, { 8, 382, 512 }, { 9, 383, 512 }, { 3, 384, 512 }, { 4, 385, 512 }, { 4, 386, 512 }, { 5, 387, 512 }, { 4, 388, 512 }, { 5, 389, 512 }, { 5, 390, 512 }, { 6, 391, 512 }, { 4, 392, 512 }, { 5, 393, 512 }, { 5, 394, 512 }, { 6, 395, 512 }, { 5, 396, 512 }, { 6, 397, 512 }, { 6, 398, 512 }, { 7, 399, 512 }, { 4, 400, 512 }, { 5, 401, 512 }, { 5, 402, 512 }, { 6, 403, 512 }, { 5, 404, 512 }, { 6, 405, 512 }, { 6, 406, 512 }, { 7, 407, 512 }, { 5, 408, 512 }, { 6, 409, 512 }, { 6, 410, 512 }, { 7, 411, 512 }, { 6, 412, 512 }, { 7, 413, 512 }, { 7, 414, 512 }, { 8, 415, 512 }, { 4, 416, 512 }, { 5, 417, 512 }, { 5, 418, 512 }, { 6, 419, 512 }, { 5, 420, 512 }, { 6, 421, 512 }, { 6, 422, 512 }, { 7, 423, 512 }, { 5, 424, 512 }, { 6, 425, 512 }, { 6, 426, 512 }, { 7, 427, 512 }, { 6, 428, 512 }, { 7, 429, 512 }, { 7, 430, 512 }, { 8, 431, 512 }, { 5, 432, 512 }, { 6, 433, 512 }, { 6, 434, 512 }, { 7, 435, 512 }, { 6, 436, 512 }, { 7, 437, 512 }, { 7, 438, 512 }, { 8, 439, 512 }, { 6, 440, 512 }, { 7, 441, 512 }, { 7, 442, 512 }, { 8, 443, 512 }, { 7, 444, 512 }, { 8, 445, 512 }, { 8, 446, 512 }, { 9, 447, 512 }, { 4, 448, 512 }, { 5, 449, 512 }, { 5, 450, 512 }, { 6, 451, 512 }, { 5, 452, 512 }, { 6, 453, 512 }, { 6, 454, 512 }, { 7, 455, 512 }, { 5, 456, 512 }, { 6, 457, 512 }, { 6, 458, 512 }, { 7, 459, 512 }, { 6, 460, 512 }, { 7, 461, 512 }, { 7, 462, 512 }, { 8, 463, 512 }, { 5, 464, 512 }, { 6, 465, 512 }, { 6, 466, 512 }, { 7, 467, 512 }, { 6, 468, 512 }, { 7, 469, 512 }, { 7, 470, 512 }, { 8, 471, 512 }, { 6, 472, 512 }, { 7, 473, 512 }, { 7, 474, 512 }, { 8, 475, 512 }, { 7, 476, 512 }, { 8, 477, 512 }, { 8, 478, 512 }, { 9, 479, 512 }, { 5, 480, 512 }, { 6, 481, 512 }, { 6, 482, 512 }, { 7, 483, 512 }, { 6, 484, 512 }, { 7, 485, 512 }, { 7, 486, 512 }, { 8, 487, 512 }, { 6, 488, 512 }, { 7, 489, 512 }, { 7, 490, 512 }, { 8, 491, 512 }, { 7, 492, 512 }, { 8, 493, 512 }, { 8, 494, 512 }, { 9, 495, 512 }, { 6, 496, 512 }, { 7, 497, 512 }, { 7, 498, 512 }, { 8, 499, 512 }, { 7, 500, 512 }, { 8, 501, 512 }, { 8, 502, 512 }, { 9, 503, 512 }, { 7, 504, 512 }, { 8, 505, 512 }, { 8, 506, 512 }, { 9, 507, 512 }, { 8, 508, 512 }, { 9, 509, 512 }, { 9, 510, 512 }, { 10, 511, 512 }, #if FP_LUT > 10 { 1, 0, 0 }, { 2, 1, 1024 }, { 2, 2, 1024 }, { 3, 3, 1024 }, { 2, 4, 1024 }, { 3, 5, 1024 }, { 3, 6, 1024 }, { 4, 7, 1024 }, { 2, 8, 1024 }, { 3, 9, 1024 }, { 3, 10, 1024 }, { 4, 11, 1024 }, { 3, 12, 1024 }, { 4, 13, 1024 }, { 4, 14, 1024 }, { 5, 15, 1024 }, { 2, 16, 1024 }, { 3, 17, 1024 }, { 3, 18, 1024 }, { 4, 19, 1024 }, { 3, 20, 1024 }, { 4, 21, 1024 }, { 4, 22, 1024 }, { 5, 23, 1024 }, { 3, 24, 1024 }, { 4, 25, 1024 }, { 4, 26, 1024 }, { 5, 27, 1024 }, { 4, 28, 1024 }, { 5, 29, 1024 }, { 5, 30, 1024 }, { 6, 31, 1024 }, { 2, 32, 1024 }, { 3, 33, 1024 }, { 3, 34, 1024 }, { 4, 35, 1024 }, { 3, 36, 1024 }, { 4, 37, 1024 }, { 4, 38, 1024 }, { 5, 39, 1024 }, { 3, 40, 1024 }, { 4, 41, 1024 }, { 4, 42, 1024 }, { 5, 43, 1024 }, { 4, 44, 1024 }, { 5, 45, 1024 }, { 5, 46, 1024 }, { 6, 47, 1024 }, { 3, 48, 1024 }, { 4, 49, 1024 }, { 4, 50, 1024 }, { 5, 51, 1024 }, { 4, 52, 1024 }, { 5, 53, 1024 }, { 5, 54, 1024 }, { 6, 55, 1024 }, { 4, 56, 1024 }, { 5, 57, 1024 }, { 5, 58, 1024 }, { 6, 59, 1024 }, { 5, 60, 1024 }, { 6, 61, 1024 }, { 6, 62, 1024 }, { 7, 63, 1024 }, { 2, 64, 1024 }, { 3, 65, 1024 }, { 3, 66, 1024 }, { 4, 67, 1024 }, { 3, 68, 1024 }, { 4, 69, 1024 }, { 4, 70, 1024 }, { 5, 71, 1024 }, { 3, 72, 1024 }, { 4, 73, 1024 }, { 4, 74, 1024 }, { 5, 75, 1024 }, { 4, 76, 1024 }, { 5, 77, 1024 }, { 5, 78, 1024 }, { 6, 79, 1024 }, { 3, 80, 1024 }, { 4, 81, 1024 }, { 4, 82, 1024 }, { 5, 83, 1024 }, { 4, 84, 1024 }, { 5, 85, 1024 }, { 5, 86, 1024 }, { 6, 87, 1024 }, { 4, 88, 1024 }, { 5, 89, 1024 }, { 5, 90, 1024 }, { 6, 91, 1024 }, { 5, 92, 1024 }, { 6, 93, 1024 }, { 6, 94, 1024 }, { 7, 95, 1024 }, { 3, 96, 1024 }, { 4, 97, 1024 }, { 4, 98, 1024 }, { 5, 99, 1024 }, { 4, 100, 1024 }, { 5, 101, 1024 }, { 5, 102, 1024 }, { 6, 103, 1024 }, { 4, 104, 1024 }, { 5, 105, 1024 }, { 5, 106, 1024 }, { 6, 107, 1024 }, { 5, 108, 1024 }, { 6, 109, 1024 }, { 6, 110, 1024 }, { 7, 111, 1024 }, { 4, 112, 1024 }, { 5, 113, 1024 }, { 5, 114, 1024 }, { 6, 115, 1024 }, { 5, 116, 1024 }, { 6, 117, 1024 }, { 6, 118, 1024 }, { 7, 119, 1024 }, { 5, 120, 1024 }, { 6, 121, 1024 }, { 6, 122, 1024 }, { 7, 123, 1024 }, { 6, 124, 1024 }, { 7, 125, 1024 }, { 7, 126, 1024 }, { 8, 127, 1024 }, { 2, 128, 1024 }, { 3, 129, 1024 }, { 3, 130, 1024 }, { 4, 131, 1024 }, { 3, 132, 1024 }, { 4, 133, 1024 }, { 4, 134, 1024 }, { 5, 135, 1024 }, { 3, 136, 1024 }, { 4, 137, 1024 }, { 4, 138, 1024 }, { 5, 139, 1024 }, { 4, 140, 1024 }, { 5, 141, 1024 }, { 5, 142, 1024 }, { 6, 143, 1024 }, { 3, 144, 1024 }, { 4, 145, 1024 }, { 4, 146, 1024 }, { 5, 147, 1024 }, { 4, 148, 1024 }, { 5, 149, 1024 }, { 5, 150, 1024 }, { 6, 151, 1024 }, { 4, 152, 1024 }, { 5, 153, 1024 }, { 5, 154, 1024 }, { 6, 155, 1024 }, { 5, 156, 1024 }, { 6, 157, 1024 }, { 6, 158, 1024 }, { 7, 159, 1024 }, { 3, 160, 1024 }, { 4, 161, 1024 }, { 4, 162, 1024 }, { 5, 163, 1024 }, { 4, 164, 1024 }, { 5, 165, 1024 }, { 5, 166, 1024 }, { 6, 167, 1024 }, { 4, 168, 1024 }, { 5, 169, 1024 }, { 5, 170, 1024 }, { 6, 171, 1024 }, { 5, 172, 1024 }, { 6, 173, 1024 }, { 6, 174, 1024 }, { 7, 175, 1024 }, { 4, 176, 1024 }, { 5, 177, 1024 }, { 5, 178, 1024 }, { 6, 179, 1024 }, { 5, 180, 1024 }, { 6, 181, 1024 }, { 6, 182, 1024 }, { 7, 183, 1024 }, { 5, 184, 1024 }, { 6, 185, 1024 }, { 6, 186, 1024 }, { 7, 187, 1024 }, { 6, 188, 1024 }, { 7, 189, 1024 }, { 7, 190, 1024 }, { 8, 191, 1024 }, { 3, 192, 1024 }, { 4, 193, 1024 }, { 4, 194, 1024 }, { 5, 195, 1024 }, { 4, 196, 1024 }, { 5, 197, 1024 }, { 5, 198, 1024 }, { 6, 199, 1024 }, { 4, 200, 1024 }, { 5, 201, 1024 }, { 5, 202, 1024 }, { 6, 203, 1024 }, { 5, 204, 1024 }, { 6, 205, 1024 }, { 6, 206, 1024 }, { 7, 207, 1024 }, { 4, 208, 1024 }, { 5, 209, 1024 }, { 5, 210, 1024 }, { 6, 211, 1024 }, { 5, 212, 1024 }, { 6, 213, 1024 }, { 6, 214, 1024 }, { 7, 215, 1024 }, { 5, 216, 1024 }, { 6, 217, 1024 }, { 6, 218, 1024 }, { 7, 219, 1024 }, { 6, 220, 1024 }, { 7, 221, 1024 }, { 7, 222, 1024 }, { 8, 223, 1024 }, { 4, 224, 1024 }, { 5, 225, 1024 }, { 5, 226, 1024 }, { 6, 227, 1024 }, { 5, 228, 1024 }, { 6, 229, 1024 }, { 6, 230, 1024 }, { 7, 231, 1024 }, { 5, 232, 1024 }, { 6, 233, 1024 }, { 6, 234, 1024 }, { 7, 235, 1024 }, { 6, 236, 1024 }, { 7, 237, 1024 }, { 7, 238, 1024 }, { 8, 239, 1024 }, { 5, 240, 1024 }, { 6, 241, 1024 }, { 6, 242, 1024 }, { 7, 243, 1024 }, { 6, 244, 1024 }, { 7, 245, 1024 }, { 7, 246, 1024 }, { 8, 247, 1024 }, { 6, 248, 1024 }, { 7, 249, 1024 }, { 7, 250, 1024 }, { 8, 251, 1024 }, { 7, 252, 1024 }, { 8, 253, 1024 }, { 8, 254, 1024 }, { 9, 255, 1024 }, { 2, 256, 1024 }, { 3, 257, 1024 }, { 3, 258, 1024 }, { 4, 259, 1024 }, { 3, 260, 1024 }, { 4, 261, 1024 }, { 4, 262, 1024 }, { 5, 263, 1024 }, { 3, 264, 1024 }, { 4, 265, 1024 }, { 4, 266, 1024 }, { 5, 267, 1024 }, { 4, 268, 1024 }, { 5, 269, 1024 }, { 5, 270, 1024 }, { 6, 271, 1024 }, { 3, 272, 1024 }, { 4, 273, 1024 }, { 4, 274, 1024 }, { 5, 275, 1024 }, { 4, 276, 1024 }, { 5, 277, 1024 }, { 5, 278, 1024 }, { 6, 279, 1024 }, { 4, 280, 1024 }, { 5, 281, 1024 }, { 5, 282, 1024 }, { 6, 283, 1024 }, { 5, 284, 1024 }, { 6, 285, 1024 }, { 6, 286, 1024 }, { 7, 287, 1024 }, { 3, 288, 1024 }, { 4, 289, 1024 }, { 4, 290, 1024 }, { 5, 291, 1024 }, { 4, 292, 1024 }, { 5, 293, 1024 }, { 5, 294, 1024 }, { 6, 295, 1024 }, { 4, 296, 1024 }, { 5, 297, 1024 }, { 5, 298, 1024 }, { 6, 299, 1024 }, { 5, 300, 1024 }, { 6, 301, 1024 }, { 6, 302, 1024 }, { 7, 303, 1024 }, { 4, 304, 1024 }, { 5, 305, 1024 }, { 5, 306, 1024 }, { 6, 307, 1024 }, { 5, 308, 1024 }, { 6, 309, 1024 }, { 6, 310, 1024 }, { 7, 311, 1024 }, { 5, 312, 1024 }, { 6, 313, 1024 }, { 6, 314, 1024 }, { 7, 315, 1024 }, { 6, 316, 1024 }, { 7, 317, 1024 }, { 7, 318, 1024 }, { 8, 319, 1024 }, { 3, 320, 1024 }, { 4, 321, 1024 }, { 4, 322, 1024 }, { 5, 323, 1024 }, { 4, 324, 1024 }, { 5, 325, 1024 }, { 5, 326, 1024 }, { 6, 327, 1024 }, { 4, 328, 1024 }, { 5, 329, 1024 }, { 5, 330, 1024 }, { 6, 331, 1024 }, { 5, 332, 1024 }, { 6, 333, 1024 }, { 6, 334, 1024 }, { 7, 335, 1024 }, { 4, 336, 1024 }, { 5, 337, 1024 }, { 5, 338, 1024 }, { 6, 339, 1024 }, { 5, 340, 1024 }, { 6, 341, 1024 }, { 6, 342, 1024 }, { 7, 343, 1024 }, { 5, 344, 1024 }, { 6, 345, 1024 }, { 6, 346, 1024 }, { 7, 347, 1024 }, { 6, 348, 1024 }, { 7, 349, 1024 }, { 7, 350, 1024 }, { 8, 351, 1024 }, { 4, 352, 1024 }, { 5, 353, 1024 }, { 5, 354, 1024 }, { 6, 355, 1024 }, { 5, 356, 1024 }, { 6, 357, 1024 }, { 6, 358, 1024 }, { 7, 359, 1024 }, { 5, 360, 1024 }, { 6, 361, 1024 }, { 6, 362, 1024 }, { 7, 363, 1024 }, { 6, 364, 1024 }, { 7, 365, 1024 }, { 7, 366, 1024 }, { 8, 367, 1024 }, { 5, 368, 1024 }, { 6, 369, 1024 }, { 6, 370, 1024 }, { 7, 371, 1024 }, { 6, 372, 1024 }, { 7, 373, 1024 }, { 7, 374, 1024 }, { 8, 375, 1024 }, { 6, 376, 1024 }, { 7, 377, 1024 }, { 7, 378, 1024 }, { 8, 379, 1024 }, { 7, 380, 1024 }, { 8, 381, 1024 }, { 8, 382, 1024 }, { 9, 383, 1024 }, { 3, 384, 1024 }, { 4, 385, 1024 }, { 4, 386, 1024 }, { 5, 387, 1024 }, { 4, 388, 1024 }, { 5, 389, 1024 }, { 5, 390, 1024 }, { 6, 391, 1024 }, { 4, 392, 1024 }, { 5, 393, 1024 }, { 5, 394, 1024 }, { 6, 395, 1024 }, { 5, 396, 1024 }, { 6, 397, 1024 }, { 6, 398, 1024 }, { 7, 399, 1024 }, { 4, 400, 1024 }, { 5, 401, 1024 }, { 5, 402, 1024 }, { 6, 403, 1024 }, { 5, 404, 1024 }, { 6, 405, 1024 }, { 6, 406, 1024 }, { 7, 407, 1024 }, { 5, 408, 1024 }, { 6, 409, 1024 }, { 6, 410, 1024 }, { 7, 411, 1024 }, { 6, 412, 1024 }, { 7, 413, 1024 }, { 7, 414, 1024 }, { 8, 415, 1024 }, { 4, 416, 1024 }, { 5, 417, 1024 }, { 5, 418, 1024 }, { 6, 419, 1024 }, { 5, 420, 1024 }, { 6, 421, 1024 }, { 6, 422, 1024 }, { 7, 423, 1024 }, { 5, 424, 1024 }, { 6, 425, 1024 }, { 6, 426, 1024 }, { 7, 427, 1024 }, { 6, 428, 1024 }, { 7, 429, 1024 }, { 7, 430, 1024 }, { 8, 431, 1024 }, { 5, 432, 1024 }, { 6, 433, 1024 }, { 6, 434, 1024 }, { 7, 435, 1024 }, { 6, 436, 1024 }, { 7, 437, 1024 }, { 7, 438, 1024 }, { 8, 439, 1024 }, { 6, 440, 1024 }, { 7, 441, 1024 }, { 7, 442, 1024 }, { 8, 443, 1024 }, { 7, 444, 1024 }, { 8, 445, 1024 }, { 8, 446, 1024 }, { 9, 447, 1024 }, { 4, 448, 1024 }, { 5, 449, 1024 }, { 5, 450, 1024 }, { 6, 451, 1024 }, { 5, 452, 1024 }, { 6, 453, 1024 }, { 6, 454, 1024 }, { 7, 455, 1024 }, { 5, 456, 1024 }, { 6, 457, 1024 }, { 6, 458, 1024 }, { 7, 459, 1024 }, { 6, 460, 1024 }, { 7, 461, 1024 }, { 7, 462, 1024 }, { 8, 463, 1024 }, { 5, 464, 1024 }, { 6, 465, 1024 }, { 6, 466, 1024 }, { 7, 467, 1024 }, { 6, 468, 1024 }, { 7, 469, 1024 }, { 7, 470, 1024 }, { 8, 471, 1024 }, { 6, 472, 1024 }, { 7, 473, 1024 }, { 7, 474, 1024 }, { 8, 475, 1024 }, { 7, 476, 1024 }, { 8, 477, 1024 }, { 8, 478, 1024 }, { 9, 479, 1024 }, { 5, 480, 1024 }, { 6, 481, 1024 }, { 6, 482, 1024 }, { 7, 483, 1024 }, { 6, 484, 1024 }, { 7, 485, 1024 }, { 7, 486, 1024 }, { 8, 487, 1024 }, { 6, 488, 1024 }, { 7, 489, 1024 }, { 7, 490, 1024 }, { 8, 491, 1024 }, { 7, 492, 1024 }, { 8, 493, 1024 }, { 8, 494, 1024 }, { 9, 495, 1024 }, { 6, 496, 1024 }, { 7, 497, 1024 }, { 7, 498, 1024 }, { 8, 499, 1024 }, { 7, 500, 1024 }, { 8, 501, 1024 }, { 8, 502, 1024 }, { 9, 503, 1024 }, { 7, 504, 1024 }, { 8, 505, 1024 }, { 8, 506, 1024 }, { 9, 507, 1024 }, { 8, 508, 1024 }, { 9, 509, 1024 }, { 9, 510, 1024 }, { 10, 511, 1024 }, { 2, 512, 1024 }, { 3, 513, 1024 }, { 3, 514, 1024 }, { 4, 515, 1024 }, { 3, 516, 1024 }, { 4, 517, 1024 }, { 4, 518, 1024 }, { 5, 519, 1024 }, { 3, 520, 1024 }, { 4, 521, 1024 }, { 4, 522, 1024 }, { 5, 523, 1024 }, { 4, 524, 1024 }, { 5, 525, 1024 }, { 5, 526, 1024 }, { 6, 527, 1024 }, { 3, 528, 1024 }, { 4, 529, 1024 }, { 4, 530, 1024 }, { 5, 531, 1024 }, { 4, 532, 1024 }, { 5, 533, 1024 }, { 5, 534, 1024 }, { 6, 535, 1024 }, { 4, 536, 1024 }, { 5, 537, 1024 }, { 5, 538, 1024 }, { 6, 539, 1024 }, { 5, 540, 1024 }, { 6, 541, 1024 }, { 6, 542, 1024 }, { 7, 543, 1024 }, { 3, 544, 1024 }, { 4, 545, 1024 }, { 4, 546, 1024 }, { 5, 547, 1024 }, { 4, 548, 1024 }, { 5, 549, 1024 }, { 5, 550, 1024 }, { 6, 551, 1024 }, { 4, 552, 1024 }, { 5, 553, 1024 }, { 5, 554, 1024 }, { 6, 555, 1024 }, { 5, 556, 1024 }, { 6, 557, 1024 }, { 6, 558, 1024 }, { 7, 559, 1024 }, { 4, 560, 1024 }, { 5, 561, 1024 }, { 5, 562, 1024 }, { 6, 563, 1024 }, { 5, 564, 1024 }, { 6, 565, 1024 }, { 6, 566, 1024 }, { 7, 567, 1024 }, { 5, 568, 1024 }, { 6, 569, 1024 }, { 6, 570, 1024 }, { 7, 571, 1024 }, { 6, 572, 1024 }, { 7, 573, 1024 }, { 7, 574, 1024 }, { 8, 575, 1024 }, { 3, 576, 1024 }, { 4, 577, 1024 }, { 4, 578, 1024 }, { 5, 579, 1024 }, { 4, 580, 1024 }, { 5, 581, 1024 }, { 5, 582, 1024 }, { 6, 583, 1024 }, { 4, 584, 1024 }, { 5, 585, 1024 }, { 5, 586, 1024 }, { 6, 587, 1024 }, { 5, 588, 1024 }, { 6, 589, 1024 }, { 6, 590, 1024 }, { 7, 591, 1024 }, { 4, 592, 1024 }, { 5, 593, 1024 }, { 5, 594, 1024 }, { 6, 595, 1024 }, { 5, 596, 1024 }, { 6, 597, 1024 }, { 6, 598, 1024 }, { 7, 599, 1024 }, { 5, 600, 1024 }, { 6, 601, 1024 }, { 6, 602, 1024 }, { 7, 603, 1024 }, { 6, 604, 1024 }, { 7, 605, 1024 }, { 7, 606, 1024 }, { 8, 607, 1024 }, { 4, 608, 1024 }, { 5, 609, 1024 }, { 5, 610, 1024 }, { 6, 611, 1024 }, { 5, 612, 1024 }, { 6, 613, 1024 }, { 6, 614, 1024 }, { 7, 615, 1024 }, { 5, 616, 1024 }, { 6, 617, 1024 }, { 6, 618, 1024 }, { 7, 619, 1024 }, { 6, 620, 1024 }, { 7, 621, 1024 }, { 7, 622, 1024 }, { 8, 623, 1024 }, { 5, 624, 1024 }, { 6, 625, 1024 }, { 6, 626, 1024 }, { 7, 627, 1024 }, { 6, 628, 1024 }, { 7, 629, 1024 }, { 7, 630, 1024 }, { 8, 631, 1024 }, { 6, 632, 1024 }, { 7, 633, 1024 }, { 7, 634, 1024 }, { 8, 635, 1024 }, { 7, 636, 1024 }, { 8, 637, 1024 }, { 8, 638, 1024 }, { 9, 639, 1024 }, { 3, 640, 1024 }, { 4, 641, 1024 }, { 4, 642, 1024 }, { 5, 643, 1024 }, { 4, 644, 1024 }, { 5, 645, 1024 }, { 5, 646, 1024 }, { 6, 647, 1024 }, { 4, 648, 1024 }, { 5, 649, 1024 }, { 5, 650, 1024 }, { 6, 651, 1024 }, { 5, 652, 1024 }, { 6, 653, 1024 }, { 6, 654, 1024 }, { 7, 655, 1024 }, { 4, 656, 1024 }, { 5, 657, 1024 }, { 5, 658, 1024 }, { 6, 659, 1024 }, { 5, 660, 1024 }, { 6, 661, 1024 }, { 6, 662, 1024 }, { 7, 663, 1024 }, { 5, 664, 1024 }, { 6, 665, 1024 }, { 6, 666, 1024 }, { 7, 667, 1024 }, { 6, 668, 1024 }, { 7, 669, 1024 }, { 7, 670, 1024 }, { 8, 671, 1024 }, { 4, 672, 1024 }, { 5, 673, 1024 }, { 5, 674, 1024 }, { 6, 675, 1024 }, { 5, 676, 1024 }, { 6, 677, 1024 }, { 6, 678, 1024 }, { 7, 679, 1024 }, { 5, 680, 1024 }, { 6, 681, 1024 }, { 6, 682, 1024 }, { 7, 683, 1024 }, { 6, 684, 1024 }, { 7, 685, 1024 }, { 7, 686, 1024 }, { 8, 687, 1024 }, { 5, 688, 1024 }, { 6, 689, 1024 }, { 6, 690, 1024 }, { 7, 691, 1024 }, { 6, 692, 1024 }, { 7, 693, 1024 }, { 7, 694, 1024 }, { 8, 695, 1024 }, { 6, 696, 1024 }, { 7, 697, 1024 }, { 7, 698, 1024 }, { 8, 699, 1024 }, { 7, 700, 1024 }, { 8, 701, 1024 }, { 8, 702, 1024 }, { 9, 703, 1024 }, { 4, 704, 1024 }, { 5, 705, 1024 }, { 5, 706, 1024 }, { 6, 707, 1024 }, { 5, 708, 1024 }, { 6, 709, 1024 }, { 6, 710, 1024 }, { 7, 711, 1024 }, { 5, 712, 1024 }, { 6, 713, 1024 }, { 6, 714, 1024 }, { 7, 715, 1024 }, { 6, 716, 1024 }, { 7, 717, 1024 }, { 7, 718, 1024 }, { 8, 719, 1024 }, { 5, 720, 1024 }, { 6, 721, 1024 }, { 6, 722, 1024 }, { 7, 723, 1024 }, { 6, 724, 1024 }, { 7, 725, 1024 }, { 7, 726, 1024 }, { 8, 727, 1024 }, { 6, 728, 1024 }, { 7, 729, 1024 }, { 7, 730, 1024 }, { 8, 731, 1024 }, { 7, 732, 1024 }, { 8, 733, 1024 }, { 8, 734, 1024 }, { 9, 735, 1024 }, { 5, 736, 1024 }, { 6, 737, 1024 }, { 6, 738, 1024 }, { 7, 739, 1024 }, { 6, 740, 1024 }, { 7, 741, 1024 }, { 7, 742, 1024 }, { 8, 743, 1024 }, { 6, 744, 1024 }, { 7, 745, 1024 }, { 7, 746, 1024 }, { 8, 747, 1024 }, { 7, 748, 1024 }, { 8, 749, 1024 }, { 8, 750, 1024 }, { 9, 751, 1024 }, { 6, 752, 1024 }, { 7, 753, 1024 }, { 7, 754, 1024 }, { 8, 755, 1024 }, { 7, 756, 1024 }, { 8, 757, 1024 }, { 8, 758, 1024 }, { 9, 759, 1024 }, { 7, 760, 1024 }, { 8, 761, 1024 }, { 8, 762, 1024 }, { 9, 763, 1024 }, { 8, 764, 1024 }, { 9, 765, 1024 }, { 9, 766, 1024 }, { 10, 767, 1024 }, { 3, 768, 1024 }, { 4, 769, 1024 }, { 4, 770, 1024 }, { 5, 771, 1024 }, { 4, 772, 1024 }, { 5, 773, 1024 }, { 5, 774, 1024 }, { 6, 775, 1024 }, { 4, 776, 1024 }, { 5, 777, 1024 }, { 5, 778, 1024 }, { 6, 779, 1024 }, { 5, 780, 1024 }, { 6, 781, 1024 }, { 6, 782, 1024 }, { 7, 783, 1024 }, { 4, 784, 1024 }, { 5, 785, 1024 }, { 5, 786, 1024 }, { 6, 787, 1024 }, { 5, 788, 1024 }, { 6, 789, 1024 }, { 6, 790, 1024 }, { 7, 791, 1024 }, { 5, 792, 1024 }, { 6, 793, 1024 }, { 6, 794, 1024 }, { 7, 795, 1024 }, { 6, 796, 1024 }, { 7, 797, 1024 }, { 7, 798, 1024 }, { 8, 799, 1024 }, { 4, 800, 1024 }, { 5, 801, 1024 }, { 5, 802, 1024 }, { 6, 803, 1024 }, { 5, 804, 1024 }, { 6, 805, 1024 }, { 6, 806, 1024 }, { 7, 807, 1024 }, { 5, 808, 1024 }, { 6, 809, 1024 }, { 6, 810, 1024 }, { 7, 811, 1024 }, { 6, 812, 1024 }, { 7, 813, 1024 }, { 7, 814, 1024 }, { 8, 815, 1024 }, { 5, 816, 1024 }, { 6, 817, 1024 }, { 6, 818, 1024 }, { 7, 819, 1024 }, { 6, 820, 1024 }, { 7, 821, 1024 }, { 7, 822, 1024 }, { 8, 823, 1024 }, { 6, 824, 1024 }, { 7, 825, 1024 }, { 7, 826, 1024 }, { 8, 827, 1024 }, { 7, 828, 1024 }, { 8, 829, 1024 }, { 8, 830, 1024 }, { 9, 831, 1024 }, { 4, 832, 1024 }, { 5, 833, 1024 }, { 5, 834, 1024 }, { 6, 835, 1024 }, { 5, 836, 1024 }, { 6, 837, 1024 }, { 6, 838, 1024 }, { 7, 839, 1024 }, { 5, 840, 1024 }, { 6, 841, 1024 }, { 6, 842, 1024 }, { 7, 843, 1024 }, { 6, 844, 1024 }, { 7, 845, 1024 }, { 7, 846, 1024 }, { 8, 847, 1024 }, { 5, 848, 1024 }, { 6, 849, 1024 }, { 6, 850, 1024 }, { 7, 851, 1024 }, { 6, 852, 1024 }, { 7, 853, 1024 }, { 7, 854, 1024 }, { 8, 855, 1024 }, { 6, 856, 1024 }, { 7, 857, 1024 }, { 7, 858, 1024 }, { 8, 859, 1024 }, { 7, 860, 1024 }, { 8, 861, 1024 }, { 8, 862, 1024 }, { 9, 863, 1024 }, { 5, 864, 1024 }, { 6, 865, 1024 }, { 6, 866, 1024 }, { 7, 867, 1024 }, { 6, 868, 1024 }, { 7, 869, 1024 }, { 7, 870, 1024 }, { 8, 871, 1024 }, { 6, 872, 1024 }, { 7, 873, 1024 }, { 7, 874, 1024 }, { 8, 875, 1024 }, { 7, 876, 1024 }, { 8, 877, 1024 }, { 8, 878, 1024 }, { 9, 879, 1024 }, { 6, 880, 1024 }, { 7, 881, 1024 }, { 7, 882, 1024 }, { 8, 883, 1024 }, { 7, 884, 1024 }, { 8, 885, 1024 }, { 8, 886, 1024 }, { 9, 887, 1024 }, { 7, 888, 1024 }, { 8, 889, 1024 }, { 8, 890, 1024 }, { 9, 891, 1024 }, { 8, 892, 1024 }, { 9, 893, 1024 }, { 9, 894, 1024 }, { 10, 895, 1024 }, { 4, 896, 1024 }, { 5, 897, 1024 }, { 5, 898, 1024 }, { 6, 899, 1024 }, { 5, 900, 1024 }, { 6, 901, 1024 }, { 6, 902, 1024 }, { 7, 903, 1024 }, { 5, 904, 1024 }, { 6, 905, 1024 }, { 6, 906, 1024 }, { 7, 907, 1024 }, { 6, 908, 1024 }, { 7, 909, 1024 }, { 7, 910, 1024 }, { 8, 911, 1024 }, { 5, 912, 1024 }, { 6, 913, 1024 }, { 6, 914, 1024 }, { 7, 915, 1024 }, { 6, 916, 1024 }, { 7, 917, 1024 }, { 7, 918, 1024 }, { 8, 919, 1024 }, { 6, 920, 1024 }, { 7, 921, 1024 }, { 7, 922, 1024 }, { 8, 923, 1024 }, { 7, 924, 1024 }, { 8, 925, 1024 }, { 8, 926, 1024 }, { 9, 927, 1024 }, { 5, 928, 1024 }, { 6, 929, 1024 }, { 6, 930, 1024 }, { 7, 931, 1024 }, { 6, 932, 1024 }, { 7, 933, 1024 }, { 7, 934, 1024 }, { 8, 935, 1024 }, { 6, 936, 1024 }, { 7, 937, 1024 }, { 7, 938, 1024 }, { 8, 939, 1024 }, { 7, 940, 1024 }, { 8, 941, 1024 }, { 8, 942, 1024 }, { 9, 943, 1024 }, { 6, 944, 1024 }, { 7, 945, 1024 }, { 7, 946, 1024 }, { 8, 947, 1024 }, { 7, 948, 1024 }, { 8, 949, 1024 }, { 8, 950, 1024 }, { 9, 951, 1024 }, { 7, 952, 1024 }, { 8, 953, 1024 }, { 8, 954, 1024 }, { 9, 955, 1024 }, { 8, 956, 1024 }, { 9, 957, 1024 }, { 9, 958, 1024 }, { 10, 959, 1024 }, { 5, 960, 1024 }, { 6, 961, 1024 }, { 6, 962, 1024 }, { 7, 963, 1024 }, { 6, 964, 1024 }, { 7, 965, 1024 }, { 7, 966, 1024 }, { 8, 967, 1024 }, { 6, 968, 1024 }, { 7, 969, 1024 }, { 7, 970, 1024 }, { 8, 971, 1024 }, { 7, 972, 1024 }, { 8, 973, 1024 }, { 8, 974, 1024 }, { 9, 975, 1024 }, { 6, 976, 1024 }, { 7, 977, 1024 }, { 7, 978, 1024 }, { 8, 979, 1024 }, { 7, 980, 1024 }, { 8, 981, 1024 }, { 8, 982, 1024 }, { 9, 983, 1024 }, { 7, 984, 1024 }, { 8, 985, 1024 }, { 8, 986, 1024 }, { 9, 987, 1024 }, { 8, 988, 1024 }, { 9, 989, 1024 }, { 9, 990, 1024 }, { 10, 991, 1024 }, { 6, 992, 1024 }, { 7, 993, 1024 }, { 7, 994, 1024 }, { 8, 995, 1024 }, { 7, 996, 1024 }, { 8, 997, 1024 }, { 8, 998, 1024 }, { 9, 999, 1024 }, { 7, 1000, 1024 }, { 8, 1001, 1024 }, { 8, 1002, 1024 }, { 9, 1003, 1024 }, { 8, 1004, 1024 }, { 9, 1005, 1024 }, { 9, 1006, 1024 }, { 10, 1007, 1024 }, { 7, 1008, 1024 }, { 8, 1009, 1024 }, { 8, 1010, 1024 }, { 9, 1011, 1024 }, { 8, 1012, 1024 }, { 9, 1013, 1024 }, { 9, 1014, 1024 }, { 10, 1015, 1024 }, { 8, 1016, 1024 }, { 9, 1017, 1024 }, { 9, 1018, 1024 }, { 10, 1019, 1024 }, { 9, 1020, 1024 }, { 10, 1021, 1024 }, { 10, 1022, 1024 }, { 11, 1023, 1024 }, #if FP_LUT > 11 { 1, 0, 0 }, { 2, 1, 2048 }, { 2, 2, 2048 }, { 3, 3, 2048 }, { 2, 4, 2048 }, { 3, 5, 2048 }, { 3, 6, 2048 }, { 4, 7, 2048 }, { 2, 8, 2048 }, { 3, 9, 2048 }, { 3, 10, 2048 }, { 4, 11, 2048 }, { 3, 12, 2048 }, { 4, 13, 2048 }, { 4, 14, 2048 }, { 5, 15, 2048 }, { 2, 16, 2048 }, { 3, 17, 2048 }, { 3, 18, 2048 }, { 4, 19, 2048 }, { 3, 20, 2048 }, { 4, 21, 2048 }, { 4, 22, 2048 }, { 5, 23, 2048 }, { 3, 24, 2048 }, { 4, 25, 2048 }, { 4, 26, 2048 }, { 5, 27, 2048 }, { 4, 28, 2048 }, { 5, 29, 2048 }, { 5, 30, 2048 }, { 6, 31, 2048 }, { 2, 32, 2048 }, { 3, 33, 2048 }, { 3, 34, 2048 }, { 4, 35, 2048 }, { 3, 36, 2048 }, { 4, 37, 2048 }, { 4, 38, 2048 }, { 5, 39, 2048 }, { 3, 40, 2048 }, { 4, 41, 2048 }, { 4, 42, 2048 }, { 5, 43, 2048 }, { 4, 44, 2048 }, { 5, 45, 2048 }, { 5, 46, 2048 }, { 6, 47, 2048 }, { 3, 48, 2048 }, { 4, 49, 2048 }, { 4, 50, 2048 }, { 5, 51, 2048 }, { 4, 52, 2048 }, { 5, 53, 2048 }, { 5, 54, 2048 }, { 6, 55, 2048 }, { 4, 56, 2048 }, { 5, 57, 2048 }, { 5, 58, 2048 }, { 6, 59, 2048 }, { 5, 60, 2048 }, { 6, 61, 2048 }, { 6, 62, 2048 }, { 7, 63, 2048 }, { 2, 64, 2048 }, { 3, 65, 2048 }, { 3, 66, 2048 }, { 4, 67, 2048 }, { 3, 68, 2048 }, { 4, 69, 2048 }, { 4, 70, 2048 }, { 5, 71, 2048 }, { 3, 72, 2048 }, { 4, 73, 2048 }, { 4, 74, 2048 }, { 5, 75, 2048 }, { 4, 76, 2048 }, { 5, 77, 2048 }, { 5, 78, 2048 }, { 6, 79, 2048 }, { 3, 80, 2048 }, { 4, 81, 2048 }, { 4, 82, 2048 }, { 5, 83, 2048 }, { 4, 84, 2048 }, { 5, 85, 2048 }, { 5, 86, 2048 }, { 6, 87, 2048 }, { 4, 88, 2048 }, { 5, 89, 2048 }, { 5, 90, 2048 }, { 6, 91, 2048 }, { 5, 92, 2048 }, { 6, 93, 2048 }, { 6, 94, 2048 }, { 7, 95, 2048 }, { 3, 96, 2048 }, { 4, 97, 2048 }, { 4, 98, 2048 }, { 5, 99, 2048 }, { 4, 100, 2048 }, { 5, 101, 2048 }, { 5, 102, 2048 }, { 6, 103, 2048 }, { 4, 104, 2048 }, { 5, 105, 2048 }, { 5, 106, 2048 }, { 6, 107, 2048 }, { 5, 108, 2048 }, { 6, 109, 2048 }, { 6, 110, 2048 }, { 7, 111, 2048 }, { 4, 112, 2048 }, { 5, 113, 2048 }, { 5, 114, 2048 }, { 6, 115, 2048 }, { 5, 116, 2048 }, { 6, 117, 2048 }, { 6, 118, 2048 }, { 7, 119, 2048 }, { 5, 120, 2048 }, { 6, 121, 2048 }, { 6, 122, 2048 }, { 7, 123, 2048 }, { 6, 124, 2048 }, { 7, 125, 2048 }, { 7, 126, 2048 }, { 8, 127, 2048 }, { 2, 128, 2048 }, { 3, 129, 2048 }, { 3, 130, 2048 }, { 4, 131, 2048 }, { 3, 132, 2048 }, { 4, 133, 2048 }, { 4, 134, 2048 }, { 5, 135, 2048 }, { 3, 136, 2048 }, { 4, 137, 2048 }, { 4, 138, 2048 }, { 5, 139, 2048 }, { 4, 140, 2048 }, { 5, 141, 2048 }, { 5, 142, 2048 }, { 6, 143, 2048 }, { 3, 144, 2048 }, { 4, 145, 2048 }, { 4, 146, 2048 }, { 5, 147, 2048 }, { 4, 148, 2048 }, { 5, 149, 2048 }, { 5, 150, 2048 }, { 6, 151, 2048 }, { 4, 152, 2048 }, { 5, 153, 2048 }, { 5, 154, 2048 }, { 6, 155, 2048 }, { 5, 156, 2048 }, { 6, 157, 2048 }, { 6, 158, 2048 }, { 7, 159, 2048 }, { 3, 160, 2048 }, { 4, 161, 2048 }, { 4, 162, 2048 }, { 5, 163, 2048 }, { 4, 164, 2048 }, { 5, 165, 2048 }, { 5, 166, 2048 }, { 6, 167, 2048 }, { 4, 168, 2048 }, { 5, 169, 2048 }, { 5, 170, 2048 }, { 6, 171, 2048 }, { 5, 172, 2048 }, { 6, 173, 2048 }, { 6, 174, 2048 }, { 7, 175, 2048 }, { 4, 176, 2048 }, { 5, 177, 2048 }, { 5, 178, 2048 }, { 6, 179, 2048 }, { 5, 180, 2048 }, { 6, 181, 2048 }, { 6, 182, 2048 }, { 7, 183, 2048 }, { 5, 184, 2048 }, { 6, 185, 2048 }, { 6, 186, 2048 }, { 7, 187, 2048 }, { 6, 188, 2048 }, { 7, 189, 2048 }, { 7, 190, 2048 }, { 8, 191, 2048 }, { 3, 192, 2048 }, { 4, 193, 2048 }, { 4, 194, 2048 }, { 5, 195, 2048 }, { 4, 196, 2048 }, { 5, 197, 2048 }, { 5, 198, 2048 }, { 6, 199, 2048 }, { 4, 200, 2048 }, { 5, 201, 2048 }, { 5, 202, 2048 }, { 6, 203, 2048 }, { 5, 204, 2048 }, { 6, 205, 2048 }, { 6, 206, 2048 }, { 7, 207, 2048 }, { 4, 208, 2048 }, { 5, 209, 2048 }, { 5, 210, 2048 }, { 6, 211, 2048 }, { 5, 212, 2048 }, { 6, 213, 2048 }, { 6, 214, 2048 }, { 7, 215, 2048 }, { 5, 216, 2048 }, { 6, 217, 2048 }, { 6, 218, 2048 }, { 7, 219, 2048 }, { 6, 220, 2048 }, { 7, 221, 2048 }, { 7, 222, 2048 }, { 8, 223, 2048 }, { 4, 224, 2048 }, { 5, 225, 2048 }, { 5, 226, 2048 }, { 6, 227, 2048 }, { 5, 228, 2048 }, { 6, 229, 2048 }, { 6, 230, 2048 }, { 7, 231, 2048 }, { 5, 232, 2048 }, { 6, 233, 2048 }, { 6, 234, 2048 }, { 7, 235, 2048 }, { 6, 236, 2048 }, { 7, 237, 2048 }, { 7, 238, 2048 }, { 8, 239, 2048 }, { 5, 240, 2048 }, { 6, 241, 2048 }, { 6, 242, 2048 }, { 7, 243, 2048 }, { 6, 244, 2048 }, { 7, 245, 2048 }, { 7, 246, 2048 }, { 8, 247, 2048 }, { 6, 248, 2048 }, { 7, 249, 2048 }, { 7, 250, 2048 }, { 8, 251, 2048 }, { 7, 252, 2048 }, { 8, 253, 2048 }, { 8, 254, 2048 }, { 9, 255, 2048 }, { 2, 256, 2048 }, { 3, 257, 2048 }, { 3, 258, 2048 }, { 4, 259, 2048 }, { 3, 260, 2048 }, { 4, 261, 2048 }, { 4, 262, 2048 }, { 5, 263, 2048 }, { 3, 264, 2048 }, { 4, 265, 2048 }, { 4, 266, 2048 }, { 5, 267, 2048 }, { 4, 268, 2048 }, { 5, 269, 2048 }, { 5, 270, 2048 }, { 6, 271, 2048 }, { 3, 272, 2048 }, { 4, 273, 2048 }, { 4, 274, 2048 }, { 5, 275, 2048 }, { 4, 276, 2048 }, { 5, 277, 2048 }, { 5, 278, 2048 }, { 6, 279, 2048 }, { 4, 280, 2048 }, { 5, 281, 2048 }, { 5, 282, 2048 }, { 6, 283, 2048 }, { 5, 284, 2048 }, { 6, 285, 2048 }, { 6, 286, 2048 }, { 7, 287, 2048 }, { 3, 288, 2048 }, { 4, 289, 2048 }, { 4, 290, 2048 }, { 5, 291, 2048 }, { 4, 292, 2048 }, { 5, 293, 2048 }, { 5, 294, 2048 }, { 6, 295, 2048 }, { 4, 296, 2048 }, { 5, 297, 2048 }, { 5, 298, 2048 }, { 6, 299, 2048 }, { 5, 300, 2048 }, { 6, 301, 2048 }, { 6, 302, 2048 }, { 7, 303, 2048 }, { 4, 304, 2048 }, { 5, 305, 2048 }, { 5, 306, 2048 }, { 6, 307, 2048 }, { 5, 308, 2048 }, { 6, 309, 2048 }, { 6, 310, 2048 }, { 7, 311, 2048 }, { 5, 312, 2048 }, { 6, 313, 2048 }, { 6, 314, 2048 }, { 7, 315, 2048 }, { 6, 316, 2048 }, { 7, 317, 2048 }, { 7, 318, 2048 }, { 8, 319, 2048 }, { 3, 320, 2048 }, { 4, 321, 2048 }, { 4, 322, 2048 }, { 5, 323, 2048 }, { 4, 324, 2048 }, { 5, 325, 2048 }, { 5, 326, 2048 }, { 6, 327, 2048 }, { 4, 328, 2048 }, { 5, 329, 2048 }, { 5, 330, 2048 }, { 6, 331, 2048 }, { 5, 332, 2048 }, { 6, 333, 2048 }, { 6, 334, 2048 }, { 7, 335, 2048 }, { 4, 336, 2048 }, { 5, 337, 2048 }, { 5, 338, 2048 }, { 6, 339, 2048 }, { 5, 340, 2048 }, { 6, 341, 2048 }, { 6, 342, 2048 }, { 7, 343, 2048 }, { 5, 344, 2048 }, { 6, 345, 2048 }, { 6, 346, 2048 }, { 7, 347, 2048 }, { 6, 348, 2048 }, { 7, 349, 2048 }, { 7, 350, 2048 }, { 8, 351, 2048 }, { 4, 352, 2048 }, { 5, 353, 2048 }, { 5, 354, 2048 }, { 6, 355, 2048 }, { 5, 356, 2048 }, { 6, 357, 2048 }, { 6, 358, 2048 }, { 7, 359, 2048 }, { 5, 360, 2048 }, { 6, 361, 2048 }, { 6, 362, 2048 }, { 7, 363, 2048 }, { 6, 364, 2048 }, { 7, 365, 2048 }, { 7, 366, 2048 }, { 8, 367, 2048 }, { 5, 368, 2048 }, { 6, 369, 2048 }, { 6, 370, 2048 }, { 7, 371, 2048 }, { 6, 372, 2048 }, { 7, 373, 2048 }, { 7, 374, 2048 }, { 8, 375, 2048 }, { 6, 376, 2048 }, { 7, 377, 2048 }, { 7, 378, 2048 }, { 8, 379, 2048 }, { 7, 380, 2048 }, { 8, 381, 2048 }, { 8, 382, 2048 }, { 9, 383, 2048 }, { 3, 384, 2048 }, { 4, 385, 2048 }, { 4, 386, 2048 }, { 5, 387, 2048 }, { 4, 388, 2048 }, { 5, 389, 2048 }, { 5, 390, 2048 }, { 6, 391, 2048 }, { 4, 392, 2048 }, { 5, 393, 2048 }, { 5, 394, 2048 }, { 6, 395, 2048 }, { 5, 396, 2048 }, { 6, 397, 2048 }, { 6, 398, 2048 }, { 7, 399, 2048 }, { 4, 400, 2048 }, { 5, 401, 2048 }, { 5, 402, 2048 }, { 6, 403, 2048 }, { 5, 404, 2048 }, { 6, 405, 2048 }, { 6, 406, 2048 }, { 7, 407, 2048 }, { 5, 408, 2048 }, { 6, 409, 2048 }, { 6, 410, 2048 }, { 7, 411, 2048 }, { 6, 412, 2048 }, { 7, 413, 2048 }, { 7, 414, 2048 }, { 8, 415, 2048 }, { 4, 416, 2048 }, { 5, 417, 2048 }, { 5, 418, 2048 }, { 6, 419, 2048 }, { 5, 420, 2048 }, { 6, 421, 2048 }, { 6, 422, 2048 }, { 7, 423, 2048 }, { 5, 424, 2048 }, { 6, 425, 2048 }, { 6, 426, 2048 }, { 7, 427, 2048 }, { 6, 428, 2048 }, { 7, 429, 2048 }, { 7, 430, 2048 }, { 8, 431, 2048 }, { 5, 432, 2048 }, { 6, 433, 2048 }, { 6, 434, 2048 }, { 7, 435, 2048 }, { 6, 436, 2048 }, { 7, 437, 2048 }, { 7, 438, 2048 }, { 8, 439, 2048 }, { 6, 440, 2048 }, { 7, 441, 2048 }, { 7, 442, 2048 }, { 8, 443, 2048 }, { 7, 444, 2048 }, { 8, 445, 2048 }, { 8, 446, 2048 }, { 9, 447, 2048 }, { 4, 448, 2048 }, { 5, 449, 2048 }, { 5, 450, 2048 }, { 6, 451, 2048 }, { 5, 452, 2048 }, { 6, 453, 2048 }, { 6, 454, 2048 }, { 7, 455, 2048 }, { 5, 456, 2048 }, { 6, 457, 2048 }, { 6, 458, 2048 }, { 7, 459, 2048 }, { 6, 460, 2048 }, { 7, 461, 2048 }, { 7, 462, 2048 }, { 8, 463, 2048 }, { 5, 464, 2048 }, { 6, 465, 2048 }, { 6, 466, 2048 }, { 7, 467, 2048 }, { 6, 468, 2048 }, { 7, 469, 2048 }, { 7, 470, 2048 }, { 8, 471, 2048 }, { 6, 472, 2048 }, { 7, 473, 2048 }, { 7, 474, 2048 }, { 8, 475, 2048 }, { 7, 476, 2048 }, { 8, 477, 2048 }, { 8, 478, 2048 }, { 9, 479, 2048 }, { 5, 480, 2048 }, { 6, 481, 2048 }, { 6, 482, 2048 }, { 7, 483, 2048 }, { 6, 484, 2048 }, { 7, 485, 2048 }, { 7, 486, 2048 }, { 8, 487, 2048 }, { 6, 488, 2048 }, { 7, 489, 2048 }, { 7, 490, 2048 }, { 8, 491, 2048 }, { 7, 492, 2048 }, { 8, 493, 2048 }, { 8, 494, 2048 }, { 9, 495, 2048 }, { 6, 496, 2048 }, { 7, 497, 2048 }, { 7, 498, 2048 }, { 8, 499, 2048 }, { 7, 500, 2048 }, { 8, 501, 2048 }, { 8, 502, 2048 }, { 9, 503, 2048 }, { 7, 504, 2048 }, { 8, 505, 2048 }, { 8, 506, 2048 }, { 9, 507, 2048 }, { 8, 508, 2048 }, { 9, 509, 2048 }, { 9, 510, 2048 }, { 10, 511, 2048 }, { 2, 512, 2048 }, { 3, 513, 2048 }, { 3, 514, 2048 }, { 4, 515, 2048 }, { 3, 516, 2048 }, { 4, 517, 2048 }, { 4, 518, 2048 }, { 5, 519, 2048 }, { 3, 520, 2048 }, { 4, 521, 2048 }, { 4, 522, 2048 }, { 5, 523, 2048 }, { 4, 524, 2048 }, { 5, 525, 2048 }, { 5, 526, 2048 }, { 6, 527, 2048 }, { 3, 528, 2048 }, { 4, 529, 2048 }, { 4, 530, 2048 }, { 5, 531, 2048 }, { 4, 532, 2048 }, { 5, 533, 2048 }, { 5, 534, 2048 }, { 6, 535, 2048 }, { 4, 536, 2048 }, { 5, 537, 2048 }, { 5, 538, 2048 }, { 6, 539, 2048 }, { 5, 540, 2048 }, { 6, 541, 2048 }, { 6, 542, 2048 }, { 7, 543, 2048 }, { 3, 544, 2048 }, { 4, 545, 2048 }, { 4, 546, 2048 }, { 5, 547, 2048 }, { 4, 548, 2048 }, { 5, 549, 2048 }, { 5, 550, 2048 }, { 6, 551, 2048 }, { 4, 552, 2048 }, { 5, 553, 2048 }, { 5, 554, 2048 }, { 6, 555, 2048 }, { 5, 556, 2048 }, { 6, 557, 2048 }, { 6, 558, 2048 }, { 7, 559, 2048 }, { 4, 560, 2048 }, { 5, 561, 2048 }, { 5, 562, 2048 }, { 6, 563, 2048 }, { 5, 564, 2048 }, { 6, 565, 2048 }, { 6, 566, 2048 }, { 7, 567, 2048 }, { 5, 568, 2048 }, { 6, 569, 2048 }, { 6, 570, 2048 }, { 7, 571, 2048 }, { 6, 572, 2048 }, { 7, 573, 2048 }, { 7, 574, 2048 }, { 8, 575, 2048 }, { 3, 576, 2048 }, { 4, 577, 2048 }, { 4, 578, 2048 }, { 5, 579, 2048 }, { 4, 580, 2048 }, { 5, 581, 2048 }, { 5, 582, 2048 }, { 6, 583, 2048 }, { 4, 584, 2048 }, { 5, 585, 2048 }, { 5, 586, 2048 }, { 6, 587, 2048 }, { 5, 588, 2048 }, { 6, 589, 2048 }, { 6, 590, 2048 }, { 7, 591, 2048 }, { 4, 592, 2048 }, { 5, 593, 2048 }, { 5, 594, 2048 }, { 6, 595, 2048 }, { 5, 596, 2048 }, { 6, 597, 2048 }, { 6, 598, 2048 }, { 7, 599, 2048 }, { 5, 600, 2048 }, { 6, 601, 2048 }, { 6, 602, 2048 }, { 7, 603, 2048 }, { 6, 604, 2048 }, { 7, 605, 2048 }, { 7, 606, 2048 }, { 8, 607, 2048 }, { 4, 608, 2048 }, { 5, 609, 2048 }, { 5, 610, 2048 }, { 6, 611, 2048 }, { 5, 612, 2048 }, { 6, 613, 2048 }, { 6, 614, 2048 }, { 7, 615, 2048 }, { 5, 616, 2048 }, { 6, 617, 2048 }, { 6, 618, 2048 }, { 7, 619, 2048 }, { 6, 620, 2048 }, { 7, 621, 2048 }, { 7, 622, 2048 }, { 8, 623, 2048 }, { 5, 624, 2048 }, { 6, 625, 2048 }, { 6, 626, 2048 }, { 7, 627, 2048 }, { 6, 628, 2048 }, { 7, 629, 2048 }, { 7, 630, 2048 }, { 8, 631, 2048 }, { 6, 632, 2048 }, { 7, 633, 2048 }, { 7, 634, 2048 }, { 8, 635, 2048 }, { 7, 636, 2048 }, { 8, 637, 2048 }, { 8, 638, 2048 }, { 9, 639, 2048 }, { 3, 640, 2048 }, { 4, 641, 2048 }, { 4, 642, 2048 }, { 5, 643, 2048 }, { 4, 644, 2048 }, { 5, 645, 2048 }, { 5, 646, 2048 }, { 6, 647, 2048 }, { 4, 648, 2048 }, { 5, 649, 2048 }, { 5, 650, 2048 }, { 6, 651, 2048 }, { 5, 652, 2048 }, { 6, 653, 2048 }, { 6, 654, 2048 }, { 7, 655, 2048 }, { 4, 656, 2048 }, { 5, 657, 2048 }, { 5, 658, 2048 }, { 6, 659, 2048 }, { 5, 660, 2048 }, { 6, 661, 2048 }, { 6, 662, 2048 }, { 7, 663, 2048 }, { 5, 664, 2048 }, { 6, 665, 2048 }, { 6, 666, 2048 }, { 7, 667, 2048 }, { 6, 668, 2048 }, { 7, 669, 2048 }, { 7, 670, 2048 }, { 8, 671, 2048 }, { 4, 672, 2048 }, { 5, 673, 2048 }, { 5, 674, 2048 }, { 6, 675, 2048 }, { 5, 676, 2048 }, { 6, 677, 2048 }, { 6, 678, 2048 }, { 7, 679, 2048 }, { 5, 680, 2048 }, { 6, 681, 2048 }, { 6, 682, 2048 }, { 7, 683, 2048 }, { 6, 684, 2048 }, { 7, 685, 2048 }, { 7, 686, 2048 }, { 8, 687, 2048 }, { 5, 688, 2048 }, { 6, 689, 2048 }, { 6, 690, 2048 }, { 7, 691, 2048 }, { 6, 692, 2048 }, { 7, 693, 2048 }, { 7, 694, 2048 }, { 8, 695, 2048 }, { 6, 696, 2048 }, { 7, 697, 2048 }, { 7, 698, 2048 }, { 8, 699, 2048 }, { 7, 700, 2048 }, { 8, 701, 2048 }, { 8, 702, 2048 }, { 9, 703, 2048 }, { 4, 704, 2048 }, { 5, 705, 2048 }, { 5, 706, 2048 }, { 6, 707, 2048 }, { 5, 708, 2048 }, { 6, 709, 2048 }, { 6, 710, 2048 }, { 7, 711, 2048 }, { 5, 712, 2048 }, { 6, 713, 2048 }, { 6, 714, 2048 }, { 7, 715, 2048 }, { 6, 716, 2048 }, { 7, 717, 2048 }, { 7, 718, 2048 }, { 8, 719, 2048 }, { 5, 720, 2048 }, { 6, 721, 2048 }, { 6, 722, 2048 }, { 7, 723, 2048 }, { 6, 724, 2048 }, { 7, 725, 2048 }, { 7, 726, 2048 }, { 8, 727, 2048 }, { 6, 728, 2048 }, { 7, 729, 2048 }, { 7, 730, 2048 }, { 8, 731, 2048 }, { 7, 732, 2048 }, { 8, 733, 2048 }, { 8, 734, 2048 }, { 9, 735, 2048 }, { 5, 736, 2048 }, { 6, 737, 2048 }, { 6, 738, 2048 }, { 7, 739, 2048 }, { 6, 740, 2048 }, { 7, 741, 2048 }, { 7, 742, 2048 }, { 8, 743, 2048 }, { 6, 744, 2048 }, { 7, 745, 2048 }, { 7, 746, 2048 }, { 8, 747, 2048 }, { 7, 748, 2048 }, { 8, 749, 2048 }, { 8, 750, 2048 }, { 9, 751, 2048 }, { 6, 752, 2048 }, { 7, 753, 2048 }, { 7, 754, 2048 }, { 8, 755, 2048 }, { 7, 756, 2048 }, { 8, 757, 2048 }, { 8, 758, 2048 }, { 9, 759, 2048 }, { 7, 760, 2048 }, { 8, 761, 2048 }, { 8, 762, 2048 }, { 9, 763, 2048 }, { 8, 764, 2048 }, { 9, 765, 2048 }, { 9, 766, 2048 }, { 10, 767, 2048 }, { 3, 768, 2048 }, { 4, 769, 2048 }, { 4, 770, 2048 }, { 5, 771, 2048 }, { 4, 772, 2048 }, { 5, 773, 2048 }, { 5, 774, 2048 }, { 6, 775, 2048 }, { 4, 776, 2048 }, { 5, 777, 2048 }, { 5, 778, 2048 }, { 6, 779, 2048 }, { 5, 780, 2048 }, { 6, 781, 2048 }, { 6, 782, 2048 }, { 7, 783, 2048 }, { 4, 784, 2048 }, { 5, 785, 2048 }, { 5, 786, 2048 }, { 6, 787, 2048 }, { 5, 788, 2048 }, { 6, 789, 2048 }, { 6, 790, 2048 }, { 7, 791, 2048 }, { 5, 792, 2048 }, { 6, 793, 2048 }, { 6, 794, 2048 }, { 7, 795, 2048 }, { 6, 796, 2048 }, { 7, 797, 2048 }, { 7, 798, 2048 }, { 8, 799, 2048 }, { 4, 800, 2048 }, { 5, 801, 2048 }, { 5, 802, 2048 }, { 6, 803, 2048 }, { 5, 804, 2048 }, { 6, 805, 2048 }, { 6, 806, 2048 }, { 7, 807, 2048 }, { 5, 808, 2048 }, { 6, 809, 2048 }, { 6, 810, 2048 }, { 7, 811, 2048 }, { 6, 812, 2048 }, { 7, 813, 2048 }, { 7, 814, 2048 }, { 8, 815, 2048 }, { 5, 816, 2048 }, { 6, 817, 2048 }, { 6, 818, 2048 }, { 7, 819, 2048 }, { 6, 820, 2048 }, { 7, 821, 2048 }, { 7, 822, 2048 }, { 8, 823, 2048 }, { 6, 824, 2048 }, { 7, 825, 2048 }, { 7, 826, 2048 }, { 8, 827, 2048 }, { 7, 828, 2048 }, { 8, 829, 2048 }, { 8, 830, 2048 }, { 9, 831, 2048 }, { 4, 832, 2048 }, { 5, 833, 2048 }, { 5, 834, 2048 }, { 6, 835, 2048 }, { 5, 836, 2048 }, { 6, 837, 2048 }, { 6, 838, 2048 }, { 7, 839, 2048 }, { 5, 840, 2048 }, { 6, 841, 2048 }, { 6, 842, 2048 }, { 7, 843, 2048 }, { 6, 844, 2048 }, { 7, 845, 2048 }, { 7, 846, 2048 }, { 8, 847, 2048 }, { 5, 848, 2048 }, { 6, 849, 2048 }, { 6, 850, 2048 }, { 7, 851, 2048 }, { 6, 852, 2048 }, { 7, 853, 2048 }, { 7, 854, 2048 }, { 8, 855, 2048 }, { 6, 856, 2048 }, { 7, 857, 2048 }, { 7, 858, 2048 }, { 8, 859, 2048 }, { 7, 860, 2048 }, { 8, 861, 2048 }, { 8, 862, 2048 }, { 9, 863, 2048 }, { 5, 864, 2048 }, { 6, 865, 2048 }, { 6, 866, 2048 }, { 7, 867, 2048 }, { 6, 868, 2048 }, { 7, 869, 2048 }, { 7, 870, 2048 }, { 8, 871, 2048 }, { 6, 872, 2048 }, { 7, 873, 2048 }, { 7, 874, 2048 }, { 8, 875, 2048 }, { 7, 876, 2048 }, { 8, 877, 2048 }, { 8, 878, 2048 }, { 9, 879, 2048 }, { 6, 880, 2048 }, { 7, 881, 2048 }, { 7, 882, 2048 }, { 8, 883, 2048 }, { 7, 884, 2048 }, { 8, 885, 2048 }, { 8, 886, 2048 }, { 9, 887, 2048 }, { 7, 888, 2048 }, { 8, 889, 2048 }, { 8, 890, 2048 }, { 9, 891, 2048 }, { 8, 892, 2048 }, { 9, 893, 2048 }, { 9, 894, 2048 }, { 10, 895, 2048 }, { 4, 896, 2048 }, { 5, 897, 2048 }, { 5, 898, 2048 }, { 6, 899, 2048 }, { 5, 900, 2048 }, { 6, 901, 2048 }, { 6, 902, 2048 }, { 7, 903, 2048 }, { 5, 904, 2048 }, { 6, 905, 2048 }, { 6, 906, 2048 }, { 7, 907, 2048 }, { 6, 908, 2048 }, { 7, 909, 2048 }, { 7, 910, 2048 }, { 8, 911, 2048 }, { 5, 912, 2048 }, { 6, 913, 2048 }, { 6, 914, 2048 }, { 7, 915, 2048 }, { 6, 916, 2048 }, { 7, 917, 2048 }, { 7, 918, 2048 }, { 8, 919, 2048 }, { 6, 920, 2048 }, { 7, 921, 2048 }, { 7, 922, 2048 }, { 8, 923, 2048 }, { 7, 924, 2048 }, { 8, 925, 2048 }, { 8, 926, 2048 }, { 9, 927, 2048 }, { 5, 928, 2048 }, { 6, 929, 2048 }, { 6, 930, 2048 }, { 7, 931, 2048 }, { 6, 932, 2048 }, { 7, 933, 2048 }, { 7, 934, 2048 }, { 8, 935, 2048 }, { 6, 936, 2048 }, { 7, 937, 2048 }, { 7, 938, 2048 }, { 8, 939, 2048 }, { 7, 940, 2048 }, { 8, 941, 2048 }, { 8, 942, 2048 }, { 9, 943, 2048 }, { 6, 944, 2048 }, { 7, 945, 2048 }, { 7, 946, 2048 }, { 8, 947, 2048 }, { 7, 948, 2048 }, { 8, 949, 2048 }, { 8, 950, 2048 }, { 9, 951, 2048 }, { 7, 952, 2048 }, { 8, 953, 2048 }, { 8, 954, 2048 }, { 9, 955, 2048 }, { 8, 956, 2048 }, { 9, 957, 2048 }, { 9, 958, 2048 }, { 10, 959, 2048 }, { 5, 960, 2048 }, { 6, 961, 2048 }, { 6, 962, 2048 }, { 7, 963, 2048 }, { 6, 964, 2048 }, { 7, 965, 2048 }, { 7, 966, 2048 }, { 8, 967, 2048 }, { 6, 968, 2048 }, { 7, 969, 2048 }, { 7, 970, 2048 }, { 8, 971, 2048 }, { 7, 972, 2048 }, { 8, 973, 2048 }, { 8, 974, 2048 }, { 9, 975, 2048 }, { 6, 976, 2048 }, { 7, 977, 2048 }, { 7, 978, 2048 }, { 8, 979, 2048 }, { 7, 980, 2048 }, { 8, 981, 2048 }, { 8, 982, 2048 }, { 9, 983, 2048 }, { 7, 984, 2048 }, { 8, 985, 2048 }, { 8, 986, 2048 }, { 9, 987, 2048 }, { 8, 988, 2048 }, { 9, 989, 2048 }, { 9, 990, 2048 }, { 10, 991, 2048 }, { 6, 992, 2048 }, { 7, 993, 2048 }, { 7, 994, 2048 }, { 8, 995, 2048 }, { 7, 996, 2048 }, { 8, 997, 2048 }, { 8, 998, 2048 }, { 9, 999, 2048 }, { 7, 1000, 2048 }, { 8, 1001, 2048 }, { 8, 1002, 2048 }, { 9, 1003, 2048 }, { 8, 1004, 2048 }, { 9, 1005, 2048 }, { 9, 1006, 2048 }, { 10, 1007, 2048 }, { 7, 1008, 2048 }, { 8, 1009, 2048 }, { 8, 1010, 2048 }, { 9, 1011, 2048 }, { 8, 1012, 2048 }, { 9, 1013, 2048 }, { 9, 1014, 2048 }, { 10, 1015, 2048 }, { 8, 1016, 2048 }, { 9, 1017, 2048 }, { 9, 1018, 2048 }, { 10, 1019, 2048 }, { 9, 1020, 2048 }, { 10, 1021, 2048 }, { 10, 1022, 2048 }, { 11, 1023, 2048 }, { 2, 1024, 2048 }, { 3, 1025, 2048 }, { 3, 1026, 2048 }, { 4, 1027, 2048 }, { 3, 1028, 2048 }, { 4, 1029, 2048 }, { 4, 1030, 2048 }, { 5, 1031, 2048 }, { 3, 1032, 2048 }, { 4, 1033, 2048 }, { 4, 1034, 2048 }, { 5, 1035, 2048 }, { 4, 1036, 2048 }, { 5, 1037, 2048 }, { 5, 1038, 2048 }, { 6, 1039, 2048 }, { 3, 1040, 2048 }, { 4, 1041, 2048 }, { 4, 1042, 2048 }, { 5, 1043, 2048 }, { 4, 1044, 2048 }, { 5, 1045, 2048 }, { 5, 1046, 2048 }, { 6, 1047, 2048 }, { 4, 1048, 2048 }, { 5, 1049, 2048 }, { 5, 1050, 2048 }, { 6, 1051, 2048 }, { 5, 1052, 2048 }, { 6, 1053, 2048 }, { 6, 1054, 2048 }, { 7, 1055, 2048 }, { 3, 1056, 2048 }, { 4, 1057, 2048 }, { 4, 1058, 2048 }, { 5, 1059, 2048 }, { 4, 1060, 2048 }, { 5, 1061, 2048 }, { 5, 1062, 2048 }, { 6, 1063, 2048 }, { 4, 1064, 2048 }, { 5, 1065, 2048 }, { 5, 1066, 2048 }, { 6, 1067, 2048 }, { 5, 1068, 2048 }, { 6, 1069, 2048 }, { 6, 1070, 2048 }, { 7, 1071, 2048 }, { 4, 1072, 2048 }, { 5, 1073, 2048 }, { 5, 1074, 2048 }, { 6, 1075, 2048 }, { 5, 1076, 2048 }, { 6, 1077, 2048 }, { 6, 1078, 2048 }, { 7, 1079, 2048 }, { 5, 1080, 2048 }, { 6, 1081, 2048 }, { 6, 1082, 2048 }, { 7, 1083, 2048 }, { 6, 1084, 2048 }, { 7, 1085, 2048 }, { 7, 1086, 2048 }, { 8, 1087, 2048 }, { 3, 1088, 2048 }, { 4, 1089, 2048 }, { 4, 1090, 2048 }, { 5, 1091, 2048 }, { 4, 1092, 2048 }, { 5, 1093, 2048 }, { 5, 1094, 2048 }, { 6, 1095, 2048 }, { 4, 1096, 2048 }, { 5, 1097, 2048 }, { 5, 1098, 2048 }, { 6, 1099, 2048 }, { 5, 1100, 2048 }, { 6, 1101, 2048 }, { 6, 1102, 2048 }, { 7, 1103, 2048 }, { 4, 1104, 2048 }, { 5, 1105, 2048 }, { 5, 1106, 2048 }, { 6, 1107, 2048 }, { 5, 1108, 2048 }, { 6, 1109, 2048 }, { 6, 1110, 2048 }, { 7, 1111, 2048 }, { 5, 1112, 2048 }, { 6, 1113, 2048 }, { 6, 1114, 2048 }, { 7, 1115, 2048 }, { 6, 1116, 2048 }, { 7, 1117, 2048 }, { 7, 1118, 2048 }, { 8, 1119, 2048 }, { 4, 1120, 2048 }, { 5, 1121, 2048 }, { 5, 1122, 2048 }, { 6, 1123, 2048 }, { 5, 1124, 2048 }, { 6, 1125, 2048 }, { 6, 1126, 2048 }, { 7, 1127, 2048 }, { 5, 1128, 2048 }, { 6, 1129, 2048 }, { 6, 1130, 2048 }, { 7, 1131, 2048 }, { 6, 1132, 2048 }, { 7, 1133, 2048 }, { 7, 1134, 2048 }, { 8, 1135, 2048 }, { 5, 1136, 2048 }, { 6, 1137, 2048 }, { 6, 1138, 2048 }, { 7, 1139, 2048 }, { 6, 1140, 2048 }, { 7, 1141, 2048 }, { 7, 1142, 2048 }, { 8, 1143, 2048 }, { 6, 1144, 2048 }, { 7, 1145, 2048 }, { 7, 1146, 2048 }, { 8, 1147, 2048 }, { 7, 1148, 2048 }, { 8, 1149, 2048 }, { 8, 1150, 2048 }, { 9, 1151, 2048 }, { 3, 1152, 2048 }, { 4, 1153, 2048 }, { 4, 1154, 2048 }, { 5, 1155, 2048 }, { 4, 1156, 2048 }, { 5, 1157, 2048 }, { 5, 1158, 2048 }, { 6, 1159, 2048 }, { 4, 1160, 2048 }, { 5, 1161, 2048 }, { 5, 1162, 2048 }, { 6, 1163, 2048 }, { 5, 1164, 2048 }, { 6, 1165, 2048 }, { 6, 1166, 2048 }, { 7, 1167, 2048 }, { 4, 1168, 2048 }, { 5, 1169, 2048 }, { 5, 1170, 2048 }, { 6, 1171, 2048 }, { 5, 1172, 2048 }, { 6, 1173, 2048 }, { 6, 1174, 2048 }, { 7, 1175, 2048 }, { 5, 1176, 2048 }, { 6, 1177, 2048 }, { 6, 1178, 2048 }, { 7, 1179, 2048 }, { 6, 1180, 2048 }, { 7, 1181, 2048 }, { 7, 1182, 2048 }, { 8, 1183, 2048 }, { 4, 1184, 2048 }, { 5, 1185, 2048 }, { 5, 1186, 2048 }, { 6, 1187, 2048 }, { 5, 1188, 2048 }, { 6, 1189, 2048 }, { 6, 1190, 2048 }, { 7, 1191, 2048 }, { 5, 1192, 2048 }, { 6, 1193, 2048 }, { 6, 1194, 2048 }, { 7, 1195, 2048 }, { 6, 1196, 2048 }, { 7, 1197, 2048 }, { 7, 1198, 2048 }, { 8, 1199, 2048 }, { 5, 1200, 2048 }, { 6, 1201, 2048 }, { 6, 1202, 2048 }, { 7, 1203, 2048 }, { 6, 1204, 2048 }, { 7, 1205, 2048 }, { 7, 1206, 2048 }, { 8, 1207, 2048 }, { 6, 1208, 2048 }, { 7, 1209, 2048 }, { 7, 1210, 2048 }, { 8, 1211, 2048 }, { 7, 1212, 2048 }, { 8, 1213, 2048 }, { 8, 1214, 2048 }, { 9, 1215, 2048 }, { 4, 1216, 2048 }, { 5, 1217, 2048 }, { 5, 1218, 2048 }, { 6, 1219, 2048 }, { 5, 1220, 2048 }, { 6, 1221, 2048 }, { 6, 1222, 2048 }, { 7, 1223, 2048 }, { 5, 1224, 2048 }, { 6, 1225, 2048 }, { 6, 1226, 2048 }, { 7, 1227, 2048 }, { 6, 1228, 2048 }, { 7, 1229, 2048 }, { 7, 1230, 2048 }, { 8, 1231, 2048 }, { 5, 1232, 2048 }, { 6, 1233, 2048 }, { 6, 1234, 2048 }, { 7, 1235, 2048 }, { 6, 1236, 2048 }, { 7, 1237, 2048 }, { 7, 1238, 2048 }, { 8, 1239, 2048 }, { 6, 1240, 2048 }, { 7, 1241, 2048 }, { 7, 1242, 2048 }, { 8, 1243, 2048 }, { 7, 1244, 2048 }, { 8, 1245, 2048 }, { 8, 1246, 2048 }, { 9, 1247, 2048 }, { 5, 1248, 2048 }, { 6, 1249, 2048 }, { 6, 1250, 2048 }, { 7, 1251, 2048 }, { 6, 1252, 2048 }, { 7, 1253, 2048 }, { 7, 1254, 2048 }, { 8, 1255, 2048 }, { 6, 1256, 2048 }, { 7, 1257, 2048 }, { 7, 1258, 2048 }, { 8, 1259, 2048 }, { 7, 1260, 2048 }, { 8, 1261, 2048 }, { 8, 1262, 2048 }, { 9, 1263, 2048 }, { 6, 1264, 2048 }, { 7, 1265, 2048 }, { 7, 1266, 2048 }, { 8, 1267, 2048 }, { 7, 1268, 2048 }, { 8, 1269, 2048 }, { 8, 1270, 2048 }, { 9, 1271, 2048 }, { 7, 1272, 2048 }, { 8, 1273, 2048 }, { 8, 1274, 2048 }, { 9, 1275, 2048 }, { 8, 1276, 2048 }, { 9, 1277, 2048 }, { 9, 1278, 2048 }, { 10, 1279, 2048 }, { 3, 1280, 2048 }, { 4, 1281, 2048 }, { 4, 1282, 2048 }, { 5, 1283, 2048 }, { 4, 1284, 2048 }, { 5, 1285, 2048 }, { 5, 1286, 2048 }, { 6, 1287, 2048 }, { 4, 1288, 2048 }, { 5, 1289, 2048 }, { 5, 1290, 2048 }, { 6, 1291, 2048 }, { 5, 1292, 2048 }, { 6, 1293, 2048 }, { 6, 1294, 2048 }, { 7, 1295, 2048 }, { 4, 1296, 2048 }, { 5, 1297, 2048 }, { 5, 1298, 2048 }, { 6, 1299, 2048 }, { 5, 1300, 2048 }, { 6, 1301, 2048 }, { 6, 1302, 2048 }, { 7, 1303, 2048 }, { 5, 1304, 2048 }, { 6, 1305, 2048 }, { 6, 1306, 2048 }, { 7, 1307, 2048 }, { 6, 1308, 2048 }, { 7, 1309, 2048 }, { 7, 1310, 2048 }, { 8, 1311, 2048 }, { 4, 1312, 2048 }, { 5, 1313, 2048 }, { 5, 1314, 2048 }, { 6, 1315, 2048 }, { 5, 1316, 2048 }, { 6, 1317, 2048 }, { 6, 1318, 2048 }, { 7, 1319, 2048 }, { 5, 1320, 2048 }, { 6, 1321, 2048 }, { 6, 1322, 2048 }, { 7, 1323, 2048 }, { 6, 1324, 2048 }, { 7, 1325, 2048 }, { 7, 1326, 2048 }, { 8, 1327, 2048 }, { 5, 1328, 2048 }, { 6, 1329, 2048 }, { 6, 1330, 2048 }, { 7, 1331, 2048 }, { 6, 1332, 2048 }, { 7, 1333, 2048 }, { 7, 1334, 2048 }, { 8, 1335, 2048 }, { 6, 1336, 2048 }, { 7, 1337, 2048 }, { 7, 1338, 2048 }, { 8, 1339, 2048 }, { 7, 1340, 2048 }, { 8, 1341, 2048 }, { 8, 1342, 2048 }, { 9, 1343, 2048 }, { 4, 1344, 2048 }, { 5, 1345, 2048 }, { 5, 1346, 2048 }, { 6, 1347, 2048 }, { 5, 1348, 2048 }, { 6, 1349, 2048 }, { 6, 1350, 2048 }, { 7, 1351, 2048 }, { 5, 1352, 2048 }, { 6, 1353, 2048 }, { 6, 1354, 2048 }, { 7, 1355, 2048 }, { 6, 1356, 2048 }, { 7, 1357, 2048 }, { 7, 1358, 2048 }, { 8, 1359, 2048 }, { 5, 1360, 2048 }, { 6, 1361, 2048 }, { 6, 1362, 2048 }, { 7, 1363, 2048 }, { 6, 1364, 2048 }, { 7, 1365, 2048 }, { 7, 1366, 2048 }, { 8, 1367, 2048 }, { 6, 1368, 2048 }, { 7, 1369, 2048 }, { 7, 1370, 2048 }, { 8, 1371, 2048 }, { 7, 1372, 2048 }, { 8, 1373, 2048 }, { 8, 1374, 2048 }, { 9, 1375, 2048 }, { 5, 1376, 2048 }, { 6, 1377, 2048 }, { 6, 1378, 2048 }, { 7, 1379, 2048 }, { 6, 1380, 2048 }, { 7, 1381, 2048 }, { 7, 1382, 2048 }, { 8, 1383, 2048 }, { 6, 1384, 2048 }, { 7, 1385, 2048 }, { 7, 1386, 2048 }, { 8, 1387, 2048 }, { 7, 1388, 2048 }, { 8, 1389, 2048 }, { 8, 1390, 2048 }, { 9, 1391, 2048 }, { 6, 1392, 2048 }, { 7, 1393, 2048 }, { 7, 1394, 2048 }, { 8, 1395, 2048 }, { 7, 1396, 2048 }, { 8, 1397, 2048 }, { 8, 1398, 2048 }, { 9, 1399, 2048 }, { 7, 1400, 2048 }, { 8, 1401, 2048 }, { 8, 1402, 2048 }, { 9, 1403, 2048 }, { 8, 1404, 2048 }, { 9, 1405, 2048 }, { 9, 1406, 2048 }, { 10, 1407, 2048 }, { 4, 1408, 2048 }, { 5, 1409, 2048 }, { 5, 1410, 2048 }, { 6, 1411, 2048 }, { 5, 1412, 2048 }, { 6, 1413, 2048 }, { 6, 1414, 2048 }, { 7, 1415, 2048 }, { 5, 1416, 2048 }, { 6, 1417, 2048 }, { 6, 1418, 2048 }, { 7, 1419, 2048 }, { 6, 1420, 2048 }, { 7, 1421, 2048 }, { 7, 1422, 2048 }, { 8, 1423, 2048 }, { 5, 1424, 2048 }, { 6, 1425, 2048 }, { 6, 1426, 2048 }, { 7, 1427, 2048 }, { 6, 1428, 2048 }, { 7, 1429, 2048 }, { 7, 1430, 2048 }, { 8, 1431, 2048 }, { 6, 1432, 2048 }, { 7, 1433, 2048 }, { 7, 1434, 2048 }, { 8, 1435, 2048 }, { 7, 1436, 2048 }, { 8, 1437, 2048 }, { 8, 1438, 2048 }, { 9, 1439, 2048 }, { 5, 1440, 2048 }, { 6, 1441, 2048 }, { 6, 1442, 2048 }, { 7, 1443, 2048 }, { 6, 1444, 2048 }, { 7, 1445, 2048 }, { 7, 1446, 2048 }, { 8, 1447, 2048 }, { 6, 1448, 2048 }, { 7, 1449, 2048 }, { 7, 1450, 2048 }, { 8, 1451, 2048 }, { 7, 1452, 2048 }, { 8, 1453, 2048 }, { 8, 1454, 2048 }, { 9, 1455, 2048 }, { 6, 1456, 2048 }, { 7, 1457, 2048 }, { 7, 1458, 2048 }, { 8, 1459, 2048 }, { 7, 1460, 2048 }, { 8, 1461, 2048 }, { 8, 1462, 2048 }, { 9, 1463, 2048 }, { 7, 1464, 2048 }, { 8, 1465, 2048 }, { 8, 1466, 2048 }, { 9, 1467, 2048 }, { 8, 1468, 2048 }, { 9, 1469, 2048 }, { 9, 1470, 2048 }, { 10, 1471, 2048 }, { 5, 1472, 2048 }, { 6, 1473, 2048 }, { 6, 1474, 2048 }, { 7, 1475, 2048 }, { 6, 1476, 2048 }, { 7, 1477, 2048 }, { 7, 1478, 2048 }, { 8, 1479, 2048 }, { 6, 1480, 2048 }, { 7, 1481, 2048 }, { 7, 1482, 2048 }, { 8, 1483, 2048 }, { 7, 1484, 2048 }, { 8, 1485, 2048 }, { 8, 1486, 2048 }, { 9, 1487, 2048 }, { 6, 1488, 2048 }, { 7, 1489, 2048 }, { 7, 1490, 2048 }, { 8, 1491, 2048 }, { 7, 1492, 2048 }, { 8, 1493, 2048 }, { 8, 1494, 2048 }, { 9, 1495, 2048 }, { 7, 1496, 2048 }, { 8, 1497, 2048 }, { 8, 1498, 2048 }, { 9, 1499, 2048 }, { 8, 1500, 2048 }, { 9, 1501, 2048 }, { 9, 1502, 2048 }, { 10, 1503, 2048 }, { 6, 1504, 2048 }, { 7, 1505, 2048 }, { 7, 1506, 2048 }, { 8, 1507, 2048 }, { 7, 1508, 2048 }, { 8, 1509, 2048 }, { 8, 1510, 2048 }, { 9, 1511, 2048 }, { 7, 1512, 2048 }, { 8, 1513, 2048 }, { 8, 1514, 2048 }, { 9, 1515, 2048 }, { 8, 1516, 2048 }, { 9, 1517, 2048 }, { 9, 1518, 2048 }, { 10, 1519, 2048 }, { 7, 1520, 2048 }, { 8, 1521, 2048 }, { 8, 1522, 2048 }, { 9, 1523, 2048 }, { 8, 1524, 2048 }, { 9, 1525, 2048 }, { 9, 1526, 2048 }, { 10, 1527, 2048 }, { 8, 1528, 2048 }, { 9, 1529, 2048 }, { 9, 1530, 2048 }, { 10, 1531, 2048 }, { 9, 1532, 2048 }, { 10, 1533, 2048 }, { 10, 1534, 2048 }, { 11, 1535, 2048 }, { 3, 1536, 2048 }, { 4, 1537, 2048 }, { 4, 1538, 2048 }, { 5, 1539, 2048 }, { 4, 1540, 2048 }, { 5, 1541, 2048 }, { 5, 1542, 2048 }, { 6, 1543, 2048 }, { 4, 1544, 2048 }, { 5, 1545, 2048 }, { 5, 1546, 2048 }, { 6, 1547, 2048 }, { 5, 1548, 2048 }, { 6, 1549, 2048 }, { 6, 1550, 2048 }, { 7, 1551, 2048 }, { 4, 1552, 2048 }, { 5, 1553, 2048 }, { 5, 1554, 2048 }, { 6, 1555, 2048 }, { 5, 1556, 2048 }, { 6, 1557, 2048 }, { 6, 1558, 2048 }, { 7, 1559, 2048 }, { 5, 1560, 2048 }, { 6, 1561, 2048 }, { 6, 1562, 2048 }, { 7, 1563, 2048 }, { 6, 1564, 2048 }, { 7, 1565, 2048 }, { 7, 1566, 2048 }, { 8, 1567, 2048 }, { 4, 1568, 2048 }, { 5, 1569, 2048 }, { 5, 1570, 2048 }, { 6, 1571, 2048 }, { 5, 1572, 2048 }, { 6, 1573, 2048 }, { 6, 1574, 2048 }, { 7, 1575, 2048 }, { 5, 1576, 2048 }, { 6, 1577, 2048 }, { 6, 1578, 2048 }, { 7, 1579, 2048 }, { 6, 1580, 2048 }, { 7, 1581, 2048 }, { 7, 1582, 2048 }, { 8, 1583, 2048 }, { 5, 1584, 2048 }, { 6, 1585, 2048 }, { 6, 1586, 2048 }, { 7, 1587, 2048 }, { 6, 1588, 2048 }, { 7, 1589, 2048 }, { 7, 1590, 2048 }, { 8, 1591, 2048 }, { 6, 1592, 2048 }, { 7, 1593, 2048 }, { 7, 1594, 2048 }, { 8, 1595, 2048 }, { 7, 1596, 2048 }, { 8, 1597, 2048 }, { 8, 1598, 2048 }, { 9, 1599, 2048 }, { 4, 1600, 2048 }, { 5, 1601, 2048 }, { 5, 1602, 2048 }, { 6, 1603, 2048 }, { 5, 1604, 2048 }, { 6, 1605, 2048 }, { 6, 1606, 2048 }, { 7, 1607, 2048 }, { 5, 1608, 2048 }, { 6, 1609, 2048 }, { 6, 1610, 2048 }, { 7, 1611, 2048 }, { 6, 1612, 2048 }, { 7, 1613, 2048 }, { 7, 1614, 2048 }, { 8, 1615, 2048 }, { 5, 1616, 2048 }, { 6, 1617, 2048 }, { 6, 1618, 2048 }, { 7, 1619, 2048 }, { 6, 1620, 2048 }, { 7, 1621, 2048 }, { 7, 1622, 2048 }, { 8, 1623, 2048 }, { 6, 1624, 2048 }, { 7, 1625, 2048 }, { 7, 1626, 2048 }, { 8, 1627, 2048 }, { 7, 1628, 2048 }, { 8, 1629, 2048 }, { 8, 1630, 2048 }, { 9, 1631, 2048 }, { 5, 1632, 2048 }, { 6, 1633, 2048 }, { 6, 1634, 2048 }, { 7, 1635, 2048 }, { 6, 1636, 2048 }, { 7, 1637, 2048 }, { 7, 1638, 2048 }, { 8, 1639, 2048 }, { 6, 1640, 2048 }, { 7, 1641, 2048 }, { 7, 1642, 2048 }, { 8, 1643, 2048 }, { 7, 1644, 2048 }, { 8, 1645, 2048 }, { 8, 1646, 2048 }, { 9, 1647, 2048 }, { 6, 1648, 2048 }, { 7, 1649, 2048 }, { 7, 1650, 2048 }, { 8, 1651, 2048 }, { 7, 1652, 2048 }, { 8, 1653, 2048 }, { 8, 1654, 2048 }, { 9, 1655, 2048 }, { 7, 1656, 2048 }, { 8, 1657, 2048 }, { 8, 1658, 2048 }, { 9, 1659, 2048 }, { 8, 1660, 2048 }, { 9, 1661, 2048 }, { 9, 1662, 2048 }, { 10, 1663, 2048 }, { 4, 1664, 2048 }, { 5, 1665, 2048 }, { 5, 1666, 2048 }, { 6, 1667, 2048 }, { 5, 1668, 2048 }, { 6, 1669, 2048 }, { 6, 1670, 2048 }, { 7, 1671, 2048 }, { 5, 1672, 2048 }, { 6, 1673, 2048 }, { 6, 1674, 2048 }, { 7, 1675, 2048 }, { 6, 1676, 2048 }, { 7, 1677, 2048 }, { 7, 1678, 2048 }, { 8, 1679, 2048 }, { 5, 1680, 2048 }, { 6, 1681, 2048 }, { 6, 1682, 2048 }, { 7, 1683, 2048 }, { 6, 1684, 2048 }, { 7, 1685, 2048 }, { 7, 1686, 2048 }, { 8, 1687, 2048 }, { 6, 1688, 2048 }, { 7, 1689, 2048 }, { 7, 1690, 2048 }, { 8, 1691, 2048 }, { 7, 1692, 2048 }, { 8, 1693, 2048 }, { 8, 1694, 2048 }, { 9, 1695, 2048 }, { 5, 1696, 2048 }, { 6, 1697, 2048 }, { 6, 1698, 2048 }, { 7, 1699, 2048 }, { 6, 1700, 2048 }, { 7, 1701, 2048 }, { 7, 1702, 2048 }, { 8, 1703, 2048 }, { 6, 1704, 2048 }, { 7, 1705, 2048 }, { 7, 1706, 2048 }, { 8, 1707, 2048 }, { 7, 1708, 2048 }, { 8, 1709, 2048 }, { 8, 1710, 2048 }, { 9, 1711, 2048 }, { 6, 1712, 2048 }, { 7, 1713, 2048 }, { 7, 1714, 2048 }, { 8, 1715, 2048 }, { 7, 1716, 2048 }, { 8, 1717, 2048 }, { 8, 1718, 2048 }, { 9, 1719, 2048 }, { 7, 1720, 2048 }, { 8, 1721, 2048 }, { 8, 1722, 2048 }, { 9, 1723, 2048 }, { 8, 1724, 2048 }, { 9, 1725, 2048 }, { 9, 1726, 2048 }, { 10, 1727, 2048 }, { 5, 1728, 2048 }, { 6, 1729, 2048 }, { 6, 1730, 2048 }, { 7, 1731, 2048 }, { 6, 1732, 2048 }, { 7, 1733, 2048 }, { 7, 1734, 2048 }, { 8, 1735, 2048 }, { 6, 1736, 2048 }, { 7, 1737, 2048 }, { 7, 1738, 2048 }, { 8, 1739, 2048 }, { 7, 1740, 2048 }, { 8, 1741, 2048 }, { 8, 1742, 2048 }, { 9, 1743, 2048 }, { 6, 1744, 2048 }, { 7, 1745, 2048 }, { 7, 1746, 2048 }, { 8, 1747, 2048 }, { 7, 1748, 2048 }, { 8, 1749, 2048 }, { 8, 1750, 2048 }, { 9, 1751, 2048 }, { 7, 1752, 2048 }, { 8, 1753, 2048 }, { 8, 1754, 2048 }, { 9, 1755, 2048 }, { 8, 1756, 2048 }, { 9, 1757, 2048 }, { 9, 1758, 2048 }, { 10, 1759, 2048 }, { 6, 1760, 2048 }, { 7, 1761, 2048 }, { 7, 1762, 2048 }, { 8, 1763, 2048 }, { 7, 1764, 2048 }, { 8, 1765, 2048 }, { 8, 1766, 2048 }, { 9, 1767, 2048 }, { 7, 1768, 2048 }, { 8, 1769, 2048 }, { 8, 1770, 2048 }, { 9, 1771, 2048 }, { 8, 1772, 2048 }, { 9, 1773, 2048 }, { 9, 1774, 2048 }, { 10, 1775, 2048 }, { 7, 1776, 2048 }, { 8, 1777, 2048 }, { 8, 1778, 2048 }, { 9, 1779, 2048 }, { 8, 1780, 2048 }, { 9, 1781, 2048 }, { 9, 1782, 2048 }, { 10, 1783, 2048 }, { 8, 1784, 2048 }, { 9, 1785, 2048 }, { 9, 1786, 2048 }, { 10, 1787, 2048 }, { 9, 1788, 2048 }, { 10, 1789, 2048 }, { 10, 1790, 2048 }, { 11, 1791, 2048 }, { 4, 1792, 2048 }, { 5, 1793, 2048 }, { 5, 1794, 2048 }, { 6, 1795, 2048 }, { 5, 1796, 2048 }, { 6, 1797, 2048 }, { 6, 1798, 2048 }, { 7, 1799, 2048 }, { 5, 1800, 2048 }, { 6, 1801, 2048 }, { 6, 1802, 2048 }, { 7, 1803, 2048 }, { 6, 1804, 2048 }, { 7, 1805, 2048 }, { 7, 1806, 2048 }, { 8, 1807, 2048 }, { 5, 1808, 2048 }, { 6, 1809, 2048 }, { 6, 1810, 2048 }, { 7, 1811, 2048 }, { 6, 1812, 2048 }, { 7, 1813, 2048 }, { 7, 1814, 2048 }, { 8, 1815, 2048 }, { 6, 1816, 2048 }, { 7, 1817, 2048 }, { 7, 1818, 2048 }, { 8, 1819, 2048 }, { 7, 1820, 2048 }, { 8, 1821, 2048 }, { 8, 1822, 2048 }, { 9, 1823, 2048 }, { 5, 1824, 2048 }, { 6, 1825, 2048 }, { 6, 1826, 2048 }, { 7, 1827, 2048 }, { 6, 1828, 2048 }, { 7, 1829, 2048 }, { 7, 1830, 2048 }, { 8, 1831, 2048 }, { 6, 1832, 2048 }, { 7, 1833, 2048 }, { 7, 1834, 2048 }, { 8, 1835, 2048 }, { 7, 1836, 2048 }, { 8, 1837, 2048 }, { 8, 1838, 2048 }, { 9, 1839, 2048 }, { 6, 1840, 2048 }, { 7, 1841, 2048 }, { 7, 1842, 2048 }, { 8, 1843, 2048 }, { 7, 1844, 2048 }, { 8, 1845, 2048 }, { 8, 1846, 2048 }, { 9, 1847, 2048 }, { 7, 1848, 2048 }, { 8, 1849, 2048 }, { 8, 1850, 2048 }, { 9, 1851, 2048 }, { 8, 1852, 2048 }, { 9, 1853, 2048 }, { 9, 1854, 2048 }, { 10, 1855, 2048 }, { 5, 1856, 2048 }, { 6, 1857, 2048 }, { 6, 1858, 2048 }, { 7, 1859, 2048 }, { 6, 1860, 2048 }, { 7, 1861, 2048 }, { 7, 1862, 2048 }, { 8, 1863, 2048 }, { 6, 1864, 2048 }, { 7, 1865, 2048 }, { 7, 1866, 2048 }, { 8, 1867, 2048 }, { 7, 1868, 2048 }, { 8, 1869, 2048 }, { 8, 1870, 2048 }, { 9, 1871, 2048 }, { 6, 1872, 2048 }, { 7, 1873, 2048 }, { 7, 1874, 2048 }, { 8, 1875, 2048 }, { 7, 1876, 2048 }, { 8, 1877, 2048 }, { 8, 1878, 2048 }, { 9, 1879, 2048 }, { 7, 1880, 2048 }, { 8, 1881, 2048 }, { 8, 1882, 2048 }, { 9, 1883, 2048 }, { 8, 1884, 2048 }, { 9, 1885, 2048 }, { 9, 1886, 2048 }, { 10, 1887, 2048 }, { 6, 1888, 2048 }, { 7, 1889, 2048 }, { 7, 1890, 2048 }, { 8, 1891, 2048 }, { 7, 1892, 2048 }, { 8, 1893, 2048 }, { 8, 1894, 2048 }, { 9, 1895, 2048 }, { 7, 1896, 2048 }, { 8, 1897, 2048 }, { 8, 1898, 2048 }, { 9, 1899, 2048 }, { 8, 1900, 2048 }, { 9, 1901, 2048 }, { 9, 1902, 2048 }, { 10, 1903, 2048 }, { 7, 1904, 2048 }, { 8, 1905, 2048 }, { 8, 1906, 2048 }, { 9, 1907, 2048 }, { 8, 1908, 2048 }, { 9, 1909, 2048 }, { 9, 1910, 2048 }, { 10, 1911, 2048 }, { 8, 1912, 2048 }, { 9, 1913, 2048 }, { 9, 1914, 2048 }, { 10, 1915, 2048 }, { 9, 1916, 2048 }, { 10, 1917, 2048 }, { 10, 1918, 2048 }, { 11, 1919, 2048 }, { 5, 1920, 2048 }, { 6, 1921, 2048 }, { 6, 1922, 2048 }, { 7, 1923, 2048 }, { 6, 1924, 2048 }, { 7, 1925, 2048 }, { 7, 1926, 2048 }, { 8, 1927, 2048 }, { 6, 1928, 2048 }, { 7, 1929, 2048 }, { 7, 1930, 2048 }, { 8, 1931, 2048 }, { 7, 1932, 2048 }, { 8, 1933, 2048 }, { 8, 1934, 2048 }, { 9, 1935, 2048 }, { 6, 1936, 2048 }, { 7, 1937, 2048 }, { 7, 1938, 2048 }, { 8, 1939, 2048 }, { 7, 1940, 2048 }, { 8, 1941, 2048 }, { 8, 1942, 2048 }, { 9, 1943, 2048 }, { 7, 1944, 2048 }, { 8, 1945, 2048 }, { 8, 1946, 2048 }, { 9, 1947, 2048 }, { 8, 1948, 2048 }, { 9, 1949, 2048 }, { 9, 1950, 2048 }, { 10, 1951, 2048 }, { 6, 1952, 2048 }, { 7, 1953, 2048 }, { 7, 1954, 2048 }, { 8, 1955, 2048 }, { 7, 1956, 2048 }, { 8, 1957, 2048 }, { 8, 1958, 2048 }, { 9, 1959, 2048 }, { 7, 1960, 2048 }, { 8, 1961, 2048 }, { 8, 1962, 2048 }, { 9, 1963, 2048 }, { 8, 1964, 2048 }, { 9, 1965, 2048 }, { 9, 1966, 2048 }, { 10, 1967, 2048 }, { 7, 1968, 2048 }, { 8, 1969, 2048 }, { 8, 1970, 2048 }, { 9, 1971, 2048 }, { 8, 1972, 2048 }, { 9, 1973, 2048 }, { 9, 1974, 2048 }, { 10, 1975, 2048 }, { 8, 1976, 2048 }, { 9, 1977, 2048 }, { 9, 1978, 2048 }, { 10, 1979, 2048 }, { 9, 1980, 2048 }, { 10, 1981, 2048 }, { 10, 1982, 2048 }, { 11, 1983, 2048 }, { 6, 1984, 2048 }, { 7, 1985, 2048 }, { 7, 1986, 2048 }, { 8, 1987, 2048 }, { 7, 1988, 2048 }, { 8, 1989, 2048 }, { 8, 1990, 2048 }, { 9, 1991, 2048 }, { 7, 1992, 2048 }, { 8, 1993, 2048 }, { 8, 1994, 2048 }, { 9, 1995, 2048 }, { 8, 1996, 2048 }, { 9, 1997, 2048 }, { 9, 1998, 2048 }, { 10, 1999, 2048 }, { 7, 2000, 2048 }, { 8, 2001, 2048 }, { 8, 2002, 2048 }, { 9, 2003, 2048 }, { 8, 2004, 2048 }, { 9, 2005, 2048 }, { 9, 2006, 2048 }, { 10, 2007, 2048 }, { 8, 2008, 2048 }, { 9, 2009, 2048 }, { 9, 2010, 2048 }, { 10, 2011, 2048 }, { 9, 2012, 2048 }, { 10, 2013, 2048 }, { 10, 2014, 2048 }, { 11, 2015, 2048 }, { 7, 2016, 2048 }, { 8, 2017, 2048 }, { 8, 2018, 2048 }, { 9, 2019, 2048 }, { 8, 2020, 2048 }, { 9, 2021, 2048 }, { 9, 2022, 2048 }, { 10, 2023, 2048 }, { 8, 2024, 2048 }, { 9, 2025, 2048 }, { 9, 2026, 2048 }, { 10, 2027, 2048 }, { 9, 2028, 2048 }, { 10, 2029, 2048 }, { 10, 2030, 2048 }, { 11, 2031, 2048 }, { 8, 2032, 2048 }, { 9, 2033, 2048 }, { 9, 2034, 2048 }, { 10, 2035, 2048 }, { 9, 2036, 2048 }, { 10, 2037, 2048 }, { 10, 2038, 2048 }, { 11, 2039, 2048 }, { 9, 2040, 2048 }, { 10, 2041, 2048 }, { 10, 2042, 2048 }, { 11, 2043, 2048 }, { 10, 2044, 2048 }, { 11, 2045, 2048 }, { 11, 2046, 2048 }, { 12, 2047, 2048 }, #endif #endif #endif #endif #endif #endif }; /* find a hole and free as required, return -1 if no hole found */ static int find_hole(void) { unsigned x; int y, z; for (z = -1, y = INT_MAX, x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].lru_count < y && fp_cache[x].lock == 0) { z = x; y = fp_cache[x].lru_count; } } /* decrease all */ for (x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].lru_count > 3) { --(fp_cache[x].lru_count); } } /* free entry z */ if (z >= 0 && fp_cache[z].g) { mp_clear(&fp_cache[z].mu); wc_ecc_del_point(fp_cache[z].g); fp_cache[z].g = NULL; for (x = 0; x < (1U<<FP_LUT); x++) { wc_ecc_del_point(fp_cache[z].LUT[x]); fp_cache[z].LUT[x] = NULL; } fp_cache[z].lru_count = 0; } return z; } /* determine if a base is already in the cache and if so, where */ static int find_base(ecc_point* g) { int x; for (x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].g != NULL && mp_cmp(fp_cache[x].g->x, g->x) == MP_EQ && mp_cmp(fp_cache[x].g->y, g->y) == MP_EQ && mp_cmp(fp_cache[x].g->z, g->z) == MP_EQ) { break; } } if (x == FP_ENTRIES) { x = -1; } return x; } /* add a new base to the cache */ static int add_entry(int idx, ecc_point *g) { unsigned x, y; /* allocate base and LUT */ fp_cache[idx].g = wc_ecc_new_point(); if (fp_cache[idx].g == NULL) { return GEN_MEM_ERR; } /* copy x and y */ if ((mp_copy(g->x, fp_cache[idx].g->x) != MP_OKAY) || (mp_copy(g->y, fp_cache[idx].g->y) != MP_OKAY) || (mp_copy(g->z, fp_cache[idx].g->z) != MP_OKAY)) { wc_ecc_del_point(fp_cache[idx].g); fp_cache[idx].g = NULL; return GEN_MEM_ERR; } for (x = 0; x < (1U<<FP_LUT); x++) { fp_cache[idx].LUT[x] = wc_ecc_new_point(); if (fp_cache[idx].LUT[x] == NULL) { for (y = 0; y < x; y++) { wc_ecc_del_point(fp_cache[idx].LUT[y]); fp_cache[idx].LUT[y] = NULL; } wc_ecc_del_point(fp_cache[idx].g); fp_cache[idx].g = NULL; fp_cache[idx].lru_count = 0; return GEN_MEM_ERR; } } fp_cache[idx].lru_count = 0; return MP_OKAY; } #endif #ifndef WOLFSSL_SP_MATH /* build the LUT by spacing the bits of the input by #modulus/FP_LUT bits apart * * The algorithm builds patterns in increasing bit order by first making all * single bit input patterns, then all two bit input patterns and so on */ static int build_lut(int idx, mp_int* a, mp_int* modulus, mp_digit mp, mp_int* mu) { int err; unsigned x, y, bitlen, lut_gap; mp_int tmp; if (mp_init(&tmp) != MP_OKAY) return GEN_MEM_ERR; /* sanity check to make sure lut_order table is of correct size, should compile out to a NOP if true */ if ((sizeof(lut_orders) / sizeof(lut_orders[0])) < (1U<<FP_LUT)) { err = BAD_FUNC_ARG; } else { /* get bitlen and round up to next multiple of FP_LUT */ bitlen = mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { bitlen += FP_LUT - x; } lut_gap = bitlen / FP_LUT; /* init the mu */ err = mp_init_copy(&fp_cache[idx].mu, mu); } /* copy base */ if (err == MP_OKAY) { if ((mp_mulmod(fp_cache[idx].g->x, mu, modulus, fp_cache[idx].LUT[1]->x) != MP_OKAY) || (mp_mulmod(fp_cache[idx].g->y, mu, modulus, fp_cache[idx].LUT[1]->y) != MP_OKAY) || (mp_mulmod(fp_cache[idx].g->z, mu, modulus, fp_cache[idx].LUT[1]->z) != MP_OKAY)) { err = MP_MULMOD_E; } } /* make all single bit entries */ for (x = 1; x < FP_LUT; x++) { if (err != MP_OKAY) break; if ((mp_copy(fp_cache[idx].LUT[1<<(x-1)]->x, fp_cache[idx].LUT[1<<x]->x) != MP_OKAY) || (mp_copy(fp_cache[idx].LUT[1<<(x-1)]->y, fp_cache[idx].LUT[1<<x]->y) != MP_OKAY) || (mp_copy(fp_cache[idx].LUT[1<<(x-1)]->z, fp_cache[idx].LUT[1<<x]->z) != MP_OKAY)){ err = MP_INIT_E; break; } else { /* now double it bitlen/FP_LUT times */ for (y = 0; y < lut_gap; y++) { if ((err = ecc_projective_dbl_point(fp_cache[idx].LUT[1<<x], fp_cache[idx].LUT[1<<x], a, modulus, mp)) != MP_OKAY) { break; } } } } /* now make all entries in increase order of hamming weight */ for (x = 2; x <= FP_LUT; x++) { if (err != MP_OKAY) break; for (y = 0; y < (1UL<<FP_LUT); y++) { if (lut_orders[y].ham != (int)x) continue; /* perform the add */ if ((err = ecc_projective_add_point( fp_cache[idx].LUT[lut_orders[y].terma], fp_cache[idx].LUT[lut_orders[y].termb], fp_cache[idx].LUT[y], a, modulus, mp)) != MP_OKAY) { break; } } } /* now map all entries back to affine space to make point addition faster */ for (x = 1; x < (1UL<<FP_LUT); x++) { if (err != MP_OKAY) break; /* convert z to normal from montgomery */ err = mp_montgomery_reduce(fp_cache[idx].LUT[x]->z, modulus, mp); /* invert it */ if (err == MP_OKAY) err = mp_invmod(fp_cache[idx].LUT[x]->z, modulus, fp_cache[idx].LUT[x]->z); if (err == MP_OKAY) /* now square it */ err = mp_sqrmod(fp_cache[idx].LUT[x]->z, modulus, &tmp); if (err == MP_OKAY) /* fix x */ err = mp_mulmod(fp_cache[idx].LUT[x]->x, &tmp, modulus, fp_cache[idx].LUT[x]->x); if (err == MP_OKAY) /* get 1/z^3 */ err = mp_mulmod(&tmp, fp_cache[idx].LUT[x]->z, modulus, &tmp); if (err == MP_OKAY) /* fix y */ err = mp_mulmod(fp_cache[idx].LUT[x]->y, &tmp, modulus, fp_cache[idx].LUT[x]->y); if (err == MP_OKAY) /* free z */ mp_clear(fp_cache[idx].LUT[x]->z); } mp_clear(&tmp); if (err == MP_OKAY) return MP_OKAY; /* err cleanup */ for (y = 0; y < (1U<<FP_LUT); y++) { wc_ecc_del_point(fp_cache[idx].LUT[y]); fp_cache[idx].LUT[y] = NULL; } wc_ecc_del_point(fp_cache[idx].g); fp_cache[idx].g = NULL; fp_cache[idx].lru_count = 0; mp_clear(&fp_cache[idx].mu); return err; } /* perform a fixed point ECC mulmod */ static int accel_fp_mul(int idx, mp_int* k, ecc_point *R, mp_int* a, mp_int* modulus, mp_digit mp, int map) { #define KB_SIZE 128 #ifdef WOLFSSL_SMALL_STACK unsigned char* kb = NULL; #else unsigned char kb[KB_SIZE]; #endif int x, err; unsigned y, z = 0, bitlen, bitpos, lut_gap, first; mp_int tk, order; if (mp_init_multi(&tk, &order, NULL, NULL, NULL, NULL) != MP_OKAY) return MP_INIT_E; /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(k) > mp_unsigned_bin_size(modulus)) { /* find order */ y = mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } /* back off if we are on the 521 bit curve */ if (y == 66) --x; if ((err = mp_read_radix(&order, ecc_sets[x].order, MP_RADIX_HEX)) != MP_OKAY) { goto done; } /* k must be less than modulus */ if (mp_cmp(k, &order) != MP_LT) { if ((err = mp_mod(k, &order, &tk)) != MP_OKAY) { goto done; } } else { if ((err = mp_copy(k, &tk)) != MP_OKAY) { goto done; } } } else { if ((err = mp_copy(k, &tk)) != MP_OKAY) { goto done; } } /* get bitlen and round up to next multiple of FP_LUT */ bitlen = mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { bitlen += FP_LUT - x; } lut_gap = bitlen / FP_LUT; /* get the k value */ if (mp_unsigned_bin_size(&tk) > (int)(KB_SIZE - 2)) { err = BUFFER_E; goto done; } /* store k */ #ifdef WOLFSSL_SMALL_STACK kb = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (kb == NULL) { err = MEMORY_E; goto done; } #endif XMEMSET(kb, 0, KB_SIZE); if ((err = mp_to_unsigned_bin(&tk, kb)) == MP_OKAY) { /* let's reverse kb so it's little endian */ x = 0; y = mp_unsigned_bin_size(&tk); if (y > 0) { y -= 1; } while ((unsigned)x < y) { z = kb[x]; kb[x] = kb[y]; kb[y] = (byte)z; ++x; --y; } /* at this point we can start, yipee */ first = 1; for (x = lut_gap-1; x >= 0; x--) { /* extract FP_LUT bits from kb spread out by lut_gap bits and offset by x bits from the start */ bitpos = x; for (y = z = 0; y < FP_LUT; y++) { z |= ((kb[bitpos>>3] >> (bitpos&7)) & 1) << y; bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid the mult in each loop */ } /* double if not first */ if (!first) { if ((err = ecc_projective_dbl_point(R, R, a, modulus, mp)) != MP_OKAY) { break; } } /* add if not first, otherwise copy */ if (!first && z) { if ((err = ecc_projective_add_point(R, fp_cache[idx].LUT[z], R, a, modulus, mp)) != MP_OKAY) { break; } } else if (z) { if ((mp_copy(fp_cache[idx].LUT[z]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx].LUT[z]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx].mu, R->z) != MP_OKAY)) { err = GEN_MEM_ERR; break; } first = 0; } } } if (err == MP_OKAY) { (void) z; /* Acknowledge the unused assignment */ ForceZero(kb, KB_SIZE); /* map R back from projective space */ if (map) { err = ecc_map(R, modulus, mp); } else { err = MP_OKAY; } } done: /* cleanup */ mp_clear(&order); mp_clear(&tk); #ifdef WOLFSSL_SMALL_STACK XFREE(kb, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif #undef KB_SIZE return err; } #endif #ifdef ECC_SHAMIR #ifndef WOLFSSL_SP_MATH /* perform a fixed point ECC mulmod */ static int accel_fp_mul2add(int idx1, int idx2, mp_int* kA, mp_int* kB, ecc_point *R, mp_int* a, mp_int* modulus, mp_digit mp) { #define KB_SIZE 128 #ifdef WOLFSSL_SMALL_STACK unsigned char* kb[2] = {NULL, NULL}; #else unsigned char kb[2][KB_SIZE]; #endif int x, err; unsigned y, z, bitlen, bitpos, lut_gap, first, zA, zB; mp_int tka, tkb, order; if (mp_init_multi(&tka, &tkb, &order, NULL, NULL, NULL) != MP_OKAY) return MP_INIT_E; /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(kA) > mp_unsigned_bin_size(modulus)) { /* find order */ y = mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } /* back off if we are on the 521 bit curve */ if (y == 66) --x; if ((err = mp_read_radix(&order, ecc_sets[x].order, MP_RADIX_HEX)) != MP_OKAY) { goto done; } /* kA must be less than modulus */ if (mp_cmp(kA, &order) != MP_LT) { if ((err = mp_mod(kA, &order, &tka)) != MP_OKAY) { goto done; } } else { if ((err = mp_copy(kA, &tka)) != MP_OKAY) { goto done; } } } else { if ((err = mp_copy(kA, &tka)) != MP_OKAY) { goto done; } } /* if it's smaller than modulus we fine */ if (mp_unsigned_bin_size(kB) > mp_unsigned_bin_size(modulus)) { /* find order */ y = mp_unsigned_bin_size(modulus); for (x = 0; ecc_sets[x].size; x++) { if (y <= (unsigned)ecc_sets[x].size) break; } /* back off if we are on the 521 bit curve */ if (y == 66) --x; if ((err = mp_read_radix(&order, ecc_sets[x].order, MP_RADIX_HEX)) != MP_OKAY) { goto done; } /* kB must be less than modulus */ if (mp_cmp(kB, &order) != MP_LT) { if ((err = mp_mod(kB, &order, &tkb)) != MP_OKAY) { goto done; } } else { if ((err = mp_copy(kB, &tkb)) != MP_OKAY) { goto done; } } } else { if ((err = mp_copy(kB, &tkb)) != MP_OKAY) { goto done; } } /* get bitlen and round up to next multiple of FP_LUT */ bitlen = mp_unsigned_bin_size(modulus) << 3; x = bitlen % FP_LUT; if (x) { bitlen += FP_LUT - x; } lut_gap = bitlen / FP_LUT; /* get the k value */ if ((mp_unsigned_bin_size(&tka) > (int)(KB_SIZE - 2)) || (mp_unsigned_bin_size(&tkb) > (int)(KB_SIZE - 2)) ) { err = BUFFER_E; goto done; } /* store k */ #ifdef WOLFSSL_SMALL_STACK kb[0] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (kb[0] == NULL) { err = MEMORY_E; goto done; } #endif XMEMSET(kb[0], 0, KB_SIZE); if ((err = mp_to_unsigned_bin(&tka, kb[0])) != MP_OKAY) { goto done; } /* let's reverse kb so it's little endian */ x = 0; y = mp_unsigned_bin_size(&tka); if (y > 0) { y -= 1; } mp_clear(&tka); while ((unsigned)x < y) { z = kb[0][x]; kb[0][x] = kb[0][y]; kb[0][y] = (byte)z; ++x; --y; } /* store b */ #ifdef WOLFSSL_SMALL_STACK kb[1] = (unsigned char*)XMALLOC(KB_SIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (kb[1] == NULL) { err = MEMORY_E; goto done; } #endif XMEMSET(kb[1], 0, KB_SIZE); if ((err = mp_to_unsigned_bin(&tkb, kb[1])) == MP_OKAY) { x = 0; y = mp_unsigned_bin_size(&tkb); if (y > 0) { y -= 1; } while ((unsigned)x < y) { z = kb[1][x]; kb[1][x] = kb[1][y]; kb[1][y] = (byte)z; ++x; --y; } /* at this point we can start, yipee */ first = 1; for (x = lut_gap-1; x >= 0; x--) { /* extract FP_LUT bits from kb spread out by lut_gap bits and offset by x bits from the start */ bitpos = x; for (y = zA = zB = 0; y < FP_LUT; y++) { zA |= ((kb[0][bitpos>>3] >> (bitpos&7)) & 1) << y; zB |= ((kb[1][bitpos>>3] >> (bitpos&7)) & 1) << y; bitpos += lut_gap; /* it's y*lut_gap + x, but here we can avoid the mult in each loop */ } /* double if not first */ if (!first) { if ((err = ecc_projective_dbl_point(R, R, a, modulus, mp)) != MP_OKAY) { break; } } /* add if not first, otherwise copy */ if (!first) { if (zA) { if ((err = ecc_projective_add_point(R, fp_cache[idx1].LUT[zA], R, a, modulus, mp)) != MP_OKAY) { break; } } if (zB) { if ((err = ecc_projective_add_point(R, fp_cache[idx2].LUT[zB], R, a, modulus, mp)) != MP_OKAY) { break; } } } else { if (zA) { if ((mp_copy(fp_cache[idx1].LUT[zA]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx1].LUT[zA]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx1].mu, R->z) != MP_OKAY)) { err = GEN_MEM_ERR; break; } first = 0; } if (zB && first == 0) { if (zB) { if ((err = ecc_projective_add_point(R, fp_cache[idx2].LUT[zB], R, a, modulus, mp)) != MP_OKAY){ break; } } } else if (zB && first == 1) { if ((mp_copy(fp_cache[idx2].LUT[zB]->x, R->x) != MP_OKAY) || (mp_copy(fp_cache[idx2].LUT[zB]->y, R->y) != MP_OKAY) || (mp_copy(&fp_cache[idx2].mu, R->z) != MP_OKAY)) { err = GEN_MEM_ERR; break; } first = 0; } } } } done: /* cleanup */ mp_clear(&tkb); mp_clear(&tka); mp_clear(&order); #ifdef WOLFSSL_SMALL_STACK if (kb[0]) #endif ForceZero(kb[0], KB_SIZE); #ifdef WOLFSSL_SMALL_STACK if (kb[1]) #endif ForceZero(kb[1], KB_SIZE); #ifdef WOLFSSL_SMALL_STACK XFREE(kb[0], NULL, DYNAMIC_TYPE_ECC_BUFFER); XFREE(kb[1], NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif #undef KB_SIZE if (err != MP_OKAY) return err; return ecc_map(R, modulus, mp); } /** ECC Fixed Point mulmod global with heap hint used Computes kA*A + kB*B = C using Shamir's Trick A First point to multiply kA What to multiple A by B Second point to multiply kB What to multiple B by C [out] Destination point (can overlap with A or B) a ECC curve parameter a modulus Modulus for curve return MP_OKAY on success */ int ecc_mul2add(ecc_point* A, mp_int* kA, ecc_point* B, mp_int* kB, ecc_point* C, mp_int* a, mp_int* modulus, void* heap) { int idx1 = -1, idx2 = -1, err = MP_OKAY, mpInit = 0; mp_digit mp; mp_int mu; err = mp_init(&mu); if (err != MP_OKAY) return err; #ifndef HAVE_THREAD_LS if (initMutex == 0) { wc_InitMutex(&ecc_fp_lock); initMutex = 1; } if (wc_LockMutex(&ecc_fp_lock) != 0) return BAD_MUTEX_E; #endif /* HAVE_THREAD_LS */ /* find point */ idx1 = find_base(A); /* no entry? */ if (idx1 == -1) { /* find hole and add it */ if ((idx1 = find_hole()) >= 0) { err = add_entry(idx1, A); } } if (err == MP_OKAY && idx1 != -1) { /* increment LRU */ ++(fp_cache[idx1].lru_count); } if (err == MP_OKAY) /* find point */ idx2 = find_base(B); if (err == MP_OKAY) { /* no entry? */ if (idx2 == -1) { /* find hole and add it */ if ((idx2 = find_hole()) >= 0) err = add_entry(idx2, B); } } if (err == MP_OKAY && idx2 != -1) { /* increment LRU */ ++(fp_cache[idx2].lru_count); } if (err == MP_OKAY) { /* if it's 2 build the LUT, if it's higher just use the LUT */ if (idx1 >= 0 && fp_cache[idx1].lru_count == 2) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { mpInit = 1; err = mp_montgomery_calc_normalization(&mu, modulus); } if (err == MP_OKAY) /* build the LUT */ err = build_lut(idx1, a, modulus, mp, &mu); } } if (err == MP_OKAY) { /* if it's 2 build the LUT, if it's higher just use the LUT */ if (idx2 >= 0 && fp_cache[idx2].lru_count == 2) { if (mpInit == 0) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { mpInit = 1; err = mp_montgomery_calc_normalization(&mu, modulus); } } if (err == MP_OKAY) /* build the LUT */ err = build_lut(idx2, a, modulus, mp, &mu); } } if (err == MP_OKAY) { if (idx1 >=0 && idx2 >= 0 && fp_cache[idx1].lru_count >= 2 && fp_cache[idx2].lru_count >= 2) { if (mpInit == 0) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); } if (err == MP_OKAY) err = accel_fp_mul2add(idx1, idx2, kA, kB, C, a, modulus, mp); } else { err = normal_ecc_mul2add(A, kA, B, kB, C, a, modulus, heap); } } #ifndef HAVE_THREAD_LS wc_UnLockMutex(&ecc_fp_lock); #endif /* HAVE_THREAD_LS */ mp_clear(&mu); return err; } #endif #endif /* ECC_SHAMIR */ /** ECC Fixed Point mulmod global k The multiplicand G Base point to multiply R [out] Destination of product a ECC curve parameter a modulus The modulus for the curve map [boolean] If non-zero maps the point back to affine co-ordinates, otherwise it's left in jacobian-montgomery form return MP_OKAY if successful */ int wc_ecc_mulmod_ex(mp_int* k, ecc_point *G, ecc_point *R, mp_int* a, mp_int* modulus, int map, void* heap) { #ifndef WOLFSSL_SP_MATH int idx, err = MP_OKAY; mp_digit mp; mp_int mu; int mpSetup = 0; if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } if (mp_init(&mu) != MP_OKAY) return MP_INIT_E; #ifndef HAVE_THREAD_LS if (initMutex == 0) { wc_InitMutex(&ecc_fp_lock); initMutex = 1; } if (wc_LockMutex(&ecc_fp_lock) != 0) return BAD_MUTEX_E; #endif /* HAVE_THREAD_LS */ /* find point */ idx = find_base(G); /* no entry? */ if (idx == -1) { /* find hole and add it */ idx = find_hole(); if (idx >= 0) err = add_entry(idx, G); } if (err == MP_OKAY && idx >= 0) { /* increment LRU */ ++(fp_cache[idx].lru_count); } if (err == MP_OKAY) { /* if it's 2 build the LUT, if it's higher just use the LUT */ if (idx >= 0 && fp_cache[idx].lru_count == 2) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); if (err == MP_OKAY) { /* compute mu */ mpSetup = 1; err = mp_montgomery_calc_normalization(&mu, modulus); } if (err == MP_OKAY) /* build the LUT */ err = build_lut(idx, a, modulus, mp, &mu); } } if (err == MP_OKAY) { if (idx >= 0 && fp_cache[idx].lru_count >= 2) { if (mpSetup == 0) { /* compute mp */ err = mp_montgomery_setup(modulus, &mp); } if (err == MP_OKAY) err = accel_fp_mul(idx, k, R, a, modulus, mp, map); } else { err = normal_ecc_mulmod(k, G, R, a, modulus, map, heap); } } #ifndef HAVE_THREAD_LS wc_UnLockMutex(&ecc_fp_lock); #endif /* HAVE_THREAD_LS */ mp_clear(&mu); return err; #else if (k == NULL || G == NULL || R == NULL || a == NULL || modulus == NULL) { return ECC_BAD_ARG_E; } return sp_ecc_mulmod_256(k, G, R, map, heap); #endif } #ifndef WOLFSSL_SP_MATH /* helper function for freeing the cache ... must be called with the cache mutex locked */ static void wc_ecc_fp_free_cache(void) { unsigned x, y; for (x = 0; x < FP_ENTRIES; x++) { if (fp_cache[x].g != NULL) { for (y = 0; y < (1U<<FP_LUT); y++) { wc_ecc_del_point(fp_cache[x].LUT[y]); fp_cache[x].LUT[y] = NULL; } wc_ecc_del_point(fp_cache[x].g); fp_cache[x].g = NULL; mp_clear(&fp_cache[x].mu); fp_cache[x].lru_count = 0; fp_cache[x].lock = 0; } } } #endif /** Free the Fixed Point cache */ void wc_ecc_fp_free(void) { #ifndef WOLFSSL_SP_MATH #ifndef HAVE_THREAD_LS if (initMutex == 0) { wc_InitMutex(&ecc_fp_lock); initMutex = 1; } if (wc_LockMutex(&ecc_fp_lock) == 0) { #endif /* HAVE_THREAD_LS */ wc_ecc_fp_free_cache(); #ifndef HAVE_THREAD_LS wc_UnLockMutex(&ecc_fp_lock); wc_FreeMutex(&ecc_fp_lock); initMutex = 0; } #endif /* HAVE_THREAD_LS */ #endif } #endif /* FP_ECC */ #ifdef HAVE_ECC_ENCRYPT enum ecCliState { ecCLI_INIT = 1, ecCLI_SALT_GET = 2, ecCLI_SALT_SET = 3, ecCLI_SENT_REQ = 4, ecCLI_RECV_RESP = 5, ecCLI_BAD_STATE = 99 }; enum ecSrvState { ecSRV_INIT = 1, ecSRV_SALT_GET = 2, ecSRV_SALT_SET = 3, ecSRV_RECV_REQ = 4, ecSRV_SENT_RESP = 5, ecSRV_BAD_STATE = 99 }; struct ecEncCtx { const byte* kdfSalt; /* optional salt for kdf */ const byte* kdfInfo; /* optional info for kdf */ const byte* macSalt; /* optional salt for mac */ word32 kdfSaltSz; /* size of kdfSalt */ word32 kdfInfoSz; /* size of kdfInfo */ word32 macSaltSz; /* size of macSalt */ void* heap; /* heap hint for memory used */ byte clientSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */ byte serverSalt[EXCHANGE_SALT_SZ]; /* for msg exchange */ byte encAlgo; /* which encryption type */ byte kdfAlgo; /* which key derivation function type */ byte macAlgo; /* which mac function type */ byte protocol; /* are we REQ_RESP client or server ? */ byte cliSt; /* protocol state, for sanity checks */ byte srvSt; /* protocol state, for sanity checks */ }; const byte* wc_ecc_ctx_get_own_salt(ecEncCtx* ctx) { if (ctx == NULL || ctx->protocol == 0) return NULL; if (ctx->protocol == REQ_RESP_CLIENT) { if (ctx->cliSt == ecCLI_INIT) { ctx->cliSt = ecCLI_SALT_GET; return ctx->clientSalt; } else { ctx->cliSt = ecCLI_BAD_STATE; return NULL; } } else if (ctx->protocol == REQ_RESP_SERVER) { if (ctx->srvSt == ecSRV_INIT) { ctx->srvSt = ecSRV_SALT_GET; return ctx->serverSalt; } else { ctx->srvSt = ecSRV_BAD_STATE; return NULL; } } return NULL; } /* optional set info, can be called before or after set_peer_salt */ int wc_ecc_ctx_set_info(ecEncCtx* ctx, const byte* info, int sz) { if (ctx == NULL || info == 0 || sz < 0) return BAD_FUNC_ARG; ctx->kdfInfo = info; ctx->kdfInfoSz = sz; return 0; } static const char* exchange_info = "Secure Message Exchange"; int wc_ecc_ctx_set_peer_salt(ecEncCtx* ctx, const byte* salt) { byte tmp[EXCHANGE_SALT_SZ/2]; int halfSz = EXCHANGE_SALT_SZ/2; if (ctx == NULL || ctx->protocol == 0 || salt == NULL) return BAD_FUNC_ARG; if (ctx->protocol == REQ_RESP_CLIENT) { XMEMCPY(ctx->serverSalt, salt, EXCHANGE_SALT_SZ); if (ctx->cliSt == ecCLI_SALT_GET) ctx->cliSt = ecCLI_SALT_SET; else { ctx->cliSt = ecCLI_BAD_STATE; return BAD_STATE_E; } } else { XMEMCPY(ctx->clientSalt, salt, EXCHANGE_SALT_SZ); if (ctx->srvSt == ecSRV_SALT_GET) ctx->srvSt = ecSRV_SALT_SET; else { ctx->srvSt = ecSRV_BAD_STATE; return BAD_STATE_E; } } /* mix half and half */ /* tmp stores 2nd half of client before overwrite */ XMEMCPY(tmp, ctx->clientSalt + halfSz, halfSz); XMEMCPY(ctx->clientSalt + halfSz, ctx->serverSalt, halfSz); XMEMCPY(ctx->serverSalt, tmp, halfSz); ctx->kdfSalt = ctx->clientSalt; ctx->kdfSaltSz = EXCHANGE_SALT_SZ; ctx->macSalt = ctx->serverSalt; ctx->macSaltSz = EXCHANGE_SALT_SZ; if (ctx->kdfInfo == NULL) { /* default info */ ctx->kdfInfo = (const byte*)exchange_info; ctx->kdfInfoSz = EXCHANGE_INFO_SZ; } return 0; } static int ecc_ctx_set_salt(ecEncCtx* ctx, int flags, WC_RNG* rng) { byte* saltBuffer = NULL; if (ctx == NULL || rng == NULL || flags == 0) return BAD_FUNC_ARG; saltBuffer = (flags == REQ_RESP_CLIENT) ? ctx->clientSalt : ctx->serverSalt; return wc_RNG_GenerateBlock(rng, saltBuffer, EXCHANGE_SALT_SZ); } static void ecc_ctx_init(ecEncCtx* ctx, int flags) { if (ctx) { XMEMSET(ctx, 0, sizeof(ecEncCtx)); ctx->encAlgo = ecAES_128_CBC; ctx->kdfAlgo = ecHKDF_SHA256; ctx->macAlgo = ecHMAC_SHA256; ctx->protocol = (byte)flags; if (flags == REQ_RESP_CLIENT) ctx->cliSt = ecCLI_INIT; if (flags == REQ_RESP_SERVER) ctx->srvSt = ecSRV_INIT; } } /* allow ecc context reset so user doesn't have to init/free for reuse */ int wc_ecc_ctx_reset(ecEncCtx* ctx, WC_RNG* rng) { if (ctx == NULL || rng == NULL) return BAD_FUNC_ARG; ecc_ctx_init(ctx, ctx->protocol); return ecc_ctx_set_salt(ctx, ctx->protocol, rng); } ecEncCtx* wc_ecc_ctx_new_ex(int flags, WC_RNG* rng, void* heap) { int ret = 0; ecEncCtx* ctx = (ecEncCtx*)XMALLOC(sizeof(ecEncCtx), heap, DYNAMIC_TYPE_ECC); if (ctx) { ctx->protocol = (byte)flags; ctx->heap = heap; } ret = wc_ecc_ctx_reset(ctx, rng); if (ret != 0) { wc_ecc_ctx_free(ctx); ctx = NULL; } return ctx; } /* alloc/init and set defaults, return new Context */ ecEncCtx* wc_ecc_ctx_new(int flags, WC_RNG* rng) { return wc_ecc_ctx_new_ex(flags, rng, NULL); } /* free any resources, clear any keys */ void wc_ecc_ctx_free(ecEncCtx* ctx) { if (ctx) { ForceZero(ctx, sizeof(ecEncCtx)); XFREE(ctx, ctx->heap, DYNAMIC_TYPE_ECC); } } static int ecc_get_key_sizes(ecEncCtx* ctx, int* encKeySz, int* ivSz, int* keysLen, word32* digestSz, word32* blockSz) { if (ctx) { switch (ctx->encAlgo) { case ecAES_128_CBC: *encKeySz = KEY_SIZE_128; *ivSz = IV_SIZE_128; *blockSz = AES_BLOCK_SIZE; break; default: return BAD_FUNC_ARG; } switch (ctx->macAlgo) { case ecHMAC_SHA256: *digestSz = WC_SHA256_DIGEST_SIZE; break; default: return BAD_FUNC_ARG; } } else return BAD_FUNC_ARG; *keysLen = *encKeySz + *ivSz + *digestSz; return 0; } /* ecc encrypt with shared secret run through kdf ctx holds non default algos and inputs msgSz should be the right size for encAlgo, i.e., already padded return 0 on success */ int wc_ecc_encrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx) { int ret = 0; word32 blockSz; word32 digestSz; ecEncCtx localCtx; #ifdef WOLFSSL_SMALL_STACK byte* sharedSecret; byte* keys; #else byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */ byte keys[ECC_BUFSIZE]; /* max size */ #endif word32 sharedSz = ECC_MAXSIZE; int keysLen; int encKeySz; int ivSz; int offset = 0; /* keys offset if doing msg exchange */ byte* encKey; byte* encIv; byte* macKey; if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL || outSz == NULL) return BAD_FUNC_ARG; if (ctx == NULL) { /* use defaults */ ecc_ctx_init(&localCtx, 0); ctx = &localCtx; } ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz, &blockSz); if (ret != 0) return ret; if (ctx->protocol == REQ_RESP_SERVER) { offset = keysLen; keysLen *= 2; if (ctx->srvSt != ecSRV_RECV_REQ) return BAD_STATE_E; ctx->srvSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */ } else if (ctx->protocol == REQ_RESP_CLIENT) { if (ctx->cliSt != ecCLI_SALT_SET) return BAD_STATE_E; ctx->cliSt = ecCLI_SENT_REQ; /* only do this once */ } if (keysLen > ECC_BUFSIZE) /* keys size */ return BUFFER_E; if ( (msgSz%blockSz) != 0) return BAD_PADDING_E; if (*outSz < (msgSz + digestSz)) return BUFFER_E; #ifdef WOLFSSL_SMALL_STACK sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (sharedSecret == NULL) return MEMORY_E; keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (keys == NULL) { XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); return MEMORY_E; } #endif do { #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); if (ret != 0) break; #endif ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz); } while (ret == WC_PENDING_E); if (ret == 0) { switch (ctx->kdfAlgo) { case ecHKDF_SHA256 : ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt, ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz, keys, keysLen); break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { encKey = keys + offset; encIv = encKey + encKeySz; macKey = encKey + encKeySz + ivSz; switch (ctx->encAlgo) { case ecAES_128_CBC: { Aes aes; ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv, AES_ENCRYPTION); if (ret != 0) break; ret = wc_AesCbcEncrypt(&aes, out, msg, msgSz); #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &aes.asyncDev, WC_ASYNC_FLAG_NONE); #endif } break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { switch (ctx->macAlgo) { case ecHMAC_SHA256: { Hmac hmac; ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID); if (ret == 0) { ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE); if (ret == 0) ret = wc_HmacUpdate(&hmac, out, msgSz); if (ret == 0) ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz); if (ret == 0) ret = wc_HmacFinal(&hmac, out+msgSz); wc_HmacFree(&hmac); } } break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) *outSz = msgSz + digestSz; #ifdef WOLFSSL_SMALL_STACK XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return ret; } /* ecc decrypt with shared secret run through kdf ctx holds non default algos and inputs return 0 on success */ int wc_ecc_decrypt(ecc_key* privKey, ecc_key* pubKey, const byte* msg, word32 msgSz, byte* out, word32* outSz, ecEncCtx* ctx) { int ret = 0; word32 blockSz; word32 digestSz; ecEncCtx localCtx; #ifdef WOLFSSL_SMALL_STACK byte* sharedSecret; byte* keys; #else byte sharedSecret[ECC_MAXSIZE]; /* 521 max size */ byte keys[ECC_BUFSIZE]; /* max size */ #endif word32 sharedSz = ECC_MAXSIZE; int keysLen; int encKeySz; int ivSz; int offset = 0; /* in case using msg exchange */ byte* encKey; byte* encIv; byte* macKey; if (privKey == NULL || pubKey == NULL || msg == NULL || out == NULL || outSz == NULL) return BAD_FUNC_ARG; if (ctx == NULL) { /* use defaults */ ecc_ctx_init(&localCtx, 0); ctx = &localCtx; } ret = ecc_get_key_sizes(ctx, &encKeySz, &ivSz, &keysLen, &digestSz, &blockSz); if (ret != 0) return ret; if (ctx->protocol == REQ_RESP_CLIENT) { offset = keysLen; keysLen *= 2; if (ctx->cliSt != ecCLI_SENT_REQ) return BAD_STATE_E; ctx->cliSt = ecSRV_BAD_STATE; /* we're done no more ops allowed */ } else if (ctx->protocol == REQ_RESP_SERVER) { if (ctx->srvSt != ecSRV_SALT_SET) return BAD_STATE_E; ctx->srvSt = ecSRV_RECV_REQ; /* only do this once */ } if (keysLen > ECC_BUFSIZE) /* keys size */ return BUFFER_E; if ( ((msgSz-digestSz) % blockSz) != 0) return BAD_PADDING_E; if (*outSz < (msgSz - digestSz)) return BUFFER_E; #ifdef WOLFSSL_SMALL_STACK sharedSecret = (byte*)XMALLOC(ECC_MAXSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (sharedSecret == NULL) return MEMORY_E; keys = (byte*)XMALLOC(ECC_BUFSIZE, NULL, DYNAMIC_TYPE_ECC_BUFFER); if (keys == NULL) { XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); return MEMORY_E; } #endif do { #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &privKey->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN); if (ret != 0) break; #endif ret = wc_ecc_shared_secret(privKey, pubKey, sharedSecret, &sharedSz); } while (ret == WC_PENDING_E); if (ret == 0) { switch (ctx->kdfAlgo) { case ecHKDF_SHA256 : ret = wc_HKDF(WC_SHA256, sharedSecret, sharedSz, ctx->kdfSalt, ctx->kdfSaltSz, ctx->kdfInfo, ctx->kdfInfoSz, keys, keysLen); break; default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { encKey = keys + offset; encIv = encKey + encKeySz; macKey = encKey + encKeySz + ivSz; switch (ctx->macAlgo) { case ecHMAC_SHA256: { byte verify[WC_SHA256_DIGEST_SIZE]; Hmac hmac; ret = wc_HmacInit(&hmac, NULL, INVALID_DEVID); if (ret == 0) { ret = wc_HmacSetKey(&hmac, WC_SHA256, macKey, WC_SHA256_DIGEST_SIZE); if (ret == 0) ret = wc_HmacUpdate(&hmac, msg, msgSz-digestSz); if (ret == 0) ret = wc_HmacUpdate(&hmac, ctx->macSalt, ctx->macSaltSz); if (ret == 0) ret = wc_HmacFinal(&hmac, verify); if (ret == 0) { if (XMEMCMP(verify, msg + msgSz - digestSz, digestSz) != 0) ret = -1; } wc_HmacFree(&hmac); } break; } default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) { switch (ctx->encAlgo) { #ifdef HAVE_AES_CBC case ecAES_128_CBC: { Aes aes; ret = wc_AesSetKey(&aes, encKey, KEY_SIZE_128, encIv, AES_DECRYPTION); if (ret != 0) break; ret = wc_AesCbcDecrypt(&aes, out, msg, msgSz-digestSz); #if defined(WOLFSSL_ASYNC_CRYPT) ret = wc_AsyncWait(ret, &aes.asyncDev, WC_ASYNC_FLAG_NONE); #endif } break; #endif default: ret = BAD_FUNC_ARG; break; } } if (ret == 0) *outSz = msgSz - digestSz; #ifdef WOLFSSL_SMALL_STACK XFREE(sharedSecret, NULL, DYNAMIC_TYPE_ECC_BUFFER); XFREE(keys, NULL, DYNAMIC_TYPE_ECC_BUFFER); #endif return ret; } #endif /* HAVE_ECC_ENCRYPT */ #ifdef HAVE_COMP_KEY #ifndef WOLFSSL_ATECC508A #ifndef WOLFSSL_SP_MATH int do_mp_jacobi(mp_int* a, mp_int* n, int* c); int do_mp_jacobi(mp_int* a, mp_int* n, int* c) { int k, s, res; int r = 0; /* initialize to help static analysis out */ mp_digit residue; /* if a < 0 return MP_VAL */ if (mp_isneg(a) == MP_YES) { return MP_VAL; } /* if n <= 0 return MP_VAL */ if (mp_cmp_d(n, 0) != MP_GT) { return MP_VAL; } /* step 1. handle case of a == 0 */ if (mp_iszero (a) == MP_YES) { /* special case of a == 0 and n == 1 */ if (mp_cmp_d (n, 1) == MP_EQ) { *c = 1; } else { *c = 0; } return MP_OKAY; } /* step 2. if a == 1, return 1 */ if (mp_cmp_d (a, 1) == MP_EQ) { *c = 1; return MP_OKAY; } /* default */ s = 0; /* divide out larger power of two */ k = mp_cnt_lsb(a); res = mp_div_2d(a, k, a, NULL); if (res == MP_OKAY) { /* step 4. if e is even set s=1 */ if ((k & 1) == 0) { s = 1; } else { /* else set s=1 if p = 1/7 (mod 8) or s=-1 if p = 3/5 (mod 8) */ residue = n->dp[0] & 7; if (residue == 1 || residue == 7) { s = 1; } else if (residue == 3 || residue == 5) { s = -1; } } /* step 5. if p == 3 (mod 4) *and* a == 3 (mod 4) then s = -s */ if ( ((n->dp[0] & 3) == 3) && ((a->dp[0] & 3) == 3)) { s = -s; } } if (res == MP_OKAY) { /* if a == 1 we're done */ if (mp_cmp_d(a, 1) == MP_EQ) { *c = s; } else { /* n1 = n mod a */ res = mp_mod (n, a, n); if (res == MP_OKAY) res = do_mp_jacobi(n, a, &r); if (res == MP_OKAY) *c = s * r; } } return res; } /* computes the jacobi c = (a | n) (or Legendre if n is prime) * HAC pp. 73 Algorithm 2.149 * HAC is wrong here, as the special case of (0 | 1) is not * handled correctly. */ int mp_jacobi(mp_int* a, mp_int* n, int* c) { mp_int a1, n1; int res; /* step 3. write a = a1 * 2**k */ if ((res = mp_init_multi(&a1, &n1, NULL, NULL, NULL, NULL)) != MP_OKAY) { return res; } if ((res = mp_copy(a, &a1)) != MP_OKAY) { goto done; } if ((res = mp_copy(n, &n1)) != MP_OKAY) { goto done; } res = do_mp_jacobi(&a1, &n1, c); done: /* cleanup */ mp_clear(&n1); mp_clear(&a1); return res; } /* Solves the modular equation x^2 = n (mod p) * where prime number is greater than 2 (odd prime). * The result is returned in the third argument x * the function returns MP_OKAY on success, MP_VAL or another error on failure */ int mp_sqrtmod_prime(mp_int* n, mp_int* prime, mp_int* ret) { #ifdef SQRTMOD_USE_MOD_EXP int res; mp_int e; res = mp_init(&e); if (res == MP_OKAY) res = mp_add_d(prime, 1, &e); if (res == MP_OKAY) res = mp_div_2d(&e, 2, &e, NULL); if (res == MP_OKAY) res = mp_exptmod(n, &e, prime, ret); mp_clear(&e); return res; #else int res, legendre, done = 0; mp_int t1, C, Q, S, Z, M, T, R, two; mp_digit i; /* first handle the simple cases n = 0 or n = 1 */ if (mp_cmp_d(n, 0) == MP_EQ) { mp_zero(ret); return MP_OKAY; } if (mp_cmp_d(n, 1) == MP_EQ) { return mp_set(ret, 1); } /* prime must be odd */ if (mp_cmp_d(prime, 2) == MP_EQ) { return MP_VAL; } /* is quadratic non-residue mod prime */ if ((res = mp_jacobi(n, prime, &legendre)) != MP_OKAY) { return res; } if (legendre == -1) { return MP_VAL; } if ((res = mp_init_multi(&t1, &C, &Q, &S, &Z, &M)) != MP_OKAY) return res; if ((res = mp_init_multi(&T, &R, &two, NULL, NULL, NULL)) != MP_OKAY) { mp_clear(&t1); mp_clear(&C); mp_clear(&Q); mp_clear(&S); mp_clear(&Z); mp_clear(&M); return res; } /* SPECIAL CASE: if prime mod 4 == 3 * compute directly: res = n^(prime+1)/4 mod prime * Handbook of Applied Cryptography algorithm 3.36 */ res = mp_mod_d(prime, 4, &i); if (res == MP_OKAY && i == 3) { res = mp_add_d(prime, 1, &t1); if (res == MP_OKAY) res = mp_div_2(&t1, &t1); if (res == MP_OKAY) res = mp_div_2(&t1, &t1); if (res == MP_OKAY) res = mp_exptmod(n, &t1, prime, ret); done = 1; } /* NOW: TonelliShanks algorithm */ if (res == MP_OKAY && done == 0) { /* factor out powers of 2 from prime-1, defining Q and S * as: prime-1 = Q*2^S */ /* Q = prime - 1 */ res = mp_copy(prime, &Q); if (res == MP_OKAY) res = mp_sub_d(&Q, 1, &Q); /* S = 0 */ if (res == MP_OKAY) mp_zero(&S); while (res == MP_OKAY && mp_iseven(&Q) == MP_YES) { /* Q = Q / 2 */ res = mp_div_2(&Q, &Q); /* S = S + 1 */ if (res == MP_OKAY) res = mp_add_d(&S, 1, &S); } /* find a Z such that the Legendre symbol (Z|prime) == -1 */ /* Z = 2 */ if (res == MP_OKAY) res = mp_set_int(&Z, 2); while (res == MP_OKAY) { res = mp_jacobi(&Z, prime, &legendre); if (res == MP_OKAY && legendre == -1) break; /* Z = Z + 1 */ if (res == MP_OKAY) res = mp_add_d(&Z, 1, &Z); } /* C = Z ^ Q mod prime */ if (res == MP_OKAY) res = mp_exptmod(&Z, &Q, prime, &C); /* t1 = (Q + 1) / 2 */ if (res == MP_OKAY) res = mp_add_d(&Q, 1, &t1); if (res == MP_OKAY) res = mp_div_2(&t1, &t1); /* R = n ^ ((Q + 1) / 2) mod prime */ if (res == MP_OKAY) res = mp_exptmod(n, &t1, prime, &R); /* T = n ^ Q mod prime */ if (res == MP_OKAY) res = mp_exptmod(n, &Q, prime, &T); /* M = S */ if (res == MP_OKAY) res = mp_copy(&S, &M); if (res == MP_OKAY) res = mp_set_int(&two, 2); while (res == MP_OKAY && done == 0) { res = mp_copy(&T, &t1); /* reduce to 1 and count */ i = 0; while (res == MP_OKAY) { if (mp_cmp_d(&t1, 1) == MP_EQ) break; res = mp_exptmod(&t1, &two, prime, &t1); if (res == MP_OKAY) i++; } if (res == MP_OKAY && i == 0) { res = mp_copy(&R, ret); done = 1; } if (done == 0) { /* t1 = 2 ^ (M - i - 1) */ if (res == MP_OKAY) res = mp_sub_d(&M, i, &t1); if (res == MP_OKAY) res = mp_sub_d(&t1, 1, &t1); if (res == MP_OKAY) res = mp_exptmod(&two, &t1, prime, &t1); /* t1 = C ^ (2 ^ (M - i - 1)) mod prime */ if (res == MP_OKAY) res = mp_exptmod(&C, &t1, prime, &t1); /* C = (t1 * t1) mod prime */ if (res == MP_OKAY) res = mp_sqrmod(&t1, prime, &C); /* R = (R * t1) mod prime */ if (res == MP_OKAY) res = mp_mulmod(&R, &t1, prime, &R); /* T = (T * C) mod prime */ if (res == MP_OKAY) res = mp_mulmod(&T, &C, prime, &T); /* M = i */ if (res == MP_OKAY) res = mp_set(&M, i); } } } /* done */ mp_clear(&t1); mp_clear(&C); mp_clear(&Q); mp_clear(&S); mp_clear(&Z); mp_clear(&M); mp_clear(&T); mp_clear(&R); mp_clear(&two); return res; #endif } #endif #endif /* !WOLFSSL_ATECC508A */ /* export public ECC key in ANSI X9.63 format compressed */ static int wc_ecc_export_x963_compressed(ecc_key* key, byte* out, word32* outLen) { word32 numlen; int ret = MP_OKAY; if (key == NULL || out == NULL || outLen == NULL) return BAD_FUNC_ARG; if (wc_ecc_is_valid_idx(key->idx) == 0) { return ECC_BAD_ARG_E; } numlen = key->dp->size; if (*outLen < (1 + numlen)) { *outLen = 1 + numlen; return BUFFER_E; } #ifdef WOLFSSL_ATECC508A /* TODO: Implement equiv call to ATECC508A */ ret = BAD_COND_E; #else /* store first byte */ out[0] = mp_isodd(key->pubkey.y) == MP_YES ? ECC_POINT_COMP_ODD : ECC_POINT_COMP_EVEN; /* pad and store x */ XMEMSET(out+1, 0, numlen); ret = mp_to_unsigned_bin(key->pubkey.x, out+1 + (numlen - mp_unsigned_bin_size(key->pubkey.x))); *outLen = 1 + numlen; #endif /* WOLFSSL_ATECC508A */ return ret; } #endif /* HAVE_COMP_KEY */ int wc_ecc_get_oid(word32 oidSum, const byte** oid, word32* oidSz) { int x; if (oidSum == 0) { return BAD_FUNC_ARG; } /* find matching OID sum (based on encoded value) */ for (x = 0; ecc_sets[x].size != 0; x++) { if (ecc_sets[x].oidSum == oidSum) { int ret = 0; #ifdef HAVE_OID_ENCODING /* check cache */ oid_cache_t* o = &ecc_oid_cache[x]; if (o->oidSz == 0) { o->oidSz = sizeof(o->oid); ret = EncodeObjectId(ecc_sets[x].oid, ecc_sets[x].oidSz, o->oid, &o->oidSz); } if (oidSz) { *oidSz = o->oidSz; } if (oid) { *oid = o->oid; } #else if (oidSz) { *oidSz = ecc_sets[x].oidSz; } if (oid) { *oid = ecc_sets[x].oid; } #endif /* on success return curve id */ if (ret == 0) { ret = ecc_sets[x].id; } return ret; } } return NOT_COMPILED_IN; } #ifdef WOLFSSL_CUSTOM_CURVES int wc_ecc_set_custom_curve(ecc_key* key, const ecc_set_type* dp) { if (key == NULL || dp == NULL) { return BAD_FUNC_ARG; } key->idx = ECC_CUSTOM_IDX; key->dp = dp; return 0; } #endif /* WOLFSSL_CUSTOM_CURVES */ #ifdef HAVE_X963_KDF static INLINE void IncrementX963KdfCounter(byte* inOutCtr) { int i; /* in network byte order so start at end and work back */ for (i = 3; i >= 0; i--) { if (++inOutCtr[i]) /* we're done unless we overflow */ return; } } /* ASN X9.63 Key Derivation Function (SEC1) */ int wc_X963_KDF(enum wc_HashType type, const byte* secret, word32 secretSz, const byte* sinfo, word32 sinfoSz, byte* out, word32 outSz) { int ret, i; int digestSz, copySz; int remaining = outSz; byte* outIdx; byte counter[4]; byte tmp[WC_MAX_DIGEST_SIZE]; #ifdef WOLFSSL_SMALL_STACK wc_HashAlg* hash; #else wc_HashAlg hash[1]; #endif if (secret == NULL || secretSz == 0 || out == NULL) return BAD_FUNC_ARG; /* X9.63 allowed algos only */ if (type != WC_HASH_TYPE_SHA && type != WC_HASH_TYPE_SHA224 && type != WC_HASH_TYPE_SHA256 && type != WC_HASH_TYPE_SHA384 && type != WC_HASH_TYPE_SHA512) return BAD_FUNC_ARG; digestSz = wc_HashGetDigestSize(type); if (digestSz < 0) return digestSz; #ifdef WOLFSSL_SMALL_STACK hash = (wc_HashAlg*)XMALLOC(sizeof(wc_HashAlg), NULL, DYNAMIC_TYPE_HASHES); if (hash == NULL) return MEMORY_E; #endif ret = wc_HashInit(hash, type); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } outIdx = out; XMEMSET(counter, 0, sizeof(counter)); for (i = 1; remaining > 0; i++) { IncrementX963KdfCounter(counter); ret = wc_HashUpdate(hash, type, secret, secretSz); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } ret = wc_HashUpdate(hash, type, counter, sizeof(counter)); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } if (sinfo) { ret = wc_HashUpdate(hash, type, sinfo, sinfoSz); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } } ret = wc_HashFinal(hash, type, tmp); if (ret != 0) { #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return ret; } copySz = min(remaining, digestSz); XMEMCPY(outIdx, tmp, copySz); remaining -= copySz; outIdx += copySz; } #ifdef WOLFSSL_SMALL_STACK XFREE(hash, NULL, DYNAMIC_TYPE_HASHES); #endif return 0; } #endif /* HAVE_X963_KDF */ #endif /* HAVE_ECC */
./CrossVul/dataset_final_sorted/CWE-200/c/good_187_0
crossvul-cpp_data_bad_3366_0
/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com * Copyright (c) 2016 Facebook * * This program is free software; you can redistribute it and/or * modify it under the terms of version 2 of the GNU General Public * License as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. */ #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/bpf.h> #include <linux/bpf_verifier.h> #include <linux/filter.h> #include <net/netlink.h> #include <linux/file.h> #include <linux/vmalloc.h> #include <linux/stringify.h> /* bpf_check() is a static code analyzer that walks eBPF program * instruction by instruction and updates register/stack state. * All paths of conditional branches are analyzed until 'bpf_exit' insn. * * The first pass is depth-first-search to check that the program is a DAG. * It rejects the following programs: * - larger than BPF_MAXINSNS insns * - if loop is present (detected via back-edge) * - unreachable insns exist (shouldn't be a forest. program = one function) * - out of bounds or malformed jumps * The second pass is all possible path descent from the 1st insn. * Since it's analyzing all pathes through the program, the length of the * analysis is limited to 64k insn, which may be hit even if total number of * insn is less then 4K, but there are too many branches that change stack/regs. * Number of 'branches to be analyzed' is limited to 1k * * On entry to each instruction, each register has a type, and the instruction * changes the types of the registers depending on instruction semantics. * If instruction is BPF_MOV64_REG(BPF_REG_1, BPF_REG_5), then type of R5 is * copied to R1. * * All registers are 64-bit. * R0 - return register * R1-R5 argument passing registers * R6-R9 callee saved registers * R10 - frame pointer read-only * * At the start of BPF program the register R1 contains a pointer to bpf_context * and has type PTR_TO_CTX. * * Verifier tracks arithmetic operations on pointers in case: * BPF_MOV64_REG(BPF_REG_1, BPF_REG_10), * BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -20), * 1st insn copies R10 (which has FRAME_PTR) type into R1 * and 2nd arithmetic instruction is pattern matched to recognize * that it wants to construct a pointer to some element within stack. * So after 2nd insn, the register R1 has type PTR_TO_STACK * (and -20 constant is saved for further stack bounds checking). * Meaning that this reg is a pointer to stack plus known immediate constant. * * Most of the time the registers have UNKNOWN_VALUE type, which * means the register has some value, but it's not a valid pointer. * (like pointer plus pointer becomes UNKNOWN_VALUE type) * * When verifier sees load or store instructions the type of base register * can be: PTR_TO_MAP_VALUE, PTR_TO_CTX, FRAME_PTR. These are three pointer * types recognized by check_mem_access() function. * * PTR_TO_MAP_VALUE means that this register is pointing to 'map element value' * and the range of [ptr, ptr + map's value_size) is accessible. * * registers used to pass values to function calls are checked against * function argument constraints. * * ARG_PTR_TO_MAP_KEY is one of such argument constraints. * It means that the register type passed to this function must be * PTR_TO_STACK and it will be used inside the function as * 'pointer to map element key' * * For example the argument constraints for bpf_map_lookup_elem(): * .ret_type = RET_PTR_TO_MAP_VALUE_OR_NULL, * .arg1_type = ARG_CONST_MAP_PTR, * .arg2_type = ARG_PTR_TO_MAP_KEY, * * ret_type says that this function returns 'pointer to map elem value or null' * function expects 1st argument to be a const pointer to 'struct bpf_map' and * 2nd argument should be a pointer to stack, which will be used inside * the helper function as a pointer to map element key. * * On the kernel side the helper function looks like: * u64 bpf_map_lookup_elem(u64 r1, u64 r2, u64 r3, u64 r4, u64 r5) * { * struct bpf_map *map = (struct bpf_map *) (unsigned long) r1; * void *key = (void *) (unsigned long) r2; * void *value; * * here kernel can access 'key' and 'map' pointers safely, knowing that * [key, key + map->key_size) bytes are valid and were initialized on * the stack of eBPF program. * } * * Corresponding eBPF program may look like: * BPF_MOV64_REG(BPF_REG_2, BPF_REG_10), // after this insn R2 type is FRAME_PTR * BPF_ALU64_IMM(BPF_ADD, BPF_REG_2, -4), // after this insn R2 type is PTR_TO_STACK * BPF_LD_MAP_FD(BPF_REG_1, map_fd), // after this insn R1 type is CONST_PTR_TO_MAP * BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, BPF_FUNC_map_lookup_elem), * here verifier looks at prototype of map_lookup_elem() and sees: * .arg1_type == ARG_CONST_MAP_PTR and R1->type == CONST_PTR_TO_MAP, which is ok, * Now verifier knows that this map has key of R1->map_ptr->key_size bytes * * Then .arg2_type == ARG_PTR_TO_MAP_KEY and R2->type == PTR_TO_STACK, ok so far, * Now verifier checks that [R2, R2 + map's key_size) are within stack limits * and were initialized prior to this call. * If it's ok, then verifier allows this BPF_CALL insn and looks at * .ret_type which is RET_PTR_TO_MAP_VALUE_OR_NULL, so it sets * R0->type = PTR_TO_MAP_VALUE_OR_NULL which means bpf_map_lookup_elem() function * returns ether pointer to map value or NULL. * * When type PTR_TO_MAP_VALUE_OR_NULL passes through 'if (reg != 0) goto +off' * insn, the register holding that pointer in the true branch changes state to * PTR_TO_MAP_VALUE and the same register changes state to CONST_IMM in the false * branch. See check_cond_jmp_op(). * * After the call R0 is set to return type of the function and registers R1-R5 * are set to NOT_INIT to indicate that they are no longer readable. */ /* verifier_state + insn_idx are pushed to stack when branch is encountered */ struct bpf_verifier_stack_elem { /* verifer state is 'st' * before processing instruction 'insn_idx' * and after processing instruction 'prev_insn_idx' */ struct bpf_verifier_state st; int insn_idx; int prev_insn_idx; struct bpf_verifier_stack_elem *next; }; #define BPF_COMPLEXITY_LIMIT_INSNS 65536 #define BPF_COMPLEXITY_LIMIT_STACK 1024 #define BPF_MAP_PTR_POISON ((void *)0xeB9F + POISON_POINTER_DELTA) struct bpf_call_arg_meta { struct bpf_map *map_ptr; bool raw_mode; bool pkt_access; int regno; int access_size; }; /* verbose verifier prints what it's seeing * bpf_check() is called under lock, so no race to access these global vars */ static u32 log_level, log_size, log_len; static char *log_buf; static DEFINE_MUTEX(bpf_verifier_lock); /* log_level controls verbosity level of eBPF verifier. * verbose() is used to dump the verification trace to the log, so the user * can figure out what's wrong with the program */ static __printf(1, 2) void verbose(const char *fmt, ...) { va_list args; if (log_level == 0 || log_len >= log_size - 1) return; va_start(args, fmt); log_len += vscnprintf(log_buf + log_len, log_size - log_len, fmt, args); va_end(args); } /* string representation of 'enum bpf_reg_type' */ static const char * const reg_type_str[] = { [NOT_INIT] = "?", [UNKNOWN_VALUE] = "inv", [PTR_TO_CTX] = "ctx", [CONST_PTR_TO_MAP] = "map_ptr", [PTR_TO_MAP_VALUE] = "map_value", [PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null", [PTR_TO_MAP_VALUE_ADJ] = "map_value_adj", [FRAME_PTR] = "fp", [PTR_TO_STACK] = "fp", [CONST_IMM] = "imm", [PTR_TO_PACKET] = "pkt", [PTR_TO_PACKET_END] = "pkt_end", }; #define __BPF_FUNC_STR_FN(x) [BPF_FUNC_ ## x] = __stringify(bpf_ ## x) static const char * const func_id_str[] = { __BPF_FUNC_MAPPER(__BPF_FUNC_STR_FN) }; #undef __BPF_FUNC_STR_FN static const char *func_id_name(int id) { BUILD_BUG_ON(ARRAY_SIZE(func_id_str) != __BPF_FUNC_MAX_ID); if (id >= 0 && id < __BPF_FUNC_MAX_ID && func_id_str[id]) return func_id_str[id]; else return "unknown"; } static void print_verifier_state(struct bpf_verifier_state *state) { struct bpf_reg_state *reg; enum bpf_reg_type t; int i; for (i = 0; i < MAX_BPF_REG; i++) { reg = &state->regs[i]; t = reg->type; if (t == NOT_INIT) continue; verbose(" R%d=%s", i, reg_type_str[t]); if (t == CONST_IMM || t == PTR_TO_STACK) verbose("%lld", reg->imm); else if (t == PTR_TO_PACKET) verbose("(id=%d,off=%d,r=%d)", reg->id, reg->off, reg->range); else if (t == UNKNOWN_VALUE && reg->imm) verbose("%lld", reg->imm); else if (t == CONST_PTR_TO_MAP || t == PTR_TO_MAP_VALUE || t == PTR_TO_MAP_VALUE_OR_NULL || t == PTR_TO_MAP_VALUE_ADJ) verbose("(ks=%d,vs=%d,id=%u)", reg->map_ptr->key_size, reg->map_ptr->value_size, reg->id); if (reg->min_value != BPF_REGISTER_MIN_RANGE) verbose(",min_value=%lld", (long long)reg->min_value); if (reg->max_value != BPF_REGISTER_MAX_RANGE) verbose(",max_value=%llu", (unsigned long long)reg->max_value); } for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) { if (state->stack_slot_type[i] == STACK_SPILL) verbose(" fp%d=%s", -MAX_BPF_STACK + i, reg_type_str[state->spilled_regs[i / BPF_REG_SIZE].type]); } verbose("\n"); } static const char *const bpf_class_string[] = { [BPF_LD] = "ld", [BPF_LDX] = "ldx", [BPF_ST] = "st", [BPF_STX] = "stx", [BPF_ALU] = "alu", [BPF_JMP] = "jmp", [BPF_RET] = "BUG", [BPF_ALU64] = "alu64", }; static const char *const bpf_alu_string[16] = { [BPF_ADD >> 4] = "+=", [BPF_SUB >> 4] = "-=", [BPF_MUL >> 4] = "*=", [BPF_DIV >> 4] = "/=", [BPF_OR >> 4] = "|=", [BPF_AND >> 4] = "&=", [BPF_LSH >> 4] = "<<=", [BPF_RSH >> 4] = ">>=", [BPF_NEG >> 4] = "neg", [BPF_MOD >> 4] = "%=", [BPF_XOR >> 4] = "^=", [BPF_MOV >> 4] = "=", [BPF_ARSH >> 4] = "s>>=", [BPF_END >> 4] = "endian", }; static const char *const bpf_ldst_string[] = { [BPF_W >> 3] = "u32", [BPF_H >> 3] = "u16", [BPF_B >> 3] = "u8", [BPF_DW >> 3] = "u64", }; static const char *const bpf_jmp_string[16] = { [BPF_JA >> 4] = "jmp", [BPF_JEQ >> 4] = "==", [BPF_JGT >> 4] = ">", [BPF_JGE >> 4] = ">=", [BPF_JSET >> 4] = "&", [BPF_JNE >> 4] = "!=", [BPF_JSGT >> 4] = "s>", [BPF_JSGE >> 4] = "s>=", [BPF_CALL >> 4] = "call", [BPF_EXIT >> 4] = "exit", }; static void print_bpf_insn(struct bpf_insn *insn) { u8 class = BPF_CLASS(insn->code); if (class == BPF_ALU || class == BPF_ALU64) { if (BPF_SRC(insn->code) == BPF_X) verbose("(%02x) %sr%d %s %sr%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->src_reg); else verbose("(%02x) %sr%d %s %s%d\n", insn->code, class == BPF_ALU ? "(u32) " : "", insn->dst_reg, bpf_alu_string[BPF_OP(insn->code) >> 4], class == BPF_ALU ? "(u32) " : "", insn->imm); } else if (class == BPF_STX) { if (BPF_MODE(insn->code) == BPF_MEM) verbose("(%02x) *(%s *)(r%d %+d) = r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else if (BPF_MODE(insn->code) == BPF_XADD) verbose("(%02x) lock *(%s *)(r%d %+d) += r%d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->src_reg); else verbose("BUG_%02x\n", insn->code); } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_st_%02x\n", insn->code); return; } verbose("(%02x) *(%s *)(r%d %+d) = %d\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->dst_reg, insn->off, insn->imm); } else if (class == BPF_LDX) { if (BPF_MODE(insn->code) != BPF_MEM) { verbose("BUG_ldx_%02x\n", insn->code); return; } verbose("(%02x) r%d = *(%s *)(r%d %+d)\n", insn->code, insn->dst_reg, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->off); } else if (class == BPF_LD) { if (BPF_MODE(insn->code) == BPF_ABS) { verbose("(%02x) r0 = *(%s *)skb[%d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->imm); } else if (BPF_MODE(insn->code) == BPF_IND) { verbose("(%02x) r0 = *(%s *)skb[r%d + %d]\n", insn->code, bpf_ldst_string[BPF_SIZE(insn->code) >> 3], insn->src_reg, insn->imm); } else if (BPF_MODE(insn->code) == BPF_IMM) { verbose("(%02x) r%d = 0x%x\n", insn->code, insn->dst_reg, insn->imm); } else { verbose("BUG_ld_%02x\n", insn->code); return; } } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { verbose("(%02x) call %s#%d\n", insn->code, func_id_name(insn->imm), insn->imm); } else if (insn->code == (BPF_JMP | BPF_JA)) { verbose("(%02x) goto pc%+d\n", insn->code, insn->off); } else if (insn->code == (BPF_JMP | BPF_EXIT)) { verbose("(%02x) exit\n", insn->code); } else if (BPF_SRC(insn->code) == BPF_X) { verbose("(%02x) if r%d %s r%d goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->src_reg, insn->off); } else { verbose("(%02x) if r%d %s 0x%x goto pc%+d\n", insn->code, insn->dst_reg, bpf_jmp_string[BPF_OP(insn->code) >> 4], insn->imm, insn->off); } } else { verbose("(%02x) %s\n", insn->code, bpf_class_string[class]); } } static int pop_stack(struct bpf_verifier_env *env, int *prev_insn_idx) { struct bpf_verifier_stack_elem *elem; int insn_idx; if (env->head == NULL) return -1; memcpy(&env->cur_state, &env->head->st, sizeof(env->cur_state)); insn_idx = env->head->insn_idx; if (prev_insn_idx) *prev_insn_idx = env->head->prev_insn_idx; elem = env->head->next; kfree(env->head); env->head = elem; env->stack_size--; return insn_idx; } static struct bpf_verifier_state *push_stack(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { struct bpf_verifier_stack_elem *elem; elem = kmalloc(sizeof(struct bpf_verifier_stack_elem), GFP_KERNEL); if (!elem) goto err; memcpy(&elem->st, &env->cur_state, sizeof(env->cur_state)); elem->insn_idx = insn_idx; elem->prev_insn_idx = prev_insn_idx; elem->next = env->head; env->head = elem; env->stack_size++; if (env->stack_size > BPF_COMPLEXITY_LIMIT_STACK) { verbose("BPF program is too complex\n"); goto err; } return &elem->st; err: /* pop all elements and return */ while (pop_stack(env, NULL) >= 0); return NULL; } #define CALLER_SAVED_REGS 6 static const int caller_saved[CALLER_SAVED_REGS] = { BPF_REG_0, BPF_REG_1, BPF_REG_2, BPF_REG_3, BPF_REG_4, BPF_REG_5 }; static void init_reg_state(struct bpf_reg_state *regs) { int i; for (i = 0; i < MAX_BPF_REG; i++) { regs[i].type = NOT_INIT; regs[i].imm = 0; regs[i].min_value = BPF_REGISTER_MIN_RANGE; regs[i].max_value = BPF_REGISTER_MAX_RANGE; } /* frame pointer */ regs[BPF_REG_FP].type = FRAME_PTR; /* 1st arg to a function */ regs[BPF_REG_1].type = PTR_TO_CTX; } static void __mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno) { regs[regno].type = UNKNOWN_VALUE; regs[regno].id = 0; regs[regno].imm = 0; } static void mark_reg_unknown_value(struct bpf_reg_state *regs, u32 regno) { BUG_ON(regno >= MAX_BPF_REG); __mark_reg_unknown_value(regs, regno); } static void reset_reg_range_values(struct bpf_reg_state *regs, u32 regno) { regs[regno].min_value = BPF_REGISTER_MIN_RANGE; regs[regno].max_value = BPF_REGISTER_MAX_RANGE; } static void mark_reg_unknown_value_and_range(struct bpf_reg_state *regs, u32 regno) { mark_reg_unknown_value(regs, regno); reset_reg_range_values(regs, regno); } enum reg_arg_type { SRC_OP, /* register is used as source operand */ DST_OP, /* register is used as destination operand */ DST_OP_NO_MARK /* same as above, check only, don't mark */ }; static int check_reg_arg(struct bpf_reg_state *regs, u32 regno, enum reg_arg_type t) { if (regno >= MAX_BPF_REG) { verbose("R%d is invalid\n", regno); return -EINVAL; } if (t == SRC_OP) { /* check whether register used as source operand can be read */ if (regs[regno].type == NOT_INIT) { verbose("R%d !read_ok\n", regno); return -EACCES; } } else { /* check whether register used as dest operand can be written to */ if (regno == BPF_REG_FP) { verbose("frame pointer is read only\n"); return -EACCES; } if (t == DST_OP) mark_reg_unknown_value(regs, regno); } return 0; } static int bpf_size_to_bytes(int bpf_size) { if (bpf_size == BPF_W) return 4; else if (bpf_size == BPF_H) return 2; else if (bpf_size == BPF_B) return 1; else if (bpf_size == BPF_DW) return 8; else return -EINVAL; } static bool is_spillable_regtype(enum bpf_reg_type type) { switch (type) { case PTR_TO_MAP_VALUE: case PTR_TO_MAP_VALUE_OR_NULL: case PTR_TO_MAP_VALUE_ADJ: case PTR_TO_STACK: case PTR_TO_CTX: case PTR_TO_PACKET: case PTR_TO_PACKET_END: case FRAME_PTR: case CONST_PTR_TO_MAP: return true; default: return false; } } /* check_stack_read/write functions track spill/fill of registers, * stack boundary and alignment are checked in check_mem_access() */ static int check_stack_write(struct bpf_verifier_state *state, int off, int size, int value_regno) { int i; /* caller checked that off % size == 0 and -MAX_BPF_STACK <= off < 0, * so it's aligned access and [off, off + size) are within stack limits */ if (value_regno >= 0 && is_spillable_regtype(state->regs[value_regno].type)) { /* register containing pointer is being spilled into stack */ if (size != BPF_REG_SIZE) { verbose("invalid size of register spill\n"); return -EACCES; } /* save register state */ state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] = state->regs[value_regno]; for (i = 0; i < BPF_REG_SIZE; i++) state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_SPILL; } else { /* regular write of data into stack */ state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE] = (struct bpf_reg_state) {}; for (i = 0; i < size; i++) state->stack_slot_type[MAX_BPF_STACK + off + i] = STACK_MISC; } return 0; } static int check_stack_read(struct bpf_verifier_state *state, int off, int size, int value_regno) { u8 *slot_type; int i; slot_type = &state->stack_slot_type[MAX_BPF_STACK + off]; if (slot_type[0] == STACK_SPILL) { if (size != BPF_REG_SIZE) { verbose("invalid size of register spill\n"); return -EACCES; } for (i = 1; i < BPF_REG_SIZE; i++) { if (slot_type[i] != STACK_SPILL) { verbose("corrupted spill memory\n"); return -EACCES; } } if (value_regno >= 0) /* restore register state from stack */ state->regs[value_regno] = state->spilled_regs[(MAX_BPF_STACK + off) / BPF_REG_SIZE]; return 0; } else { for (i = 0; i < size; i++) { if (slot_type[i] != STACK_MISC) { verbose("invalid read from stack off %d+%d size %d\n", off, i, size); return -EACCES; } } if (value_regno >= 0) /* have read misc data from the stack */ mark_reg_unknown_value_and_range(state->regs, value_regno); return 0; } } /* check read/write into map element returned by bpf_map_lookup_elem() */ static int check_map_access(struct bpf_verifier_env *env, u32 regno, int off, int size) { struct bpf_map *map = env->cur_state.regs[regno].map_ptr; if (off < 0 || size <= 0 || off + size > map->value_size) { verbose("invalid access to map value, value_size=%d off=%d size=%d\n", map->value_size, off, size); return -EACCES; } return 0; } /* check read/write into an adjusted map element */ static int check_map_access_adj(struct bpf_verifier_env *env, u32 regno, int off, int size) { struct bpf_verifier_state *state = &env->cur_state; struct bpf_reg_state *reg = &state->regs[regno]; int err; /* We adjusted the register to this map value, so we * need to change off and size to min_value and max_value * respectively to make sure our theoretical access will be * safe. */ if (log_level) print_verifier_state(state); env->varlen_map_value_access = true; /* The minimum value is only important with signed * comparisons where we can't assume the floor of a * value is 0. If we are using signed variables for our * index'es we need to make sure that whatever we use * will have a set floor within our range. */ if (reg->min_value < 0) { verbose("R%d min value is negative, either use unsigned index or do a if (index >=0) check.\n", regno); return -EACCES; } err = check_map_access(env, regno, reg->min_value + off, size); if (err) { verbose("R%d min value is outside of the array range\n", regno); return err; } /* If we haven't set a max value then we need to bail * since we can't be sure we won't do bad things. */ if (reg->max_value == BPF_REGISTER_MAX_RANGE) { verbose("R%d unbounded memory access, make sure to bounds check any array access into a map\n", regno); return -EACCES; } return check_map_access(env, regno, reg->max_value + off, size); } #define MAX_PACKET_OFF 0xffff static bool may_access_direct_pkt_data(struct bpf_verifier_env *env, const struct bpf_call_arg_meta *meta, enum bpf_access_type t) { switch (env->prog->type) { case BPF_PROG_TYPE_LWT_IN: case BPF_PROG_TYPE_LWT_OUT: /* dst_input() and dst_output() can't write for now */ if (t == BPF_WRITE) return false; /* fallthrough */ case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: case BPF_PROG_TYPE_XDP: case BPF_PROG_TYPE_LWT_XMIT: if (meta) return meta->pkt_access; env->seen_direct_write = true; return true; default: return false; } } static int check_packet_access(struct bpf_verifier_env *env, u32 regno, int off, int size) { struct bpf_reg_state *regs = env->cur_state.regs; struct bpf_reg_state *reg = &regs[regno]; off += reg->off; if (off < 0 || size <= 0 || off + size > reg->range) { verbose("invalid access to packet, off=%d size=%d, R%d(id=%d,off=%d,r=%d)\n", off, size, regno, reg->id, reg->off, reg->range); return -EACCES; } return 0; } /* check access to 'struct bpf_context' fields */ static int check_ctx_access(struct bpf_verifier_env *env, int off, int size, enum bpf_access_type t, enum bpf_reg_type *reg_type) { /* for analyzer ctx accesses are already validated and converted */ if (env->analyzer_ops) return 0; if (env->prog->aux->ops->is_valid_access && env->prog->aux->ops->is_valid_access(off, size, t, reg_type)) { /* remember the offset of last byte accessed in ctx */ if (env->prog->aux->max_ctx_offset < off + size) env->prog->aux->max_ctx_offset = off + size; return 0; } verbose("invalid bpf_context access off=%d size=%d\n", off, size); return -EACCES; } static bool is_pointer_value(struct bpf_verifier_env *env, int regno) { if (env->allow_ptr_leaks) return false; switch (env->cur_state.regs[regno].type) { case UNKNOWN_VALUE: case CONST_IMM: return false; default: return true; } } static int check_pkt_ptr_alignment(const struct bpf_reg_state *reg, int off, int size) { if (reg->id && size != 1) { verbose("Unknown alignment. Only byte-sized access allowed in packet access.\n"); return -EACCES; } /* skb->data is NET_IP_ALIGN-ed */ if ((NET_IP_ALIGN + reg->off + off) % size != 0) { verbose("misaligned packet access off %d+%d+%d size %d\n", NET_IP_ALIGN, reg->off, off, size); return -EACCES; } return 0; } static int check_val_ptr_alignment(const struct bpf_reg_state *reg, int size) { if (size != 1) { verbose("Unknown alignment. Only byte-sized access allowed in value access.\n"); return -EACCES; } return 0; } static int check_ptr_alignment(const struct bpf_reg_state *reg, int off, int size) { switch (reg->type) { case PTR_TO_PACKET: return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ? 0 : check_pkt_ptr_alignment(reg, off, size); case PTR_TO_MAP_VALUE_ADJ: return IS_ENABLED(CONFIG_HAVE_EFFICIENT_UNALIGNED_ACCESS) ? 0 : check_val_ptr_alignment(reg, size); default: if (off % size != 0) { verbose("misaligned access off %d size %d\n", off, size); return -EACCES; } return 0; } } /* check whether memory at (regno + off) is accessible for t = (read | write) * if t==write, value_regno is a register which value is stored into memory * if t==read, value_regno is a register which will receive the value from memory * if t==write && value_regno==-1, some unknown value is stored into memory * if t==read && value_regno==-1, don't care what we read from memory */ static int check_mem_access(struct bpf_verifier_env *env, u32 regno, int off, int bpf_size, enum bpf_access_type t, int value_regno) { struct bpf_verifier_state *state = &env->cur_state; struct bpf_reg_state *reg = &state->regs[regno]; int size, err = 0; if (reg->type == PTR_TO_STACK) off += reg->imm; size = bpf_size_to_bytes(bpf_size); if (size < 0) return size; err = check_ptr_alignment(reg, off, size); if (err) return err; if (reg->type == PTR_TO_MAP_VALUE || reg->type == PTR_TO_MAP_VALUE_ADJ) { if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose("R%d leaks addr into map\n", value_regno); return -EACCES; } if (reg->type == PTR_TO_MAP_VALUE_ADJ) err = check_map_access_adj(env, regno, off, size); else err = check_map_access(env, regno, off, size); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown_value_and_range(state->regs, value_regno); } else if (reg->type == PTR_TO_CTX) { enum bpf_reg_type reg_type = UNKNOWN_VALUE; if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose("R%d leaks addr into ctx\n", value_regno); return -EACCES; } err = check_ctx_access(env, off, size, t, &reg_type); if (!err && t == BPF_READ && value_regno >= 0) { mark_reg_unknown_value_and_range(state->regs, value_regno); /* note that reg.[id|off|range] == 0 */ state->regs[value_regno].type = reg_type; } } else if (reg->type == FRAME_PTR || reg->type == PTR_TO_STACK) { if (off >= 0 || off < -MAX_BPF_STACK) { verbose("invalid stack off=%d size=%d\n", off, size); return -EACCES; } if (t == BPF_WRITE) { if (!env->allow_ptr_leaks && state->stack_slot_type[MAX_BPF_STACK + off] == STACK_SPILL && size != BPF_REG_SIZE) { verbose("attempt to corrupt spilled pointer on stack\n"); return -EACCES; } err = check_stack_write(state, off, size, value_regno); } else { err = check_stack_read(state, off, size, value_regno); } } else if (state->regs[regno].type == PTR_TO_PACKET) { if (t == BPF_WRITE && !may_access_direct_pkt_data(env, NULL, t)) { verbose("cannot write into packet\n"); return -EACCES; } if (t == BPF_WRITE && value_regno >= 0 && is_pointer_value(env, value_regno)) { verbose("R%d leaks addr into packet\n", value_regno); return -EACCES; } err = check_packet_access(env, regno, off, size); if (!err && t == BPF_READ && value_regno >= 0) mark_reg_unknown_value_and_range(state->regs, value_regno); } else { verbose("R%d invalid mem access '%s'\n", regno, reg_type_str[reg->type]); return -EACCES; } if (!err && size <= 2 && value_regno >= 0 && env->allow_ptr_leaks && state->regs[value_regno].type == UNKNOWN_VALUE) { /* 1 or 2 byte load zero-extends, determine the number of * zero upper bits. Not doing it fo 4 byte load, since * such values cannot be added to ptr_to_packet anyway. */ state->regs[value_regno].imm = 64 - size * 8; } return err; } static int check_xadd(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs; int err; if ((BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) || insn->imm != 0) { verbose("BPF_XADD uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; /* check whether atomic_add can read the memory */ err = check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, -1); if (err) return err; /* check whether atomic_add can write into the same memory */ return check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); } /* when register 'regno' is passed into function that will read 'access_size' * bytes from that pointer, make sure that it's within stack boundary * and all elements of stack are initialized */ static int check_stack_boundary(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_verifier_state *state = &env->cur_state; struct bpf_reg_state *regs = state->regs; int off, i; if (regs[regno].type != PTR_TO_STACK) { if (zero_size_allowed && access_size == 0 && regs[regno].type == CONST_IMM && regs[regno].imm == 0) return 0; verbose("R%d type=%s expected=%s\n", regno, reg_type_str[regs[regno].type], reg_type_str[PTR_TO_STACK]); return -EACCES; } off = regs[regno].imm; if (off >= 0 || off < -MAX_BPF_STACK || off + access_size > 0 || access_size <= 0) { verbose("invalid stack type R%d off=%d access_size=%d\n", regno, off, access_size); return -EACCES; } if (meta && meta->raw_mode) { meta->access_size = access_size; meta->regno = regno; return 0; } for (i = 0; i < access_size; i++) { if (state->stack_slot_type[MAX_BPF_STACK + off + i] != STACK_MISC) { verbose("invalid indirect read from stack off %d+%d size %d\n", off, i, access_size); return -EACCES; } } return 0; } static int check_helper_mem_access(struct bpf_verifier_env *env, int regno, int access_size, bool zero_size_allowed, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = env->cur_state.regs; switch (regs[regno].type) { case PTR_TO_PACKET: return check_packet_access(env, regno, 0, access_size); case PTR_TO_MAP_VALUE: return check_map_access(env, regno, 0, access_size); case PTR_TO_MAP_VALUE_ADJ: return check_map_access_adj(env, regno, 0, access_size); default: /* const_imm|ptr_to_stack or invalid ptr */ return check_stack_boundary(env, regno, access_size, zero_size_allowed, meta); } } static int check_func_arg(struct bpf_verifier_env *env, u32 regno, enum bpf_arg_type arg_type, struct bpf_call_arg_meta *meta) { struct bpf_reg_state *regs = env->cur_state.regs, *reg = &regs[regno]; enum bpf_reg_type expected_type, type = reg->type; int err = 0; if (arg_type == ARG_DONTCARE) return 0; if (type == NOT_INIT) { verbose("R%d !read_ok\n", regno); return -EACCES; } if (arg_type == ARG_ANYTHING) { if (is_pointer_value(env, regno)) { verbose("R%d leaks addr into helper function\n", regno); return -EACCES; } return 0; } if (type == PTR_TO_PACKET && !may_access_direct_pkt_data(env, meta, BPF_READ)) { verbose("helper access to the packet is not allowed\n"); return -EACCES; } if (arg_type == ARG_PTR_TO_MAP_KEY || arg_type == ARG_PTR_TO_MAP_VALUE) { expected_type = PTR_TO_STACK; if (type != PTR_TO_PACKET && type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { expected_type = CONST_IMM; /* One exception. Allow UNKNOWN_VALUE registers when the * boundaries are known and don't cause unsafe memory accesses */ if (type != UNKNOWN_VALUE && type != expected_type) goto err_type; } else if (arg_type == ARG_CONST_MAP_PTR) { expected_type = CONST_PTR_TO_MAP; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_CTX) { expected_type = PTR_TO_CTX; if (type != expected_type) goto err_type; } else if (arg_type == ARG_PTR_TO_MEM || arg_type == ARG_PTR_TO_UNINIT_MEM) { expected_type = PTR_TO_STACK; /* One exception here. In case function allows for NULL to be * passed in as argument, it's a CONST_IMM type. Final test * happens during stack boundary checking. */ if (type == CONST_IMM && reg->imm == 0) /* final test in check_stack_boundary() */; else if (type != PTR_TO_PACKET && type != PTR_TO_MAP_VALUE && type != PTR_TO_MAP_VALUE_ADJ && type != expected_type) goto err_type; meta->raw_mode = arg_type == ARG_PTR_TO_UNINIT_MEM; } else { verbose("unsupported arg_type %d\n", arg_type); return -EFAULT; } if (arg_type == ARG_CONST_MAP_PTR) { /* bpf_map_xxx(map_ptr) call: remember that map_ptr */ meta->map_ptr = reg->map_ptr; } else if (arg_type == ARG_PTR_TO_MAP_KEY) { /* bpf_map_xxx(..., map_ptr, ..., key) call: * check that [key, key + map->key_size) are within * stack limits and initialized */ if (!meta->map_ptr) { /* in function declaration map_ptr must come before * map_key, so that it's verified and known before * we have to check map_key here. Otherwise it means * that kernel subsystem misconfigured verifier */ verbose("invalid map_ptr to access map->key\n"); return -EACCES; } if (type == PTR_TO_PACKET) err = check_packet_access(env, regno, 0, meta->map_ptr->key_size); else err = check_stack_boundary(env, regno, meta->map_ptr->key_size, false, NULL); } else if (arg_type == ARG_PTR_TO_MAP_VALUE) { /* bpf_map_xxx(..., map_ptr, ..., value) call: * check [value, value + map->value_size) validity */ if (!meta->map_ptr) { /* kernel subsystem misconfigured verifier */ verbose("invalid map_ptr to access map->value\n"); return -EACCES; } if (type == PTR_TO_PACKET) err = check_packet_access(env, regno, 0, meta->map_ptr->value_size); else err = check_stack_boundary(env, regno, meta->map_ptr->value_size, false, NULL); } else if (arg_type == ARG_CONST_SIZE || arg_type == ARG_CONST_SIZE_OR_ZERO) { bool zero_size_allowed = (arg_type == ARG_CONST_SIZE_OR_ZERO); /* bpf_xxx(..., buf, len) call will access 'len' bytes * from stack pointer 'buf'. Check it * note: regno == len, regno - 1 == buf */ if (regno == 0) { /* kernel subsystem misconfigured verifier */ verbose("ARG_CONST_SIZE cannot be first argument\n"); return -EACCES; } /* If the register is UNKNOWN_VALUE, the access check happens * using its boundaries. Otherwise, just use its imm */ if (type == UNKNOWN_VALUE) { /* For unprivileged variable accesses, disable raw * mode so that the program is required to * initialize all the memory that the helper could * just partially fill up. */ meta = NULL; if (reg->min_value < 0) { verbose("R%d min value is negative, either use unsigned or 'var &= const'\n", regno); return -EACCES; } if (reg->min_value == 0) { err = check_helper_mem_access(env, regno - 1, 0, zero_size_allowed, meta); if (err) return err; } if (reg->max_value == BPF_REGISTER_MAX_RANGE) { verbose("R%d unbounded memory access, use 'var &= const' or 'if (var < const)'\n", regno); return -EACCES; } err = check_helper_mem_access(env, regno - 1, reg->max_value, zero_size_allowed, meta); if (err) return err; } else { /* register is CONST_IMM */ err = check_helper_mem_access(env, regno - 1, reg->imm, zero_size_allowed, meta); } } return err; err_type: verbose("R%d type=%s expected=%s\n", regno, reg_type_str[type], reg_type_str[expected_type]); return -EACCES; } static int check_map_func_compatibility(struct bpf_map *map, int func_id) { if (!map) return 0; /* We need a two way check, first is from map perspective ... */ switch (map->map_type) { case BPF_MAP_TYPE_PROG_ARRAY: if (func_id != BPF_FUNC_tail_call) goto error; break; case BPF_MAP_TYPE_PERF_EVENT_ARRAY: if (func_id != BPF_FUNC_perf_event_read && func_id != BPF_FUNC_perf_event_output) goto error; break; case BPF_MAP_TYPE_STACK_TRACE: if (func_id != BPF_FUNC_get_stackid) goto error; break; case BPF_MAP_TYPE_CGROUP_ARRAY: if (func_id != BPF_FUNC_skb_under_cgroup && func_id != BPF_FUNC_current_task_under_cgroup) goto error; break; case BPF_MAP_TYPE_ARRAY_OF_MAPS: case BPF_MAP_TYPE_HASH_OF_MAPS: if (func_id != BPF_FUNC_map_lookup_elem) goto error; default: break; } /* ... and second from the function itself. */ switch (func_id) { case BPF_FUNC_tail_call: if (map->map_type != BPF_MAP_TYPE_PROG_ARRAY) goto error; break; case BPF_FUNC_perf_event_read: case BPF_FUNC_perf_event_output: if (map->map_type != BPF_MAP_TYPE_PERF_EVENT_ARRAY) goto error; break; case BPF_FUNC_get_stackid: if (map->map_type != BPF_MAP_TYPE_STACK_TRACE) goto error; break; case BPF_FUNC_current_task_under_cgroup: case BPF_FUNC_skb_under_cgroup: if (map->map_type != BPF_MAP_TYPE_CGROUP_ARRAY) goto error; break; default: break; } return 0; error: verbose("cannot pass map_type %d into func %s#%d\n", map->map_type, func_id_name(func_id), func_id); return -EINVAL; } static int check_raw_mode(const struct bpf_func_proto *fn) { int count = 0; if (fn->arg1_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg2_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg3_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg4_type == ARG_PTR_TO_UNINIT_MEM) count++; if (fn->arg5_type == ARG_PTR_TO_UNINIT_MEM) count++; return count > 1 ? -EINVAL : 0; } static void clear_all_pkt_pointers(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = &env->cur_state; struct bpf_reg_state *regs = state->regs, *reg; int i; for (i = 0; i < MAX_BPF_REG; i++) if (regs[i].type == PTR_TO_PACKET || regs[i].type == PTR_TO_PACKET_END) mark_reg_unknown_value(regs, i); for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) { if (state->stack_slot_type[i] != STACK_SPILL) continue; reg = &state->spilled_regs[i / BPF_REG_SIZE]; if (reg->type != PTR_TO_PACKET && reg->type != PTR_TO_PACKET_END) continue; reg->type = UNKNOWN_VALUE; reg->imm = 0; } } static int check_call(struct bpf_verifier_env *env, int func_id, int insn_idx) { struct bpf_verifier_state *state = &env->cur_state; const struct bpf_func_proto *fn = NULL; struct bpf_reg_state *regs = state->regs; struct bpf_reg_state *reg; struct bpf_call_arg_meta meta; bool changes_data; int i, err; /* find function prototype */ if (func_id < 0 || func_id >= __BPF_FUNC_MAX_ID) { verbose("invalid func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } if (env->prog->aux->ops->get_func_proto) fn = env->prog->aux->ops->get_func_proto(func_id); if (!fn) { verbose("unknown func %s#%d\n", func_id_name(func_id), func_id); return -EINVAL; } /* eBPF programs must be GPL compatible to use GPL-ed functions */ if (!env->prog->gpl_compatible && fn->gpl_only) { verbose("cannot call GPL only function from proprietary program\n"); return -EINVAL; } changes_data = bpf_helper_changes_pkt_data(fn->func); memset(&meta, 0, sizeof(meta)); meta.pkt_access = fn->pkt_access; /* We only support one arg being in raw mode at the moment, which * is sufficient for the helper functions we have right now. */ err = check_raw_mode(fn); if (err) { verbose("kernel subsystem misconfigured func %s#%d\n", func_id_name(func_id), func_id); return err; } /* check args */ err = check_func_arg(env, BPF_REG_1, fn->arg1_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_2, fn->arg2_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_3, fn->arg3_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_4, fn->arg4_type, &meta); if (err) return err; err = check_func_arg(env, BPF_REG_5, fn->arg5_type, &meta); if (err) return err; /* Mark slots with STACK_MISC in case of raw mode, stack offset * is inferred from register state. */ for (i = 0; i < meta.access_size; i++) { err = check_mem_access(env, meta.regno, i, BPF_B, BPF_WRITE, -1); if (err) return err; } /* reset caller saved regs */ for (i = 0; i < CALLER_SAVED_REGS; i++) { reg = regs + caller_saved[i]; reg->type = NOT_INIT; reg->imm = 0; } /* update return register */ if (fn->ret_type == RET_INTEGER) { regs[BPF_REG_0].type = UNKNOWN_VALUE; } else if (fn->ret_type == RET_VOID) { regs[BPF_REG_0].type = NOT_INIT; } else if (fn->ret_type == RET_PTR_TO_MAP_VALUE_OR_NULL) { struct bpf_insn_aux_data *insn_aux; regs[BPF_REG_0].type = PTR_TO_MAP_VALUE_OR_NULL; regs[BPF_REG_0].max_value = regs[BPF_REG_0].min_value = 0; /* remember map_ptr, so that check_map_access() * can check 'value_size' boundary of memory access * to map element returned from bpf_map_lookup_elem() */ if (meta.map_ptr == NULL) { verbose("kernel subsystem misconfigured verifier\n"); return -EINVAL; } regs[BPF_REG_0].map_ptr = meta.map_ptr; regs[BPF_REG_0].id = ++env->id_gen; insn_aux = &env->insn_aux_data[insn_idx]; if (!insn_aux->map_ptr) insn_aux->map_ptr = meta.map_ptr; else if (insn_aux->map_ptr != meta.map_ptr) insn_aux->map_ptr = BPF_MAP_PTR_POISON; } else { verbose("unknown return type %d of func %s#%d\n", fn->ret_type, func_id_name(func_id), func_id); return -EINVAL; } err = check_map_func_compatibility(meta.map_ptr, func_id); if (err) return err; if (changes_data) clear_all_pkt_pointers(env); return 0; } static int check_packet_ptr_add(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs; struct bpf_reg_state *dst_reg = &regs[insn->dst_reg]; struct bpf_reg_state *src_reg = &regs[insn->src_reg]; struct bpf_reg_state tmp_reg; s32 imm; if (BPF_SRC(insn->code) == BPF_K) { /* pkt_ptr += imm */ imm = insn->imm; add_imm: if (imm < 0) { verbose("addition of negative constant to packet pointer is not allowed\n"); return -EACCES; } if (imm >= MAX_PACKET_OFF || imm + dst_reg->off >= MAX_PACKET_OFF) { verbose("constant %d is too large to add to packet pointer\n", imm); return -EACCES; } /* a constant was added to pkt_ptr. * Remember it while keeping the same 'id' */ dst_reg->off += imm; } else { if (src_reg->type == PTR_TO_PACKET) { /* R6=pkt(id=0,off=0,r=62) R7=imm22; r7 += r6 */ tmp_reg = *dst_reg; /* save r7 state */ *dst_reg = *src_reg; /* copy pkt_ptr state r6 into r7 */ src_reg = &tmp_reg; /* pretend it's src_reg state */ /* if the checks below reject it, the copy won't matter, * since we're rejecting the whole program. If all ok, * then imm22 state will be added to r7 * and r7 will be pkt(id=0,off=22,r=62) while * r6 will stay as pkt(id=0,off=0,r=62) */ } if (src_reg->type == CONST_IMM) { /* pkt_ptr += reg where reg is known constant */ imm = src_reg->imm; goto add_imm; } /* disallow pkt_ptr += reg * if reg is not uknown_value with guaranteed zero upper bits * otherwise pkt_ptr may overflow and addition will become * subtraction which is not allowed */ if (src_reg->type != UNKNOWN_VALUE) { verbose("cannot add '%s' to ptr_to_packet\n", reg_type_str[src_reg->type]); return -EACCES; } if (src_reg->imm < 48) { verbose("cannot add integer value with %lld upper zero bits to ptr_to_packet\n", src_reg->imm); return -EACCES; } /* dst_reg stays as pkt_ptr type and since some positive * integer value was added to the pointer, increment its 'id' */ dst_reg->id = ++env->id_gen; /* something was added to pkt_ptr, set range and off to zero */ dst_reg->off = 0; dst_reg->range = 0; } return 0; } static int evaluate_reg_alu(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs; struct bpf_reg_state *dst_reg = &regs[insn->dst_reg]; u8 opcode = BPF_OP(insn->code); s64 imm_log2; /* for type == UNKNOWN_VALUE: * imm > 0 -> number of zero upper bits * imm == 0 -> don't track which is the same as all bits can be non-zero */ if (BPF_SRC(insn->code) == BPF_X) { struct bpf_reg_state *src_reg = &regs[insn->src_reg]; if (src_reg->type == UNKNOWN_VALUE && src_reg->imm > 0 && dst_reg->imm && opcode == BPF_ADD) { /* dreg += sreg * where both have zero upper bits. Adding them * can only result making one more bit non-zero * in the larger value. * Ex. 0xffff (imm=48) + 1 (imm=63) = 0x10000 (imm=47) * 0xffff (imm=48) + 0xffff = 0x1fffe (imm=47) */ dst_reg->imm = min(dst_reg->imm, src_reg->imm); dst_reg->imm--; return 0; } if (src_reg->type == CONST_IMM && src_reg->imm > 0 && dst_reg->imm && opcode == BPF_ADD) { /* dreg += sreg * where dreg has zero upper bits and sreg is const. * Adding them can only result making one more bit * non-zero in the larger value. */ imm_log2 = __ilog2_u64((long long)src_reg->imm); dst_reg->imm = min(dst_reg->imm, 63 - imm_log2); dst_reg->imm--; return 0; } /* all other cases non supported yet, just mark dst_reg */ dst_reg->imm = 0; return 0; } /* sign extend 32-bit imm into 64-bit to make sure that * negative values occupy bit 63. Note ilog2() would have * been incorrect, since sizeof(insn->imm) == 4 */ imm_log2 = __ilog2_u64((long long)insn->imm); if (dst_reg->imm && opcode == BPF_LSH) { /* reg <<= imm * if reg was a result of 2 byte load, then its imm == 48 * which means that upper 48 bits are zero and shifting this reg * left by 4 would mean that upper 44 bits are still zero */ dst_reg->imm -= insn->imm; } else if (dst_reg->imm && opcode == BPF_MUL) { /* reg *= imm * if multiplying by 14 subtract 4 * This is conservative calculation of upper zero bits. * It's not trying to special case insn->imm == 1 or 0 cases */ dst_reg->imm -= imm_log2 + 1; } else if (opcode == BPF_AND) { /* reg &= imm */ dst_reg->imm = 63 - imm_log2; } else if (dst_reg->imm && opcode == BPF_ADD) { /* reg += imm */ dst_reg->imm = min(dst_reg->imm, 63 - imm_log2); dst_reg->imm--; } else if (opcode == BPF_RSH) { /* reg >>= imm * which means that after right shift, upper bits will be zero * note that verifier already checked that * 0 <= imm < 64 for shift insn */ dst_reg->imm += insn->imm; if (unlikely(dst_reg->imm > 64)) /* some dumb code did: * r2 = *(u32 *)mem; * r2 >>= 32; * and all bits are zero now */ dst_reg->imm = 64; } else { /* all other alu ops, means that we don't know what will * happen to the value, mark it with unknown number of zero bits */ dst_reg->imm = 0; } if (dst_reg->imm < 0) { /* all 64 bits of the register can contain non-zero bits * and such value cannot be added to ptr_to_packet, since it * may overflow, mark it as unknown to avoid further eval */ dst_reg->imm = 0; } return 0; } static int evaluate_reg_imm_alu(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs; struct bpf_reg_state *dst_reg = &regs[insn->dst_reg]; struct bpf_reg_state *src_reg = &regs[insn->src_reg]; u8 opcode = BPF_OP(insn->code); u64 dst_imm = dst_reg->imm; /* dst_reg->type == CONST_IMM here. Simulate execution of insns * containing ALU ops. Don't care about overflow or negative * values, just add/sub/... them; registers are in u64. */ if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_K) { dst_imm += insn->imm; } else if (opcode == BPF_ADD && BPF_SRC(insn->code) == BPF_X && src_reg->type == CONST_IMM) { dst_imm += src_reg->imm; } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_K) { dst_imm -= insn->imm; } else if (opcode == BPF_SUB && BPF_SRC(insn->code) == BPF_X && src_reg->type == CONST_IMM) { dst_imm -= src_reg->imm; } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_K) { dst_imm *= insn->imm; } else if (opcode == BPF_MUL && BPF_SRC(insn->code) == BPF_X && src_reg->type == CONST_IMM) { dst_imm *= src_reg->imm; } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_K) { dst_imm |= insn->imm; } else if (opcode == BPF_OR && BPF_SRC(insn->code) == BPF_X && src_reg->type == CONST_IMM) { dst_imm |= src_reg->imm; } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_K) { dst_imm &= insn->imm; } else if (opcode == BPF_AND && BPF_SRC(insn->code) == BPF_X && src_reg->type == CONST_IMM) { dst_imm &= src_reg->imm; } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_K) { dst_imm >>= insn->imm; } else if (opcode == BPF_RSH && BPF_SRC(insn->code) == BPF_X && src_reg->type == CONST_IMM) { dst_imm >>= src_reg->imm; } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_K) { dst_imm <<= insn->imm; } else if (opcode == BPF_LSH && BPF_SRC(insn->code) == BPF_X && src_reg->type == CONST_IMM) { dst_imm <<= src_reg->imm; } else { mark_reg_unknown_value(regs, insn->dst_reg); goto out; } dst_reg->imm = dst_imm; out: return 0; } static void check_reg_overflow(struct bpf_reg_state *reg) { if (reg->max_value > BPF_REGISTER_MAX_RANGE) reg->max_value = BPF_REGISTER_MAX_RANGE; if (reg->min_value < BPF_REGISTER_MIN_RANGE || reg->min_value > BPF_REGISTER_MAX_RANGE) reg->min_value = BPF_REGISTER_MIN_RANGE; } static void adjust_reg_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg; s64 min_val = BPF_REGISTER_MIN_RANGE; u64 max_val = BPF_REGISTER_MAX_RANGE; u8 opcode = BPF_OP(insn->code); dst_reg = &regs[insn->dst_reg]; if (BPF_SRC(insn->code) == BPF_X) { check_reg_overflow(&regs[insn->src_reg]); min_val = regs[insn->src_reg].min_value; max_val = regs[insn->src_reg].max_value; /* If the source register is a random pointer then the * min_value/max_value values represent the range of the known * accesses into that value, not the actual min/max value of the * register itself. In this case we have to reset the reg range * values so we know it is not safe to look at. */ if (regs[insn->src_reg].type != CONST_IMM && regs[insn->src_reg].type != UNKNOWN_VALUE) { min_val = BPF_REGISTER_MIN_RANGE; max_val = BPF_REGISTER_MAX_RANGE; } } else if (insn->imm < BPF_REGISTER_MAX_RANGE && (s64)insn->imm > BPF_REGISTER_MIN_RANGE) { min_val = max_val = insn->imm; } /* We don't know anything about what was done to this register, mark it * as unknown. */ if (min_val == BPF_REGISTER_MIN_RANGE && max_val == BPF_REGISTER_MAX_RANGE) { reset_reg_range_values(regs, insn->dst_reg); return; } /* If one of our values was at the end of our ranges then we can't just * do our normal operations to the register, we need to set the values * to the min/max since they are undefined. */ if (min_val == BPF_REGISTER_MIN_RANGE) dst_reg->min_value = BPF_REGISTER_MIN_RANGE; if (max_val == BPF_REGISTER_MAX_RANGE) dst_reg->max_value = BPF_REGISTER_MAX_RANGE; switch (opcode) { case BPF_ADD: if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE) dst_reg->min_value += min_val; if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE) dst_reg->max_value += max_val; break; case BPF_SUB: if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE) dst_reg->min_value -= min_val; if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE) dst_reg->max_value -= max_val; break; case BPF_MUL: if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE) dst_reg->min_value *= min_val; if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE) dst_reg->max_value *= max_val; break; case BPF_AND: /* Disallow AND'ing of negative numbers, ain't nobody got time * for that. Otherwise the minimum is 0 and the max is the max * value we could AND against. */ if (min_val < 0) dst_reg->min_value = BPF_REGISTER_MIN_RANGE; else dst_reg->min_value = 0; dst_reg->max_value = max_val; break; case BPF_LSH: /* Gotta have special overflow logic here, if we're shifting * more than MAX_RANGE then just assume we have an invalid * range. */ if (min_val > ilog2(BPF_REGISTER_MAX_RANGE)) dst_reg->min_value = BPF_REGISTER_MIN_RANGE; else if (dst_reg->min_value != BPF_REGISTER_MIN_RANGE) dst_reg->min_value <<= min_val; if (max_val > ilog2(BPF_REGISTER_MAX_RANGE)) dst_reg->max_value = BPF_REGISTER_MAX_RANGE; else if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE) dst_reg->max_value <<= max_val; break; case BPF_RSH: /* RSH by a negative number is undefined, and the BPF_RSH is an * unsigned shift, so make the appropriate casts. */ if (min_val < 0 || dst_reg->min_value < 0) dst_reg->min_value = BPF_REGISTER_MIN_RANGE; else dst_reg->min_value = (u64)(dst_reg->min_value) >> min_val; if (dst_reg->max_value != BPF_REGISTER_MAX_RANGE) dst_reg->max_value >>= max_val; break; default: reset_reg_range_values(regs, insn->dst_reg); break; } check_reg_overflow(dst_reg); } /* check validity of 32-bit and 64-bit arithmetic operations */ static int check_alu_op(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs, *dst_reg; u8 opcode = BPF_OP(insn->code); int err; if (opcode == BPF_END || opcode == BPF_NEG) { if (opcode == BPF_NEG) { if (BPF_SRC(insn->code) != 0 || insn->src_reg != BPF_REG_0 || insn->off != 0 || insn->imm != 0) { verbose("BPF_NEG uses reserved fields\n"); return -EINVAL; } } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0 || (insn->imm != 16 && insn->imm != 32 && insn->imm != 64)) { verbose("BPF_END uses reserved fields\n"); return -EINVAL; } } /* check src operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->dst_reg)) { verbose("R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } /* check dest operand */ err = check_reg_arg(regs, insn->dst_reg, DST_OP); if (err) return err; } else if (opcode == BPF_MOV) { if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose("BPF_MOV uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose("BPF_MOV uses reserved fields\n"); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(regs, insn->dst_reg, DST_OP); if (err) return err; /* we are setting our register to something new, we need to * reset its range values. */ reset_reg_range_values(regs, insn->dst_reg); if (BPF_SRC(insn->code) == BPF_X) { if (BPF_CLASS(insn->code) == BPF_ALU64) { /* case: R1 = R2 * copy register state to dest reg */ regs[insn->dst_reg] = regs[insn->src_reg]; } else { if (is_pointer_value(env, insn->src_reg)) { verbose("R%d partial copy of pointer\n", insn->src_reg); return -EACCES; } mark_reg_unknown_value(regs, insn->dst_reg); } } else { /* case: R = imm * remember the value we stored into this reg */ regs[insn->dst_reg].type = CONST_IMM; regs[insn->dst_reg].imm = insn->imm; regs[insn->dst_reg].max_value = insn->imm; regs[insn->dst_reg].min_value = insn->imm; } } else if (opcode > BPF_END) { verbose("invalid BPF_ALU opcode %x\n", opcode); return -EINVAL; } else { /* all other ALU ops: and, sub, xor, add, ... */ if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0 || insn->off != 0) { verbose("BPF_ALU uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; } else { if (insn->src_reg != BPF_REG_0 || insn->off != 0) { verbose("BPF_ALU uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; if ((opcode == BPF_MOD || opcode == BPF_DIV) && BPF_SRC(insn->code) == BPF_K && insn->imm == 0) { verbose("div by zero\n"); return -EINVAL; } if ((opcode == BPF_LSH || opcode == BPF_RSH || opcode == BPF_ARSH) && BPF_SRC(insn->code) == BPF_K) { int size = BPF_CLASS(insn->code) == BPF_ALU64 ? 64 : 32; if (insn->imm < 0 || insn->imm >= size) { verbose("invalid shift %d\n", insn->imm); return -EINVAL; } } /* check dest operand */ err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; dst_reg = &regs[insn->dst_reg]; /* first we want to adjust our ranges. */ adjust_reg_min_max_vals(env, insn); /* pattern match 'bpf_add Rx, imm' instruction */ if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 && dst_reg->type == FRAME_PTR && BPF_SRC(insn->code) == BPF_K) { dst_reg->type = PTR_TO_STACK; dst_reg->imm = insn->imm; return 0; } else if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 && dst_reg->type == PTR_TO_STACK && ((BPF_SRC(insn->code) == BPF_X && regs[insn->src_reg].type == CONST_IMM) || BPF_SRC(insn->code) == BPF_K)) { if (BPF_SRC(insn->code) == BPF_X) dst_reg->imm += regs[insn->src_reg].imm; else dst_reg->imm += insn->imm; return 0; } else if (opcode == BPF_ADD && BPF_CLASS(insn->code) == BPF_ALU64 && (dst_reg->type == PTR_TO_PACKET || (BPF_SRC(insn->code) == BPF_X && regs[insn->src_reg].type == PTR_TO_PACKET))) { /* ptr_to_packet += K|X */ return check_packet_ptr_add(env, insn); } else if (BPF_CLASS(insn->code) == BPF_ALU64 && dst_reg->type == UNKNOWN_VALUE && env->allow_ptr_leaks) { /* unknown += K|X */ return evaluate_reg_alu(env, insn); } else if (BPF_CLASS(insn->code) == BPF_ALU64 && dst_reg->type == CONST_IMM && env->allow_ptr_leaks) { /* reg_imm += K|X */ return evaluate_reg_imm_alu(env, insn); } else if (is_pointer_value(env, insn->dst_reg)) { verbose("R%d pointer arithmetic prohibited\n", insn->dst_reg); return -EACCES; } else if (BPF_SRC(insn->code) == BPF_X && is_pointer_value(env, insn->src_reg)) { verbose("R%d pointer arithmetic prohibited\n", insn->src_reg); return -EACCES; } /* If we did pointer math on a map value then just set it to our * PTR_TO_MAP_VALUE_ADJ type so we can deal with any stores or * loads to this register appropriately, otherwise just mark the * register as unknown. */ if (env->allow_ptr_leaks && BPF_CLASS(insn->code) == BPF_ALU64 && opcode == BPF_ADD && (dst_reg->type == PTR_TO_MAP_VALUE || dst_reg->type == PTR_TO_MAP_VALUE_ADJ)) dst_reg->type = PTR_TO_MAP_VALUE_ADJ; else mark_reg_unknown_value(regs, insn->dst_reg); } return 0; } static void find_good_pkt_pointers(struct bpf_verifier_state *state, struct bpf_reg_state *dst_reg) { struct bpf_reg_state *regs = state->regs, *reg; int i; /* LLVM can generate two kind of checks: * * Type 1: * * r2 = r3; * r2 += 8; * if (r2 > pkt_end) goto <handle exception> * <access okay> * * Where: * r2 == dst_reg, pkt_end == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * Type 2: * * r2 = r3; * r2 += 8; * if (pkt_end >= r2) goto <access okay> * <handle exception> * * Where: * pkt_end == dst_reg, r2 == src_reg * r2=pkt(id=n,off=8,r=0) * r3=pkt(id=n,off=0,r=0) * * Find register r3 and mark its range as r3=pkt(id=n,off=0,r=8) * so that range of bytes [r3, r3 + 8) is safe to access. */ for (i = 0; i < MAX_BPF_REG; i++) if (regs[i].type == PTR_TO_PACKET && regs[i].id == dst_reg->id) /* keep the maximum range already checked */ regs[i].range = max(regs[i].range, dst_reg->off); for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) { if (state->stack_slot_type[i] != STACK_SPILL) continue; reg = &state->spilled_regs[i / BPF_REG_SIZE]; if (reg->type == PTR_TO_PACKET && reg->id == dst_reg->id) reg->range = max(reg->range, dst_reg->off); } } /* Adjusts the register min/max values in the case that the dst_reg is the * variable register that we are working on, and src_reg is a constant or we're * simply doing a BPF_K check. */ static void reg_set_min_max(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ true_reg->max_value = true_reg->min_value = val; break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ false_reg->max_value = false_reg->min_value = val; break; case BPF_JGT: /* Unsigned comparison, the minimum value is 0. */ false_reg->min_value = 0; /* fallthrough */ case BPF_JSGT: /* If this is false then we know the maximum val is val, * otherwise we know the min val is val+1. */ false_reg->max_value = val; true_reg->min_value = val + 1; break; case BPF_JGE: /* Unsigned comparison, the minimum value is 0. */ false_reg->min_value = 0; /* fallthrough */ case BPF_JSGE: /* If this is false then we know the maximum value is val - 1, * otherwise we know the mimimum value is val. */ false_reg->max_value = val - 1; true_reg->min_value = val; break; default: break; } check_reg_overflow(false_reg); check_reg_overflow(true_reg); } /* Same as above, but for the case that dst_reg is a CONST_IMM reg and src_reg * is the variable reg. */ static void reg_set_min_max_inv(struct bpf_reg_state *true_reg, struct bpf_reg_state *false_reg, u64 val, u8 opcode) { switch (opcode) { case BPF_JEQ: /* If this is false then we know nothing Jon Snow, but if it is * true then we know for sure. */ true_reg->max_value = true_reg->min_value = val; break; case BPF_JNE: /* If this is true we know nothing Jon Snow, but if it is false * we know the value for sure; */ false_reg->max_value = false_reg->min_value = val; break; case BPF_JGT: /* Unsigned comparison, the minimum value is 0. */ true_reg->min_value = 0; /* fallthrough */ case BPF_JSGT: /* * If this is false, then the val is <= the register, if it is * true the register <= to the val. */ false_reg->min_value = val; true_reg->max_value = val - 1; break; case BPF_JGE: /* Unsigned comparison, the minimum value is 0. */ true_reg->min_value = 0; /* fallthrough */ case BPF_JSGE: /* If this is false then constant < register, if it is true then * the register < constant. */ false_reg->min_value = val + 1; true_reg->max_value = val; break; default: break; } check_reg_overflow(false_reg); check_reg_overflow(true_reg); } static void mark_map_reg(struct bpf_reg_state *regs, u32 regno, u32 id, enum bpf_reg_type type) { struct bpf_reg_state *reg = &regs[regno]; if (reg->type == PTR_TO_MAP_VALUE_OR_NULL && reg->id == id) { if (type == UNKNOWN_VALUE) { __mark_reg_unknown_value(regs, regno); } else if (reg->map_ptr->inner_map_meta) { reg->type = CONST_PTR_TO_MAP; reg->map_ptr = reg->map_ptr->inner_map_meta; } else { reg->type = type; } /* We don't need id from this point onwards anymore, thus we * should better reset it, so that state pruning has chances * to take effect. */ reg->id = 0; } } /* The logic is similar to find_good_pkt_pointers(), both could eventually * be folded together at some point. */ static void mark_map_regs(struct bpf_verifier_state *state, u32 regno, enum bpf_reg_type type) { struct bpf_reg_state *regs = state->regs; u32 id = regs[regno].id; int i; for (i = 0; i < MAX_BPF_REG; i++) mark_map_reg(regs, i, id, type); for (i = 0; i < MAX_BPF_STACK; i += BPF_REG_SIZE) { if (state->stack_slot_type[i] != STACK_SPILL) continue; mark_map_reg(state->spilled_regs, i / BPF_REG_SIZE, id, type); } } static int check_cond_jmp_op(struct bpf_verifier_env *env, struct bpf_insn *insn, int *insn_idx) { struct bpf_verifier_state *other_branch, *this_branch = &env->cur_state; struct bpf_reg_state *regs = this_branch->regs, *dst_reg; u8 opcode = BPF_OP(insn->code); int err; if (opcode > BPF_EXIT) { verbose("invalid BPF_JMP opcode %x\n", opcode); return -EINVAL; } if (BPF_SRC(insn->code) == BPF_X) { if (insn->imm != 0) { verbose("BPF_JMP uses reserved fields\n"); return -EINVAL; } /* check src1 operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; if (is_pointer_value(env, insn->src_reg)) { verbose("R%d pointer comparison prohibited\n", insn->src_reg); return -EACCES; } } else { if (insn->src_reg != BPF_REG_0) { verbose("BPF_JMP uses reserved fields\n"); return -EINVAL; } } /* check src2 operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; dst_reg = &regs[insn->dst_reg]; /* detect if R == 0 where R was initialized to zero earlier */ if (BPF_SRC(insn->code) == BPF_K && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == CONST_IMM && dst_reg->imm == insn->imm) { if (opcode == BPF_JEQ) { /* if (imm == imm) goto pc+off; * only follow the goto, ignore fall-through */ *insn_idx += insn->off; return 0; } else { /* if (imm != imm) goto pc+off; * only follow fall-through branch, since * that's where the program will go */ return 0; } } other_branch = push_stack(env, *insn_idx + insn->off + 1, *insn_idx); if (!other_branch) return -EFAULT; /* detect if we are comparing against a constant value so we can adjust * our min/max values for our dst register. */ if (BPF_SRC(insn->code) == BPF_X) { if (regs[insn->src_reg].type == CONST_IMM) reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, regs[insn->src_reg].imm, opcode); else if (dst_reg->type == CONST_IMM) reg_set_min_max_inv(&other_branch->regs[insn->src_reg], &regs[insn->src_reg], dst_reg->imm, opcode); } else { reg_set_min_max(&other_branch->regs[insn->dst_reg], dst_reg, insn->imm, opcode); } /* detect if R == 0 where R is returned from bpf_map_lookup_elem() */ if (BPF_SRC(insn->code) == BPF_K && insn->imm == 0 && (opcode == BPF_JEQ || opcode == BPF_JNE) && dst_reg->type == PTR_TO_MAP_VALUE_OR_NULL) { /* Mark all identical map registers in each branch as either * safe or unknown depending R == 0 or R != 0 conditional. */ mark_map_regs(this_branch, insn->dst_reg, opcode == BPF_JEQ ? PTR_TO_MAP_VALUE : UNKNOWN_VALUE); mark_map_regs(other_branch, insn->dst_reg, opcode == BPF_JEQ ? UNKNOWN_VALUE : PTR_TO_MAP_VALUE); } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGT && dst_reg->type == PTR_TO_PACKET && regs[insn->src_reg].type == PTR_TO_PACKET_END) { find_good_pkt_pointers(this_branch, dst_reg); } else if (BPF_SRC(insn->code) == BPF_X && opcode == BPF_JGE && dst_reg->type == PTR_TO_PACKET_END && regs[insn->src_reg].type == PTR_TO_PACKET) { find_good_pkt_pointers(other_branch, &regs[insn->src_reg]); } else if (is_pointer_value(env, insn->dst_reg)) { verbose("R%d pointer comparison prohibited\n", insn->dst_reg); return -EACCES; } if (log_level) print_verifier_state(this_branch); return 0; } /* return the map pointer stored inside BPF_LD_IMM64 instruction */ static struct bpf_map *ld_imm64_to_map_ptr(struct bpf_insn *insn) { u64 imm64 = ((u64) (u32) insn[0].imm) | ((u64) (u32) insn[1].imm) << 32; return (struct bpf_map *) (unsigned long) imm64; } /* verify BPF_LD_IMM64 instruction */ static int check_ld_imm(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs; int err; if (BPF_SIZE(insn->code) != BPF_DW) { verbose("invalid BPF_LD_IMM insn\n"); return -EINVAL; } if (insn->off != 0) { verbose("BPF_LD_IMM64 uses reserved fields\n"); return -EINVAL; } err = check_reg_arg(regs, insn->dst_reg, DST_OP); if (err) return err; if (insn->src_reg == 0) { u64 imm = ((u64)(insn + 1)->imm << 32) | (u32)insn->imm; regs[insn->dst_reg].type = CONST_IMM; regs[insn->dst_reg].imm = imm; return 0; } /* replace_map_fd_with_map_ptr() should have caught bad ld_imm64 */ BUG_ON(insn->src_reg != BPF_PSEUDO_MAP_FD); regs[insn->dst_reg].type = CONST_PTR_TO_MAP; regs[insn->dst_reg].map_ptr = ld_imm64_to_map_ptr(insn); return 0; } static bool may_access_skb(enum bpf_prog_type type) { switch (type) { case BPF_PROG_TYPE_SOCKET_FILTER: case BPF_PROG_TYPE_SCHED_CLS: case BPF_PROG_TYPE_SCHED_ACT: return true; default: return false; } } /* verify safety of LD_ABS|LD_IND instructions: * - they can only appear in the programs where ctx == skb * - since they are wrappers of function calls, they scratch R1-R5 registers, * preserve R6-R9, and store return value into R0 * * Implicit input: * ctx == skb == R6 == CTX * * Explicit input: * SRC == any register * IMM == 32-bit immediate * * Output: * R0 - 8/16/32-bit skb data converted to cpu endianness */ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn) { struct bpf_reg_state *regs = env->cur_state.regs; u8 mode = BPF_MODE(insn->code); struct bpf_reg_state *reg; int i, err; if (!may_access_skb(env->prog->type)) { verbose("BPF_LD_[ABS|IND] instructions not allowed for this program type\n"); return -EINVAL; } if (insn->dst_reg != BPF_REG_0 || insn->off != 0 || BPF_SIZE(insn->code) == BPF_DW || (mode == BPF_ABS && insn->src_reg != BPF_REG_0)) { verbose("BPF_LD_[ABS|IND] uses reserved fields\n"); return -EINVAL; } /* check whether implicit source operand (register R6) is readable */ err = check_reg_arg(regs, BPF_REG_6, SRC_OP); if (err) return err; if (regs[BPF_REG_6].type != PTR_TO_CTX) { verbose("at the time of BPF_LD_ABS|IND R6 != pointer to skb\n"); return -EINVAL; } if (mode == BPF_IND) { /* check explicit source operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; } /* reset caller saved regs to unreadable */ for (i = 0; i < CALLER_SAVED_REGS; i++) { reg = regs + caller_saved[i]; reg->type = NOT_INIT; reg->imm = 0; } /* mark destination R0 register as readable, since it contains * the value fetched from the packet */ regs[BPF_REG_0].type = UNKNOWN_VALUE; return 0; } /* non-recursive DFS pseudo code * 1 procedure DFS-iterative(G,v): * 2 label v as discovered * 3 let S be a stack * 4 S.push(v) * 5 while S is not empty * 6 t <- S.pop() * 7 if t is what we're looking for: * 8 return t * 9 for all edges e in G.adjacentEdges(t) do * 10 if edge e is already labelled * 11 continue with the next edge * 12 w <- G.adjacentVertex(t,e) * 13 if vertex w is not discovered and not explored * 14 label e as tree-edge * 15 label w as discovered * 16 S.push(w) * 17 continue at 5 * 18 else if vertex w is discovered * 19 label e as back-edge * 20 else * 21 // vertex w is explored * 22 label e as forward- or cross-edge * 23 label t as explored * 24 S.pop() * * convention: * 0x10 - discovered * 0x11 - discovered and fall-through edge labelled * 0x12 - discovered and fall-through and branch edges labelled * 0x20 - explored */ enum { DISCOVERED = 0x10, EXPLORED = 0x20, FALLTHROUGH = 1, BRANCH = 2, }; #define STATE_LIST_MARK ((struct bpf_verifier_state_list *) -1L) static int *insn_stack; /* stack of insns to process */ static int cur_stack; /* current stack index */ static int *insn_state; /* t, w, e - match pseudo-code above: * t - index of current instruction * w - next instruction * e - edge */ static int push_insn(int t, int w, int e, struct bpf_verifier_env *env) { if (e == FALLTHROUGH && insn_state[t] >= (DISCOVERED | FALLTHROUGH)) return 0; if (e == BRANCH && insn_state[t] >= (DISCOVERED | BRANCH)) return 0; if (w < 0 || w >= env->prog->len) { verbose("jump out of range from insn %d to %d\n", t, w); return -EINVAL; } if (e == BRANCH) /* mark branch target for state pruning */ env->explored_states[w] = STATE_LIST_MARK; if (insn_state[w] == 0) { /* tree-edge */ insn_state[t] = DISCOVERED | e; insn_state[w] = DISCOVERED; if (cur_stack >= env->prog->len) return -E2BIG; insn_stack[cur_stack++] = w; return 1; } else if ((insn_state[w] & 0xF0) == DISCOVERED) { verbose("back-edge from insn %d to %d\n", t, w); return -EINVAL; } else if (insn_state[w] == EXPLORED) { /* forward- or cross-edge */ insn_state[t] = DISCOVERED | e; } else { verbose("insn state internal bug\n"); return -EFAULT; } return 0; } /* non-recursive depth-first-search to detect loops in BPF program * loop == back-edge in directed graph */ static int check_cfg(struct bpf_verifier_env *env) { struct bpf_insn *insns = env->prog->insnsi; int insn_cnt = env->prog->len; int ret = 0; int i, t; insn_state = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_state) return -ENOMEM; insn_stack = kcalloc(insn_cnt, sizeof(int), GFP_KERNEL); if (!insn_stack) { kfree(insn_state); return -ENOMEM; } insn_state[0] = DISCOVERED; /* mark 1st insn as discovered */ insn_stack[0] = 0; /* 0 is the first instruction */ cur_stack = 1; peek_stack: if (cur_stack == 0) goto check_state; t = insn_stack[cur_stack - 1]; if (BPF_CLASS(insns[t].code) == BPF_JMP) { u8 opcode = BPF_OP(insns[t].code); if (opcode == BPF_EXIT) { goto mark_explored; } else if (opcode == BPF_CALL) { ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else if (opcode == BPF_JA) { if (BPF_SRC(insns[t].code) != BPF_K) { ret = -EINVAL; goto err_free; } /* unconditional jump with single edge */ ret = push_insn(t, t + insns[t].off + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; /* tell verifier to check for equivalent states * after every call and jump */ if (t + 1 < insn_cnt) env->explored_states[t + 1] = STATE_LIST_MARK; } else { /* conditional jump with two edges */ ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; ret = push_insn(t, t + insns[t].off + 1, BRANCH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } } else { /* all other non-branch instructions with single * fall-through edge */ ret = push_insn(t, t + 1, FALLTHROUGH, env); if (ret == 1) goto peek_stack; else if (ret < 0) goto err_free; } mark_explored: insn_state[t] = EXPLORED; if (cur_stack-- <= 0) { verbose("pop stack internal bug\n"); ret = -EFAULT; goto err_free; } goto peek_stack; check_state: for (i = 0; i < insn_cnt; i++) { if (insn_state[i] != EXPLORED) { verbose("unreachable insn %d\n", i); ret = -EINVAL; goto err_free; } } ret = 0; /* cfg looks good */ err_free: kfree(insn_state); kfree(insn_stack); return ret; } /* the following conditions reduce the number of explored insns * from ~140k to ~80k for ultra large programs that use a lot of ptr_to_packet */ static bool compare_ptrs_to_packet(struct bpf_reg_state *old, struct bpf_reg_state *cur) { if (old->id != cur->id) return false; /* old ptr_to_packet is more conservative, since it allows smaller * range. Ex: * old(off=0,r=10) is equal to cur(off=0,r=20), because * old(off=0,r=10) means that with range=10 the verifier proceeded * further and found no issues with the program. Now we're in the same * spot with cur(off=0,r=20), so we're safe too, since anything further * will only be looking at most 10 bytes after this pointer. */ if (old->off == cur->off && old->range < cur->range) return true; /* old(off=20,r=10) is equal to cur(off=22,re=22 or 5 or 0) * since both cannot be used for packet access and safe(old) * pointer has smaller off that could be used for further * 'if (ptr > data_end)' check * Ex: * old(off=20,r=10) and cur(off=22,r=22) and cur(off=22,r=0) mean * that we cannot access the packet. * The safe range is: * [ptr, ptr + range - off) * so whenever off >=range, it means no safe bytes from this pointer. * When comparing old->off <= cur->off, it means that older code * went with smaller offset and that offset was later * used to figure out the safe range after 'if (ptr > data_end)' check * Say, 'old' state was explored like: * ... R3(off=0, r=0) * R4 = R3 + 20 * ... now R4(off=20,r=0) <-- here * if (R4 > data_end) * ... R4(off=20,r=20), R3(off=0,r=20) and R3 can be used to access. * ... the code further went all the way to bpf_exit. * Now the 'cur' state at the mark 'here' has R4(off=30,r=0). * old_R4(off=20,r=0) equal to cur_R4(off=30,r=0), since if the verifier * goes further, such cur_R4 will give larger safe packet range after * 'if (R4 > data_end)' and all further insn were already good with r=20, * so they will be good with r=30 and we can prune the search. */ if (old->off <= cur->off && old->off >= old->range && cur->off >= cur->range) return true; return false; } /* compare two verifier states * * all states stored in state_list are known to be valid, since * verifier reached 'bpf_exit' instruction through them * * this function is called when verifier exploring different branches of * execution popped from the state stack. If it sees an old state that has * more strict register state and more strict stack state then this execution * branch doesn't need to be explored further, since verifier already * concluded that more strict state leads to valid finish. * * Therefore two states are equivalent if register state is more conservative * and explored stack state is more conservative than the current one. * Example: * explored current * (slot1=INV slot2=MISC) == (slot1=MISC slot2=MISC) * (slot1=MISC slot2=MISC) != (slot1=INV slot2=MISC) * * In other words if current stack state (one being explored) has more * valid slots than old one that already passed validation, it means * the verifier can stop exploring and conclude that current state is valid too * * Similarly with registers. If explored state has register type as invalid * whereas register type in current state is meaningful, it means that * the current state will reach 'bpf_exit' instruction safely */ static bool states_equal(struct bpf_verifier_env *env, struct bpf_verifier_state *old, struct bpf_verifier_state *cur) { bool varlen_map_access = env->varlen_map_value_access; struct bpf_reg_state *rold, *rcur; int i; for (i = 0; i < MAX_BPF_REG; i++) { rold = &old->regs[i]; rcur = &cur->regs[i]; if (memcmp(rold, rcur, sizeof(*rold)) == 0) continue; /* If the ranges were not the same, but everything else was and * we didn't do a variable access into a map then we are a-ok. */ if (!varlen_map_access && memcmp(rold, rcur, offsetofend(struct bpf_reg_state, id)) == 0) continue; /* If we didn't map access then again we don't care about the * mismatched range values and it's ok if our old type was * UNKNOWN and we didn't go to a NOT_INIT'ed reg. */ if (rold->type == NOT_INIT || (!varlen_map_access && rold->type == UNKNOWN_VALUE && rcur->type != NOT_INIT)) continue; if (rold->type == PTR_TO_PACKET && rcur->type == PTR_TO_PACKET && compare_ptrs_to_packet(rold, rcur)) continue; return false; } for (i = 0; i < MAX_BPF_STACK; i++) { if (old->stack_slot_type[i] == STACK_INVALID) continue; if (old->stack_slot_type[i] != cur->stack_slot_type[i]) /* Ex: old explored (safe) state has STACK_SPILL in * this stack slot, but current has has STACK_MISC -> * this verifier states are not equivalent, * return false to continue verification of this path */ return false; if (i % BPF_REG_SIZE) continue; if (memcmp(&old->spilled_regs[i / BPF_REG_SIZE], &cur->spilled_regs[i / BPF_REG_SIZE], sizeof(old->spilled_regs[0]))) /* when explored and current stack slot types are * the same, check that stored pointers types * are the same as well. * Ex: explored safe path could have stored * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -8} * but current path has stored: * (bpf_reg_state) {.type = PTR_TO_STACK, .imm = -16} * such verifier states are not equivalent. * return false to continue verification of this path */ return false; else continue; } return true; } static int is_state_visited(struct bpf_verifier_env *env, int insn_idx) { struct bpf_verifier_state_list *new_sl; struct bpf_verifier_state_list *sl; sl = env->explored_states[insn_idx]; if (!sl) /* this 'insn_idx' instruction wasn't marked, so we will not * be doing state search here */ return 0; while (sl != STATE_LIST_MARK) { if (states_equal(env, &sl->state, &env->cur_state)) /* reached equivalent register/stack state, * prune the search */ return 1; sl = sl->next; } /* there were no equivalent states, remember current one. * technically the current state is not proven to be safe yet, * but it will either reach bpf_exit (which means it's safe) or * it will be rejected. Since there are no loops, we won't be * seeing this 'insn_idx' instruction again on the way to bpf_exit */ new_sl = kmalloc(sizeof(struct bpf_verifier_state_list), GFP_USER); if (!new_sl) return -ENOMEM; /* add new state to the head of linked list */ memcpy(&new_sl->state, &env->cur_state, sizeof(env->cur_state)); new_sl->next = env->explored_states[insn_idx]; env->explored_states[insn_idx] = new_sl; return 0; } static int ext_analyzer_insn_hook(struct bpf_verifier_env *env, int insn_idx, int prev_insn_idx) { if (!env->analyzer_ops || !env->analyzer_ops->insn_hook) return 0; return env->analyzer_ops->insn_hook(env, insn_idx, prev_insn_idx); } static int do_check(struct bpf_verifier_env *env) { struct bpf_verifier_state *state = &env->cur_state; struct bpf_insn *insns = env->prog->insnsi; struct bpf_reg_state *regs = state->regs; int insn_cnt = env->prog->len; int insn_idx, prev_insn_idx = 0; int insn_processed = 0; bool do_print_state = false; init_reg_state(regs); insn_idx = 0; env->varlen_map_value_access = false; for (;;) { struct bpf_insn *insn; u8 class; int err; if (insn_idx >= insn_cnt) { verbose("invalid insn idx %d insn_cnt %d\n", insn_idx, insn_cnt); return -EFAULT; } insn = &insns[insn_idx]; class = BPF_CLASS(insn->code); if (++insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) { verbose("BPF program is too large. Processed %d insn\n", insn_processed); return -E2BIG; } err = is_state_visited(env, insn_idx); if (err < 0) return err; if (err == 1) { /* found equivalent state, can prune the search */ if (log_level) { if (do_print_state) verbose("\nfrom %d to %d: safe\n", prev_insn_idx, insn_idx); else verbose("%d: safe\n", insn_idx); } goto process_bpf_exit; } if (log_level && do_print_state) { verbose("\nfrom %d to %d:", prev_insn_idx, insn_idx); print_verifier_state(&env->cur_state); do_print_state = false; } if (log_level) { verbose("%d: ", insn_idx); print_bpf_insn(insn); } err = ext_analyzer_insn_hook(env, insn_idx, prev_insn_idx); if (err) return err; if (class == BPF_ALU || class == BPF_ALU64) { err = check_alu_op(env, insn); if (err) return err; } else if (class == BPF_LDX) { enum bpf_reg_type *prev_src_type, src_reg_type; /* check for reserved fields is already done */ /* check src operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; err = check_reg_arg(regs, insn->dst_reg, DST_OP_NO_MARK); if (err) return err; src_reg_type = regs[insn->src_reg].type; /* check that memory (src_reg + off) is readable, * the state of dst_reg will be updated by this func */ err = check_mem_access(env, insn->src_reg, insn->off, BPF_SIZE(insn->code), BPF_READ, insn->dst_reg); if (err) return err; if (BPF_SIZE(insn->code) != BPF_W && BPF_SIZE(insn->code) != BPF_DW) { insn_idx++; continue; } prev_src_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_src_type == NOT_INIT) { /* saw a valid insn * dst_reg = *(u32 *)(src_reg + off) * save type to validate intersecting paths */ *prev_src_type = src_reg_type; } else if (src_reg_type != *prev_src_type && (src_reg_type == PTR_TO_CTX || *prev_src_type == PTR_TO_CTX)) { /* ABuser program is trying to use the same insn * dst_reg = *(u32*) (src_reg + off) * with different pointer types: * src_reg == ctx in one branch and * src_reg == stack|map in some other branch. * Reject it. */ verbose("same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_STX) { enum bpf_reg_type *prev_dst_type, dst_reg_type; if (BPF_MODE(insn->code) == BPF_XADD) { err = check_xadd(env, insn); if (err) return err; insn_idx++; continue; } /* check src1 operand */ err = check_reg_arg(regs, insn->src_reg, SRC_OP); if (err) return err; /* check src2 operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; dst_reg_type = regs[insn->dst_reg].type; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, insn->src_reg); if (err) return err; prev_dst_type = &env->insn_aux_data[insn_idx].ptr_type; if (*prev_dst_type == NOT_INIT) { *prev_dst_type = dst_reg_type; } else if (dst_reg_type != *prev_dst_type && (dst_reg_type == PTR_TO_CTX || *prev_dst_type == PTR_TO_CTX)) { verbose("same insn cannot be used with different pointers\n"); return -EINVAL; } } else if (class == BPF_ST) { if (BPF_MODE(insn->code) != BPF_MEM || insn->src_reg != BPF_REG_0) { verbose("BPF_ST uses reserved fields\n"); return -EINVAL; } /* check src operand */ err = check_reg_arg(regs, insn->dst_reg, SRC_OP); if (err) return err; /* check that memory (dst_reg + off) is writeable */ err = check_mem_access(env, insn->dst_reg, insn->off, BPF_SIZE(insn->code), BPF_WRITE, -1); if (err) return err; } else if (class == BPF_JMP) { u8 opcode = BPF_OP(insn->code); if (opcode == BPF_CALL) { if (BPF_SRC(insn->code) != BPF_K || insn->off != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_CALL uses reserved fields\n"); return -EINVAL; } err = check_call(env, insn->imm, insn_idx); if (err) return err; } else if (opcode == BPF_JA) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_JA uses reserved fields\n"); return -EINVAL; } insn_idx += insn->off + 1; continue; } else if (opcode == BPF_EXIT) { if (BPF_SRC(insn->code) != BPF_K || insn->imm != 0 || insn->src_reg != BPF_REG_0 || insn->dst_reg != BPF_REG_0) { verbose("BPF_EXIT uses reserved fields\n"); return -EINVAL; } /* eBPF calling convetion is such that R0 is used * to return the value from eBPF program. * Make sure that it's readable at this time * of bpf_exit, which means that program wrote * something into it earlier */ err = check_reg_arg(regs, BPF_REG_0, SRC_OP); if (err) return err; if (is_pointer_value(env, BPF_REG_0)) { verbose("R0 leaks addr as return value\n"); return -EACCES; } process_bpf_exit: insn_idx = pop_stack(env, &prev_insn_idx); if (insn_idx < 0) { break; } else { do_print_state = true; continue; } } else { err = check_cond_jmp_op(env, insn, &insn_idx); if (err) return err; } } else if (class == BPF_LD) { u8 mode = BPF_MODE(insn->code); if (mode == BPF_ABS || mode == BPF_IND) { err = check_ld_abs(env, insn); if (err) return err; } else if (mode == BPF_IMM) { err = check_ld_imm(env, insn); if (err) return err; insn_idx++; } else { verbose("invalid BPF_LD mode\n"); return -EINVAL; } reset_reg_range_values(regs, insn->dst_reg); } else { verbose("unknown insn class %d\n", class); return -EINVAL; } insn_idx++; } verbose("processed %d insns\n", insn_processed); return 0; } static int check_map_prealloc(struct bpf_map *map) { return (map->map_type != BPF_MAP_TYPE_HASH && map->map_type != BPF_MAP_TYPE_PERCPU_HASH && map->map_type != BPF_MAP_TYPE_HASH_OF_MAPS) || !(map->map_flags & BPF_F_NO_PREALLOC); } static int check_map_prog_compatibility(struct bpf_map *map, struct bpf_prog *prog) { /* Make sure that BPF_PROG_TYPE_PERF_EVENT programs only use * preallocated hash maps, since doing memory allocation * in overflow_handler can crash depending on where nmi got * triggered. */ if (prog->type == BPF_PROG_TYPE_PERF_EVENT) { if (!check_map_prealloc(map)) { verbose("perf_event programs can only use preallocated hash map\n"); return -EINVAL; } if (map->inner_map_meta && !check_map_prealloc(map->inner_map_meta)) { verbose("perf_event programs can only use preallocated inner hash map\n"); return -EINVAL; } } return 0; } /* look for pseudo eBPF instructions that access map FDs and * replace them with actual map pointers */ static int replace_map_fd_with_map_ptr(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i, j, err; err = bpf_prog_calc_tag(env->prog); if (err) return err; for (i = 0; i < insn_cnt; i++, insn++) { if (BPF_CLASS(insn->code) == BPF_LDX && (BPF_MODE(insn->code) != BPF_MEM || insn->imm != 0)) { verbose("BPF_LDX uses reserved fields\n"); return -EINVAL; } if (BPF_CLASS(insn->code) == BPF_STX && ((BPF_MODE(insn->code) != BPF_MEM && BPF_MODE(insn->code) != BPF_XADD) || insn->imm != 0)) { verbose("BPF_STX uses reserved fields\n"); return -EINVAL; } if (insn[0].code == (BPF_LD | BPF_IMM | BPF_DW)) { struct bpf_map *map; struct fd f; if (i == insn_cnt - 1 || insn[1].code != 0 || insn[1].dst_reg != 0 || insn[1].src_reg != 0 || insn[1].off != 0) { verbose("invalid bpf_ld_imm64 insn\n"); return -EINVAL; } if (insn->src_reg == 0) /* valid generic load 64-bit imm */ goto next_insn; if (insn->src_reg != BPF_PSEUDO_MAP_FD) { verbose("unrecognized bpf_ld_imm64 insn\n"); return -EINVAL; } f = fdget(insn->imm); map = __bpf_map_get(f); if (IS_ERR(map)) { verbose("fd %d is not pointing to valid bpf_map\n", insn->imm); return PTR_ERR(map); } err = check_map_prog_compatibility(map, env->prog); if (err) { fdput(f); return err; } /* store map pointer inside BPF_LD_IMM64 instruction */ insn[0].imm = (u32) (unsigned long) map; insn[1].imm = ((u64) (unsigned long) map) >> 32; /* check whether we recorded this map already */ for (j = 0; j < env->used_map_cnt; j++) if (env->used_maps[j] == map) { fdput(f); goto next_insn; } if (env->used_map_cnt >= MAX_USED_MAPS) { fdput(f); return -E2BIG; } /* hold the map. If the program is rejected by verifier, * the map will be released by release_maps() or it * will be used by the valid program until it's unloaded * and all maps are released in free_bpf_prog_info() */ map = bpf_map_inc(map, false); if (IS_ERR(map)) { fdput(f); return PTR_ERR(map); } env->used_maps[env->used_map_cnt++] = map; fdput(f); next_insn: insn++; i++; } } /* now all pseudo BPF_LD_IMM64 instructions load valid * 'struct bpf_map *' into a register instead of user map_fd. * These pointers will be used later by verifier to validate map access. */ return 0; } /* drop refcnt of maps used by the rejected program */ static void release_maps(struct bpf_verifier_env *env) { int i; for (i = 0; i < env->used_map_cnt; i++) bpf_map_put(env->used_maps[i]); } /* convert pseudo BPF_LD_IMM64 into generic BPF_LD_IMM64 */ static void convert_pseudo_ld_imm64(struct bpf_verifier_env *env) { struct bpf_insn *insn = env->prog->insnsi; int insn_cnt = env->prog->len; int i; for (i = 0; i < insn_cnt; i++, insn++) if (insn->code == (BPF_LD | BPF_IMM | BPF_DW)) insn->src_reg = 0; } /* single env->prog->insni[off] instruction was replaced with the range * insni[off, off + cnt). Adjust corresponding insn_aux_data by copying * [0, off) and [off, end) to new locations, so the patched range stays zero */ static int adjust_insn_aux_data(struct bpf_verifier_env *env, u32 prog_len, u32 off, u32 cnt) { struct bpf_insn_aux_data *new_data, *old_data = env->insn_aux_data; if (cnt == 1) return 0; new_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog_len); if (!new_data) return -ENOMEM; memcpy(new_data, old_data, sizeof(struct bpf_insn_aux_data) * off); memcpy(new_data + off + cnt - 1, old_data + off, sizeof(struct bpf_insn_aux_data) * (prog_len - off - cnt + 1)); env->insn_aux_data = new_data; vfree(old_data); return 0; } static struct bpf_prog *bpf_patch_insn_data(struct bpf_verifier_env *env, u32 off, const struct bpf_insn *patch, u32 len) { struct bpf_prog *new_prog; new_prog = bpf_patch_insn_single(env->prog, off, patch, len); if (!new_prog) return NULL; if (adjust_insn_aux_data(env, new_prog->len, off, len)) return NULL; return new_prog; } /* convert load instructions that access fields of 'struct __sk_buff' * into sequence of instructions that access fields of 'struct sk_buff' */ static int convert_ctx_accesses(struct bpf_verifier_env *env) { const struct bpf_verifier_ops *ops = env->prog->aux->ops; const int insn_cnt = env->prog->len; struct bpf_insn insn_buf[16], *insn; struct bpf_prog *new_prog; enum bpf_access_type type; int i, cnt, delta = 0; if (ops->gen_prologue) { cnt = ops->gen_prologue(insn_buf, env->seen_direct_write, env->prog); if (cnt >= ARRAY_SIZE(insn_buf)) { verbose("bpf verifier is misconfigured\n"); return -EINVAL; } else if (cnt) { new_prog = bpf_patch_insn_data(env, 0, insn_buf, cnt); if (!new_prog) return -ENOMEM; env->prog = new_prog; delta += cnt - 1; } } if (!ops->convert_ctx_access) return 0; insn = env->prog->insnsi + delta; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code == (BPF_LDX | BPF_MEM | BPF_B) || insn->code == (BPF_LDX | BPF_MEM | BPF_H) || insn->code == (BPF_LDX | BPF_MEM | BPF_W) || insn->code == (BPF_LDX | BPF_MEM | BPF_DW)) type = BPF_READ; else if (insn->code == (BPF_STX | BPF_MEM | BPF_B) || insn->code == (BPF_STX | BPF_MEM | BPF_H) || insn->code == (BPF_STX | BPF_MEM | BPF_W) || insn->code == (BPF_STX | BPF_MEM | BPF_DW)) type = BPF_WRITE; else continue; if (env->insn_aux_data[i + delta].ptr_type != PTR_TO_CTX) continue; cnt = ops->convert_ctx_access(type, insn, insn_buf, env->prog); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose("bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = new_prog; insn = new_prog->insnsi + i + delta; } return 0; } /* fixup insn->imm field of bpf_call instructions * and inline eligible helpers as explicit sequence of BPF instructions * * this function is called after eBPF program passed verification */ static int fixup_bpf_calls(struct bpf_verifier_env *env) { struct bpf_prog *prog = env->prog; struct bpf_insn *insn = prog->insnsi; const struct bpf_func_proto *fn; const int insn_cnt = prog->len; struct bpf_insn insn_buf[16]; struct bpf_prog *new_prog; struct bpf_map *map_ptr; int i, cnt, delta = 0; for (i = 0; i < insn_cnt; i++, insn++) { if (insn->code != (BPF_JMP | BPF_CALL)) continue; if (insn->imm == BPF_FUNC_get_route_realm) prog->dst_needed = 1; if (insn->imm == BPF_FUNC_get_prandom_u32) bpf_user_rnd_init_once(); if (insn->imm == BPF_FUNC_tail_call) { /* If we tail call into other programs, we * cannot make any assumptions since they can * be replaced dynamically during runtime in * the program array. */ prog->cb_access = 1; /* mark bpf_tail_call as different opcode to avoid * conditional branch in the interpeter for every normal * call and to prevent accidental JITing by JIT compiler * that doesn't support bpf_tail_call yet */ insn->imm = 0; insn->code |= BPF_X; continue; } if (ebpf_jit_enabled() && insn->imm == BPF_FUNC_map_lookup_elem) { map_ptr = env->insn_aux_data[i + delta].map_ptr; if (map_ptr == BPF_MAP_PTR_POISON || !map_ptr->ops->map_gen_lookup) goto patch_call_imm; cnt = map_ptr->ops->map_gen_lookup(map_ptr, insn_buf); if (cnt == 0 || cnt >= ARRAY_SIZE(insn_buf)) { verbose("bpf verifier is misconfigured\n"); return -EINVAL; } new_prog = bpf_patch_insn_data(env, i + delta, insn_buf, cnt); if (!new_prog) return -ENOMEM; delta += cnt - 1; /* keep walking new program and skip insns we just inserted */ env->prog = prog = new_prog; insn = new_prog->insnsi + i + delta; continue; } patch_call_imm: fn = prog->aux->ops->get_func_proto(insn->imm); /* all functions that have prototype and verifier allowed * programs to call them, must be real in-kernel functions */ if (!fn->func) { verbose("kernel subsystem misconfigured func %s#%d\n", func_id_name(insn->imm), insn->imm); return -EFAULT; } insn->imm = fn->func - __bpf_call_base; } return 0; } static void free_states(struct bpf_verifier_env *env) { struct bpf_verifier_state_list *sl, *sln; int i; if (!env->explored_states) return; for (i = 0; i < env->prog->len; i++) { sl = env->explored_states[i]; if (sl) while (sl != STATE_LIST_MARK) { sln = sl->next; kfree(sl); sl = sln; } } kfree(env->explored_states); } int bpf_check(struct bpf_prog **prog, union bpf_attr *attr) { char __user *log_ubuf = NULL; struct bpf_verifier_env *env; int ret = -EINVAL; /* 'struct bpf_verifier_env' can be global, but since it's not small, * allocate/free it every time bpf_check() is called */ env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * (*prog)->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = *prog; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); if (attr->log_level || attr->log_buf || attr->log_size) { /* user requested verbose verifier output * and supplied buffer to store the verification trace */ log_level = attr->log_level; log_ubuf = (char __user *) (unsigned long) attr->log_buf; log_size = attr->log_size; log_len = 0; ret = -EINVAL; /* log_* values have to be sane */ if (log_size < 128 || log_size > UINT_MAX >> 8 || log_level == 0 || log_ubuf == NULL) goto err_unlock; ret = -ENOMEM; log_buf = vmalloc(log_size); if (!log_buf) goto err_unlock; } else { log_level = 0; } ret = replace_map_fd_with_map_ptr(env); if (ret < 0) goto skip_full_check; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_USER); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); skip_full_check: while (pop_stack(env, NULL) >= 0); free_states(env); if (ret == 0) /* program is valid, convert *(u32*)(ctx + off) accesses */ ret = convert_ctx_accesses(env); if (ret == 0) ret = fixup_bpf_calls(env); if (log_level && log_len >= log_size - 1) { BUG_ON(log_len >= log_size); /* verifier log exceeded user supplied buffer */ ret = -ENOSPC; /* fall through to return what was recorded */ } /* copy verifier log back to user space including trailing zero */ if (log_level && copy_to_user(log_ubuf, log_buf, log_len + 1) != 0) { ret = -EFAULT; goto free_log_buf; } if (ret == 0 && env->used_map_cnt) { /* if program passed verifier, update used_maps in bpf_prog_info */ env->prog->aux->used_maps = kmalloc_array(env->used_map_cnt, sizeof(env->used_maps[0]), GFP_KERNEL); if (!env->prog->aux->used_maps) { ret = -ENOMEM; goto free_log_buf; } memcpy(env->prog->aux->used_maps, env->used_maps, sizeof(env->used_maps[0]) * env->used_map_cnt); env->prog->aux->used_map_cnt = env->used_map_cnt; /* program is valid. Convert pseudo bpf_ld_imm64 into generic * bpf_ld_imm64 instructions */ convert_pseudo_ld_imm64(env); } free_log_buf: if (log_level) vfree(log_buf); if (!env->prog->aux->used_maps) /* if we didn't copy map pointers into bpf_prog_info, release * them now. Otherwise free_bpf_prog_info() will release them. */ release_maps(env); *prog = env->prog; err_unlock: mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; } int bpf_analyzer(struct bpf_prog *prog, const struct bpf_ext_analyzer_ops *ops, void *priv) { struct bpf_verifier_env *env; int ret; env = kzalloc(sizeof(struct bpf_verifier_env), GFP_KERNEL); if (!env) return -ENOMEM; env->insn_aux_data = vzalloc(sizeof(struct bpf_insn_aux_data) * prog->len); ret = -ENOMEM; if (!env->insn_aux_data) goto err_free_env; env->prog = prog; env->analyzer_ops = ops; env->analyzer_priv = priv; /* grab the mutex to protect few globals used by verifier */ mutex_lock(&bpf_verifier_lock); log_level = 0; env->explored_states = kcalloc(env->prog->len, sizeof(struct bpf_verifier_state_list *), GFP_KERNEL); ret = -ENOMEM; if (!env->explored_states) goto skip_full_check; ret = check_cfg(env); if (ret < 0) goto skip_full_check; env->allow_ptr_leaks = capable(CAP_SYS_ADMIN); ret = do_check(env); skip_full_check: while (pop_stack(env, NULL) >= 0); free_states(env); mutex_unlock(&bpf_verifier_lock); vfree(env->insn_aux_data); err_free_env: kfree(env); return ret; } EXPORT_SYMBOL_GPL(bpf_analyzer);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3366_0
crossvul-cpp_data_good_3441_0
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2000-2001 Qualcomm Incorporated Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth SCO sockets. */ #include <linux/module.h> #include <linux/types.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/socket.h> #include <linux/skbuff.h> #include <linux/device.h> #include <linux/debugfs.h> #include <linux/seq_file.h> #include <linux/list.h> #include <net/sock.h> #include <asm/system.h> #include <linux/uaccess.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/sco.h> #define VERSION "0.6" static int disable_esco; static const struct proto_ops sco_sock_ops; static struct bt_sock_list sco_sk_list = { .lock = __RW_LOCK_UNLOCKED(sco_sk_list.lock) }; static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent); static void sco_chan_del(struct sock *sk, int err); static int sco_conn_del(struct hci_conn *conn, int err); static void sco_sock_close(struct sock *sk); static void sco_sock_kill(struct sock *sk); /* ---- SCO timers ---- */ static void sco_sock_timeout(unsigned long arg) { struct sock *sk = (struct sock *) arg; BT_DBG("sock %p state %d", sk, sk->sk_state); bh_lock_sock(sk); sk->sk_err = ETIMEDOUT; sk->sk_state_change(sk); bh_unlock_sock(sk); sco_sock_kill(sk); sock_put(sk); } static void sco_sock_set_timer(struct sock *sk, long timeout) { BT_DBG("sock %p state %d timeout %ld", sk, sk->sk_state, timeout); sk_reset_timer(sk, &sk->sk_timer, jiffies + timeout); } static void sco_sock_clear_timer(struct sock *sk) { BT_DBG("sock %p state %d", sk, sk->sk_state); sk_stop_timer(sk, &sk->sk_timer); } /* ---- SCO connections ---- */ static struct sco_conn *sco_conn_add(struct hci_conn *hcon, __u8 status) { struct hci_dev *hdev = hcon->hdev; struct sco_conn *conn = hcon->sco_data; if (conn || status) return conn; conn = kzalloc(sizeof(struct sco_conn), GFP_ATOMIC); if (!conn) return NULL; spin_lock_init(&conn->lock); hcon->sco_data = conn; conn->hcon = hcon; conn->src = &hdev->bdaddr; conn->dst = &hcon->dst; if (hdev->sco_mtu > 0) conn->mtu = hdev->sco_mtu; else conn->mtu = 60; BT_DBG("hcon %p conn %p", hcon, conn); return conn; } static inline struct sock *sco_chan_get(struct sco_conn *conn) { struct sock *sk = NULL; sco_conn_lock(conn); sk = conn->sk; sco_conn_unlock(conn); return sk; } static int sco_conn_del(struct hci_conn *hcon, int err) { struct sco_conn *conn = hcon->sco_data; struct sock *sk; if (!conn) return 0; BT_DBG("hcon %p conn %p, err %d", hcon, conn, err); /* Kill socket */ sk = sco_chan_get(conn); if (sk) { bh_lock_sock(sk); sco_sock_clear_timer(sk); sco_chan_del(sk, err); bh_unlock_sock(sk); sco_sock_kill(sk); } hcon->sco_data = NULL; kfree(conn); return 0; } static inline int sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent) { int err = 0; sco_conn_lock(conn); if (conn->sk) err = -EBUSY; else __sco_chan_add(conn, sk, parent); sco_conn_unlock(conn); return err; } static int sco_connect(struct sock *sk) { bdaddr_t *src = &bt_sk(sk)->src; bdaddr_t *dst = &bt_sk(sk)->dst; struct sco_conn *conn; struct hci_conn *hcon; struct hci_dev *hdev; int err, type; BT_DBG("%s -> %s", batostr(src), batostr(dst)); hdev = hci_get_route(dst, src); if (!hdev) return -EHOSTUNREACH; hci_dev_lock_bh(hdev); err = -ENOMEM; if (lmp_esco_capable(hdev) && !disable_esco) type = ESCO_LINK; else type = SCO_LINK; hcon = hci_connect(hdev, type, dst, BT_SECURITY_LOW, HCI_AT_NO_BONDING); if (!hcon) goto done; conn = sco_conn_add(hcon, 0); if (!conn) { hci_conn_put(hcon); goto done; } /* Update source addr of the socket */ bacpy(src, conn->src); err = sco_chan_add(conn, sk, NULL); if (err) goto done; if (hcon->state == BT_CONNECTED) { sco_sock_clear_timer(sk); sk->sk_state = BT_CONNECTED; } else { sk->sk_state = BT_CONNECT; sco_sock_set_timer(sk, sk->sk_sndtimeo); } done: hci_dev_unlock_bh(hdev); hci_dev_put(hdev); return err; } static inline int sco_send_frame(struct sock *sk, struct msghdr *msg, int len) { struct sco_conn *conn = sco_pi(sk)->conn; struct sk_buff *skb; int err, count; /* Check outgoing MTU */ if (len > conn->mtu) return -EINVAL; BT_DBG("sk %p len %d", sk, len); count = min_t(unsigned int, conn->mtu, len); skb = bt_skb_send_alloc(sk, count, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) return err; if (memcpy_fromiovec(skb_put(skb, count), msg->msg_iov, count)) { kfree_skb(skb); return -EFAULT; } hci_send_sco(conn->hcon, skb); return count; } static inline void sco_recv_frame(struct sco_conn *conn, struct sk_buff *skb) { struct sock *sk = sco_chan_get(conn); if (!sk) goto drop; BT_DBG("sk %p len %d", sk, skb->len); if (sk->sk_state != BT_CONNECTED) goto drop; if (!sock_queue_rcv_skb(sk, skb)) return; drop: kfree_skb(skb); } /* -------- Socket interface ---------- */ static struct sock *__sco_get_sock_by_addr(bdaddr_t *ba) { struct sock *sk; struct hlist_node *node; sk_for_each(sk, node, &sco_sk_list.head) if (!bacmp(&bt_sk(sk)->src, ba)) goto found; sk = NULL; found: return sk; } /* Find socket listening on source bdaddr. * Returns closest match. */ static struct sock *sco_get_sock_listen(bdaddr_t *src) { struct sock *sk = NULL, *sk1 = NULL; struct hlist_node *node; read_lock(&sco_sk_list.lock); sk_for_each(sk, node, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; /* Exact match. */ if (!bacmp(&bt_sk(sk)->src, src)) break; /* Closest match */ if (!bacmp(&bt_sk(sk)->src, BDADDR_ANY)) sk1 = sk; } read_unlock(&sco_sk_list.lock); return node ? sk : sk1; } static void sco_sock_destruct(struct sock *sk) { BT_DBG("sk %p", sk); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); } static void sco_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted channels */ while ((sk = bt_accept_dequeue(parent, NULL))) { sco_sock_close(sk); sco_sock_kill(sk); } parent->sk_state = BT_CLOSED; sock_set_flag(parent, SOCK_ZAPPED); } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void sco_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %d", sk, sk->sk_state); /* Kill poor orphan */ bt_sock_unlink(&sco_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static void __sco_sock_close(struct sock *sk) { BT_DBG("sk %p state %d socket %p", sk, sk->sk_state, sk->sk_socket); switch (sk->sk_state) { case BT_LISTEN: sco_sock_cleanup_listen(sk); break; case BT_CONNECTED: case BT_CONFIG: case BT_CONNECT: case BT_DISCONN: sco_chan_del(sk, ECONNRESET); break; default: sock_set_flag(sk, SOCK_ZAPPED); break; } } /* Must be called on unlocked socket. */ static void sco_sock_close(struct sock *sk) { sco_sock_clear_timer(sk); lock_sock(sk); __sco_sock_close(sk); release_sock(sk); sco_sock_kill(sk); } static void sco_sock_init(struct sock *sk, struct sock *parent) { BT_DBG("sk %p", sk); if (parent) sk->sk_type = parent->sk_type; } static struct proto sco_proto = { .name = "SCO", .owner = THIS_MODULE, .obj_size = sizeof(struct sco_pinfo) }; static struct sock *sco_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio) { struct sock *sk; sk = sk_alloc(net, PF_BLUETOOTH, prio, &sco_proto); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); sk->sk_destruct = sco_sock_destruct; sk->sk_sndtimeo = SCO_CONN_TIMEOUT; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; setup_timer(&sk->sk_timer, sco_sock_timeout, (unsigned long)sk); bt_sock_link(&sco_sk_list, sk); return sk; } static int sco_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_SEQPACKET) return -ESOCKTNOSUPPORT; sock->ops = &sco_sock_ops; sk = sco_sock_alloc(net, sock, protocol, GFP_ATOMIC); if (!sk) return -ENOMEM; sco_sock_init(sk, NULL); return 0; } static int sco_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; bdaddr_t *src = &sa->sco_bdaddr; int err = 0; BT_DBG("sk %p %s", sk, batostr(&sa->sco_bdaddr)); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } write_lock_bh(&sco_sk_list.lock); if (bacmp(src, BDADDR_ANY) && __sco_get_sock_by_addr(src)) { err = -EADDRINUSE; } else { /* Save source address */ bacpy(&bt_sk(sk)->src, &sa->sco_bdaddr); sk->sk_state = BT_BOUND; } write_unlock_bh(&sco_sk_list.lock); done: release_sock(sk); return err; } static int sco_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p", sk); if (alen < sizeof(struct sockaddr_sco) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; if (sk->sk_state != BT_OPEN && sk->sk_state != BT_BOUND) return -EBADFD; if (sk->sk_type != SOCK_SEQPACKET) return -EINVAL; lock_sock(sk); /* Set destination address and psm */ bacpy(&bt_sk(sk)->dst, &sa->sco_bdaddr); err = sco_connect(sk); if (err) goto done; err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); done: release_sock(sk); return err; } static int sco_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND || sock->type != SOCK_SEQPACKET) { err = -EBADFD; goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; } static int sco_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *ch; long timeo; int err = 0; lock_sock(sk); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (!(ch = bt_accept_dequeue(sk, newsock))) { set_current_state(TASK_INTERRUPTIBLE); if (!timeo) { err = -EAGAIN; break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock(sk); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } } set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", ch); done: release_sock(sk); return err; } static int sco_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_sco *sa = (struct sockaddr_sco *) addr; struct sock *sk = sock->sk; BT_DBG("sock %p, sk %p", sock, sk); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_sco); if (peer) bacpy(&sa->sco_bdaddr, &bt_sk(sk)->dst); else bacpy(&sa->sco_bdaddr, &bt_sk(sk)->src); return 0; } static int sco_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; lock_sock(sk); if (sk->sk_state == BT_CONNECTED) err = sco_send_frame(sk, msg, len); else err = -ENOTCONN; release_sock(sk); return err; } static int sco_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct sco_options opts; struct sco_conninfo cinfo; int len, err = 0; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case SCO_OPTIONS: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } opts.mtu = sco_pi(sk)->conn->mtu; BT_DBG("mtu %d", opts.mtu); len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *)&opts, len)) err = -EFAULT; break; case SCO_CONNINFO: if (sk->sk_state != BT_CONNECTED) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = sco_pi(sk)->conn->hcon->handle; memcpy(cinfo.dev_class, sco_pi(sk)->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *)&cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_SCO) return sco_sock_getsockopt_old(sock, optname, optval, optlen); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int sco_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; lock_sock(sk); if (!sk->sk_shutdown) { sk->sk_shutdown = SHUTDOWN_MASK; sco_sock_clear_timer(sk); __sco_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } release_sock(sk); return err; } static int sco_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; sco_sock_close(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) { lock_sock(sk); err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); release_sock(sk); } sock_orphan(sk); sco_sock_kill(sk); return err; } static void __sco_chan_add(struct sco_conn *conn, struct sock *sk, struct sock *parent) { BT_DBG("conn %p", conn); sco_pi(sk)->conn = conn; conn->sk = sk; if (parent) bt_accept_enqueue(parent, sk); } /* Delete channel. * Must be called on the locked socket. */ static void sco_chan_del(struct sock *sk, int err) { struct sco_conn *conn; conn = sco_pi(sk)->conn; BT_DBG("sk %p, conn %p, err %d", sk, conn, err); if (conn) { sco_conn_lock(conn); conn->sk = NULL; sco_pi(sk)->conn = NULL; sco_conn_unlock(conn); hci_conn_put(conn->hcon); } sk->sk_state = BT_CLOSED; sk->sk_err = err; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_ZAPPED); } static void sco_conn_ready(struct sco_conn *conn) { struct sock *parent; struct sock *sk = conn->sk; BT_DBG("conn %p", conn); sco_conn_lock(conn); if (sk) { sco_sock_clear_timer(sk); bh_lock_sock(sk); sk->sk_state = BT_CONNECTED; sk->sk_state_change(sk); bh_unlock_sock(sk); } else { parent = sco_get_sock_listen(conn->src); if (!parent) goto done; bh_lock_sock(parent); sk = sco_sock_alloc(sock_net(parent), NULL, BTPROTO_SCO, GFP_ATOMIC); if (!sk) { bh_unlock_sock(parent); goto done; } sco_sock_init(sk, parent); bacpy(&bt_sk(sk)->src, conn->src); bacpy(&bt_sk(sk)->dst, conn->dst); hci_conn_hold(conn->hcon); __sco_chan_add(conn, sk, parent); sk->sk_state = BT_CONNECTED; /* Wake up parent */ parent->sk_data_ready(parent, 1); bh_unlock_sock(parent); } done: sco_conn_unlock(conn); } /* ----- SCO interface with lower layer (HCI) ----- */ static int sco_connect_ind(struct hci_dev *hdev, bdaddr_t *bdaddr, __u8 type) { register struct sock *sk; struct hlist_node *node; int lm = 0; if (type != SCO_LINK && type != ESCO_LINK) return -EINVAL; BT_DBG("hdev %s, bdaddr %s", hdev->name, batostr(bdaddr)); /* Find listening sockets */ read_lock(&sco_sk_list.lock); sk_for_each(sk, node, &sco_sk_list.head) { if (sk->sk_state != BT_LISTEN) continue; if (!bacmp(&bt_sk(sk)->src, &hdev->bdaddr) || !bacmp(&bt_sk(sk)->src, BDADDR_ANY)) { lm |= HCI_LM_ACCEPT; break; } } read_unlock(&sco_sk_list.lock); return lm; } static int sco_connect_cfm(struct hci_conn *hcon, __u8 status) { BT_DBG("hcon %p bdaddr %s status %d", hcon, batostr(&hcon->dst), status); if (hcon->type != SCO_LINK && hcon->type != ESCO_LINK) return -EINVAL; if (!status) { struct sco_conn *conn; conn = sco_conn_add(hcon, status); if (conn) sco_conn_ready(conn); } else sco_conn_del(hcon, bt_err(status)); return 0; } static int sco_disconn_cfm(struct hci_conn *hcon, __u8 reason) { BT_DBG("hcon %p reason %d", hcon, reason); if (hcon->type != SCO_LINK && hcon->type != ESCO_LINK) return -EINVAL; sco_conn_del(hcon, bt_err(reason)); return 0; } static int sco_recv_scodata(struct hci_conn *hcon, struct sk_buff *skb) { struct sco_conn *conn = hcon->sco_data; if (!conn) goto drop; BT_DBG("conn %p len %d", conn, skb->len); if (skb->len) { sco_recv_frame(conn, skb); return 0; } drop: kfree_skb(skb); return 0; } static int sco_debugfs_show(struct seq_file *f, void *p) { struct sock *sk; struct hlist_node *node; read_lock_bh(&sco_sk_list.lock); sk_for_each(sk, node, &sco_sk_list.head) { seq_printf(f, "%s %s %d\n", batostr(&bt_sk(sk)->src), batostr(&bt_sk(sk)->dst), sk->sk_state); } read_unlock_bh(&sco_sk_list.lock); return 0; } static int sco_debugfs_open(struct inode *inode, struct file *file) { return single_open(file, sco_debugfs_show, inode->i_private); } static const struct file_operations sco_debugfs_fops = { .open = sco_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static struct dentry *sco_debugfs; static const struct proto_ops sco_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = sco_sock_release, .bind = sco_sock_bind, .connect = sco_sock_connect, .listen = sco_sock_listen, .accept = sco_sock_accept, .getname = sco_sock_getname, .sendmsg = sco_sock_sendmsg, .recvmsg = bt_sock_recvmsg, .poll = bt_sock_poll, .ioctl = bt_sock_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = sco_sock_shutdown, .setsockopt = sco_sock_setsockopt, .getsockopt = sco_sock_getsockopt }; static const struct net_proto_family sco_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = sco_sock_create, }; static struct hci_proto sco_hci_proto = { .name = "SCO", .id = HCI_PROTO_SCO, .connect_ind = sco_connect_ind, .connect_cfm = sco_connect_cfm, .disconn_cfm = sco_disconn_cfm, .recv_scodata = sco_recv_scodata }; static int __init sco_init(void) { int err; err = proto_register(&sco_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_SCO, &sco_sock_family_ops); if (err < 0) { BT_ERR("SCO socket registration failed"); goto error; } err = hci_register_proto(&sco_hci_proto); if (err < 0) { BT_ERR("SCO protocol registration failed"); bt_sock_unregister(BTPROTO_SCO); goto error; } if (bt_debugfs) { sco_debugfs = debugfs_create_file("sco", 0444, bt_debugfs, NULL, &sco_debugfs_fops); if (!sco_debugfs) BT_ERR("Failed to create SCO debug file"); } BT_INFO("SCO (Voice Link) ver %s", VERSION); BT_INFO("SCO socket layer initialized"); return 0; error: proto_unregister(&sco_proto); return err; } static void __exit sco_exit(void) { debugfs_remove(sco_debugfs); if (bt_sock_unregister(BTPROTO_SCO) < 0) BT_ERR("SCO socket unregistration failed"); if (hci_unregister_proto(&sco_hci_proto) < 0) BT_ERR("SCO protocol unregistration failed"); proto_unregister(&sco_proto); } module_init(sco_init); module_exit(sco_exit); module_param(disable_esco, bool, 0644); MODULE_PARM_DESC(disable_esco, "Disable eSCO connection creation"); MODULE_AUTHOR("Marcel Holtmann <marcel@holtmann.org>"); MODULE_DESCRIPTION("Bluetooth SCO ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS("bt-proto-2");
./CrossVul/dataset_final_sorted/CWE-200/c/good_3441_0
crossvul-cpp_data_good_295_1
/* $OpenBSD: auth2-hostbased.c,v 1.36 2018/07/31 03:10:27 djm Exp $ */ /* * Copyright (c) 2000 Markus Friedl. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <sys/types.h> #include <pwd.h> #include <string.h> #include <stdarg.h> #include "xmalloc.h" #include "ssh2.h" #include "packet.h" #include "sshbuf.h" #include "log.h" #include "misc.h" #include "servconf.h" #include "compat.h" #include "sshkey.h" #include "hostfile.h" #include "auth.h" #include "canohost.h" #ifdef GSSAPI #include "ssh-gss.h" #endif #include "monitor_wrap.h" #include "pathnames.h" #include "ssherr.h" #include "match.h" /* import */ extern ServerOptions options; extern u_char *session_id2; extern u_int session_id2_len; static int userauth_hostbased(struct ssh *ssh) { Authctxt *authctxt = ssh->authctxt; struct sshbuf *b; struct sshkey *key = NULL; char *pkalg, *cuser, *chost; u_char *pkblob, *sig; size_t alen, blen, slen; int r, pktype, authenticated = 0; /* XXX use sshkey_froms() */ if ((r = sshpkt_get_cstring(ssh, &pkalg, &alen)) != 0 || (r = sshpkt_get_string(ssh, &pkblob, &blen)) != 0 || (r = sshpkt_get_cstring(ssh, &chost, NULL)) != 0 || (r = sshpkt_get_cstring(ssh, &cuser, NULL)) != 0 || (r = sshpkt_get_string(ssh, &sig, &slen)) != 0) fatal("%s: packet parsing: %s", __func__, ssh_err(r)); debug("%s: cuser %s chost %s pkalg %s slen %zu", __func__, cuser, chost, pkalg, slen); #ifdef DEBUG_PK debug("signature:"); sshbuf_dump_data(sig, siglen, stderr); #endif pktype = sshkey_type_from_name(pkalg); if (pktype == KEY_UNSPEC) { /* this is perfectly legal */ logit("%s: unsupported public key algorithm: %s", __func__, pkalg); goto done; } if ((r = sshkey_from_blob(pkblob, blen, &key)) != 0) { error("%s: key_from_blob: %s", __func__, ssh_err(r)); goto done; } if (key == NULL) { error("%s: cannot decode key: %s", __func__, pkalg); goto done; } if (key->type != pktype) { error("%s: type mismatch for decoded key " "(received %d, expected %d)", __func__, key->type, pktype); goto done; } if (sshkey_type_plain(key->type) == KEY_RSA && (ssh->compat & SSH_BUG_RSASIGMD5) != 0) { error("Refusing RSA key because peer uses unsafe " "signature format"); goto done; } if (match_pattern_list(pkalg, options.hostbased_key_types, 0) != 1) { logit("%s: key type %s not in HostbasedAcceptedKeyTypes", __func__, sshkey_type(key)); goto done; } if (!authctxt->valid || authctxt->user == NULL) { debug2("%s: disabled because of invalid user", __func__); goto done; } if ((b = sshbuf_new()) == NULL) fatal("%s: sshbuf_new failed", __func__); /* reconstruct packet */ if ((r = sshbuf_put_string(b, session_id2, session_id2_len)) != 0 || (r = sshbuf_put_u8(b, SSH2_MSG_USERAUTH_REQUEST)) != 0 || (r = sshbuf_put_cstring(b, authctxt->user)) != 0 || (r = sshbuf_put_cstring(b, authctxt->service)) != 0 || (r = sshbuf_put_cstring(b, "hostbased")) != 0 || (r = sshbuf_put_string(b, pkalg, alen)) != 0 || (r = sshbuf_put_string(b, pkblob, blen)) != 0 || (r = sshbuf_put_cstring(b, chost)) != 0 || (r = sshbuf_put_cstring(b, cuser)) != 0) fatal("%s: buffer error: %s", __func__, ssh_err(r)); #ifdef DEBUG_PK sshbuf_dump(b, stderr); #endif auth2_record_info(authctxt, "client user \"%.100s\", client host \"%.100s\"", cuser, chost); /* test for allowed key and correct signature */ authenticated = 0; if (PRIVSEP(hostbased_key_allowed(authctxt->pw, cuser, chost, key)) && PRIVSEP(sshkey_verify(key, sig, slen, sshbuf_ptr(b), sshbuf_len(b), pkalg, ssh->compat)) == 0) authenticated = 1; auth2_record_key(authctxt, authenticated, key); sshbuf_free(b); done: debug2("%s: authenticated %d", __func__, authenticated); sshkey_free(key); free(pkalg); free(pkblob); free(cuser); free(chost); free(sig); return authenticated; } /* return 1 if given hostkey is allowed */ int hostbased_key_allowed(struct passwd *pw, const char *cuser, char *chost, struct sshkey *key) { struct ssh *ssh = active_state; /* XXX */ const char *resolvedname, *ipaddr, *lookup, *reason; HostStatus host_status; int len; char *fp; if (auth_key_is_revoked(key)) return 0; resolvedname = auth_get_canonical_hostname(ssh, options.use_dns); ipaddr = ssh_remote_ipaddr(ssh); debug2("%s: chost %s resolvedname %s ipaddr %s", __func__, chost, resolvedname, ipaddr); if (((len = strlen(chost)) > 0) && chost[len - 1] == '.') { debug2("stripping trailing dot from chost %s", chost); chost[len - 1] = '\0'; } if (options.hostbased_uses_name_from_packet_only) { if (auth_rhosts2(pw, cuser, chost, chost) == 0) { debug2("%s: auth_rhosts2 refused " "user \"%.100s\" host \"%.100s\" (from packet)", __func__, cuser, chost); return 0; } lookup = chost; } else { if (strcasecmp(resolvedname, chost) != 0) logit("userauth_hostbased mismatch: " "client sends %s, but we resolve %s to %s", chost, ipaddr, resolvedname); if (auth_rhosts2(pw, cuser, resolvedname, ipaddr) == 0) { debug2("%s: auth_rhosts2 refused " "user \"%.100s\" host \"%.100s\" addr \"%.100s\"", __func__, cuser, resolvedname, ipaddr); return 0; } lookup = resolvedname; } debug2("%s: access allowed by auth_rhosts2", __func__); if (sshkey_is_cert(key) && sshkey_cert_check_authority(key, 1, 0, lookup, &reason)) { error("%s", reason); auth_debug_add("%s", reason); return 0; } host_status = check_key_in_hostfiles(pw, key, lookup, _PATH_SSH_SYSTEM_HOSTFILE, options.ignore_user_known_hosts ? NULL : _PATH_SSH_USER_HOSTFILE); /* backward compat if no key has been found. */ if (host_status == HOST_NEW) { host_status = check_key_in_hostfiles(pw, key, lookup, _PATH_SSH_SYSTEM_HOSTFILE2, options.ignore_user_known_hosts ? NULL : _PATH_SSH_USER_HOSTFILE2); } if (host_status == HOST_OK) { if (sshkey_is_cert(key)) { if ((fp = sshkey_fingerprint(key->cert->signature_key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) fatal("%s: sshkey_fingerprint fail", __func__); verbose("Accepted certificate ID \"%s\" signed by " "%s CA %s from %s@%s", key->cert->key_id, sshkey_type(key->cert->signature_key), fp, cuser, lookup); } else { if ((fp = sshkey_fingerprint(key, options.fingerprint_hash, SSH_FP_DEFAULT)) == NULL) fatal("%s: sshkey_fingerprint fail", __func__); verbose("Accepted %s public key %s from %s@%s", sshkey_type(key), fp, cuser, lookup); } free(fp); } return (host_status == HOST_OK); } Authmethod method_hostbased = { "hostbased", userauth_hostbased, &options.hostbased_authentication };
./CrossVul/dataset_final_sorted/CWE-200/c/good_295_1
crossvul-cpp_data_good_760_2
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * ROUTE - implementation of the IP router. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Linus Torvalds, <Linus.Torvalds@helsinki.fi> * Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * * Fixes: * Alan Cox : Verify area fixes. * Alan Cox : cli() protects routing changes * Rui Oliveira : ICMP routing table updates * (rco@di.uminho.pt) Routing table insertion and update * Linus Torvalds : Rewrote bits to be sensible * Alan Cox : Added BSD route gw semantics * Alan Cox : Super /proc >4K * Alan Cox : MTU in route table * Alan Cox : MSS actually. Also added the window * clamper. * Sam Lantinga : Fixed route matching in rt_del() * Alan Cox : Routing cache support. * Alan Cox : Removed compatibility cruft. * Alan Cox : RTF_REJECT support. * Alan Cox : TCP irtt support. * Jonathan Naylor : Added Metric support. * Miquel van Smoorenburg : BSD API fixes. * Miquel van Smoorenburg : Metrics. * Alan Cox : Use __u32 properly * Alan Cox : Aligned routing errors more closely with BSD * our system is still very different. * Alan Cox : Faster /proc handling * Alexey Kuznetsov : Massive rework to support tree based routing, * routing caches and better behaviour. * * Olaf Erb : irtt wasn't being copied right. * Bjorn Ekwall : Kerneld route support. * Alan Cox : Multicast fixed (I hope) * Pavel Krauz : Limited broadcast fixed * Mike McLagan : Routing by source * Alexey Kuznetsov : End of old history. Split to fib.c and * route.c and rewritten from scratch. * Andi Kleen : Load-limit warning messages. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Vitaly E. Lavrov : Race condition in ip_route_input_slow. * Tobias Ringstrom : Uninitialized res.type in ip_route_output_slow. * Vladimir V. Ivanov : IP rule info (flowid) is really useful. * Marc Boucher : routing by fwmark * Robert Olsson : Added rt_cache statistics * Arnaldo C. Melo : Convert proc stuff to seq_file * Eric Dumazet : hashed spinlocks and rt_check_expire() fixes. * Ilia Sotnikov : Ignore TOS on PMTUD and Redirect * Ilia Sotnikov : Removed TOS from hash calculations * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) "IPv4: " fmt #include <linux/module.h> #include <linux/uaccess.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/inetdevice.h> #include <linux/igmp.h> #include <linux/pkt_sched.h> #include <linux/mroute.h> #include <linux/netfilter_ipv4.h> #include <linux/random.h> #include <linux/rcupdate.h> #include <linux/times.h> #include <linux/slab.h> #include <linux/jhash.h> #include <net/dst.h> #include <net/dst_metadata.h> #include <net/net_namespace.h> #include <net/protocol.h> #include <net/ip.h> #include <net/route.h> #include <net/inetpeer.h> #include <net/sock.h> #include <net/ip_fib.h> #include <net/arp.h> #include <net/tcp.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/lwtunnel.h> #include <net/netevent.h> #include <net/rtnetlink.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #endif #include <net/secure_seq.h> #include <net/ip_tunnels.h> #include <net/l3mdev.h> #include "fib_lookup.h" #define RT_FL_TOS(oldflp4) \ ((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK)) #define RT_GC_TIMEOUT (300*HZ) static int ip_rt_max_size; static int ip_rt_redirect_number __read_mostly = 9; static int ip_rt_redirect_load __read_mostly = HZ / 50; static int ip_rt_redirect_silence __read_mostly = ((HZ / 50) << (9 + 1)); static int ip_rt_error_cost __read_mostly = HZ; static int ip_rt_error_burst __read_mostly = 5 * HZ; static int ip_rt_mtu_expires __read_mostly = 10 * 60 * HZ; static u32 ip_rt_min_pmtu __read_mostly = 512 + 20 + 20; static int ip_rt_min_advmss __read_mostly = 256; static int ip_rt_gc_timeout __read_mostly = RT_GC_TIMEOUT; /* * Interface to generic destination cache. */ static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie); static unsigned int ipv4_default_advmss(const struct dst_entry *dst); static unsigned int ipv4_mtu(const struct dst_entry *dst); static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst); static void ipv4_link_failure(struct sk_buff *skb); static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu); static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb); static void ipv4_dst_destroy(struct dst_entry *dst); static u32 *ipv4_cow_metrics(struct dst_entry *dst, unsigned long old) { WARN_ON(1); return NULL; } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr); static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr); static struct dst_ops ipv4_dst_ops = { .family = AF_INET, .check = ipv4_dst_check, .default_advmss = ipv4_default_advmss, .mtu = ipv4_mtu, .cow_metrics = ipv4_cow_metrics, .destroy = ipv4_dst_destroy, .negative_advice = ipv4_negative_advice, .link_failure = ipv4_link_failure, .update_pmtu = ip_rt_update_pmtu, .redirect = ip_do_redirect, .local_out = __ip_local_out, .neigh_lookup = ipv4_neigh_lookup, .confirm_neigh = ipv4_confirm_neigh, }; #define ECN_OR_COST(class) TC_PRIO_##class const __u8 ip_tos2prio[16] = { TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK) }; EXPORT_SYMBOL(ip_tos2prio); static DEFINE_PER_CPU(struct rt_cache_stat, rt_cache_stat); #define RT_CACHE_STAT_INC(field) raw_cpu_inc(rt_cache_stat.field) #ifdef CONFIG_PROC_FS static void *rt_cache_seq_start(struct seq_file *seq, loff_t *pos) { if (*pos) return NULL; return SEQ_START_TOKEN; } static void *rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return NULL; } static void rt_cache_seq_stop(struct seq_file *seq, void *v) { } static int rt_cache_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway \tFlags\t\tRefCnt\tUse\t" "Metric\tSource\t\tMTU\tWindow\tIRTT\tTOS\tHHRef\t" "HHUptod\tSpecDst"); return 0; } static const struct seq_operations rt_cache_seq_ops = { .start = rt_cache_seq_start, .next = rt_cache_seq_next, .stop = rt_cache_seq_stop, .show = rt_cache_seq_show, }; static int rt_cache_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cache_seq_ops); } static const struct file_operations rt_cache_seq_fops = { .open = rt_cache_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *rt_cpu_seq_start(struct seq_file *seq, loff_t *pos) { int cpu; if (*pos == 0) return SEQ_START_TOKEN; for (cpu = *pos-1; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void *rt_cpu_seq_next(struct seq_file *seq, void *v, loff_t *pos) { int cpu; for (cpu = *pos; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void rt_cpu_seq_stop(struct seq_file *seq, void *v) { } static int rt_cpu_seq_show(struct seq_file *seq, void *v) { struct rt_cache_stat *st = v; if (v == SEQ_START_TOKEN) { seq_printf(seq, "entries in_hit in_slow_tot in_slow_mc in_no_route in_brd in_martian_dst in_martian_src out_hit out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n"); return 0; } seq_printf(seq,"%08x %08x %08x %08x %08x %08x %08x %08x " " %08x %08x %08x %08x %08x %08x %08x %08x %08x \n", dst_entries_get_slow(&ipv4_dst_ops), 0, /* st->in_hit */ st->in_slow_tot, st->in_slow_mc, st->in_no_route, st->in_brd, st->in_martian_dst, st->in_martian_src, 0, /* st->out_hit */ st->out_slow_tot, st->out_slow_mc, 0, /* st->gc_total */ 0, /* st->gc_ignored */ 0, /* st->gc_goal_miss */ 0, /* st->gc_dst_overflow */ 0, /* st->in_hlist_search */ 0 /* st->out_hlist_search */ ); return 0; } static const struct seq_operations rt_cpu_seq_ops = { .start = rt_cpu_seq_start, .next = rt_cpu_seq_next, .stop = rt_cpu_seq_stop, .show = rt_cpu_seq_show, }; static int rt_cpu_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cpu_seq_ops); } static const struct file_operations rt_cpu_seq_fops = { .open = rt_cpu_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #ifdef CONFIG_IP_ROUTE_CLASSID static int rt_acct_proc_show(struct seq_file *m, void *v) { struct ip_rt_acct *dst, *src; unsigned int i, j; dst = kcalloc(256, sizeof(struct ip_rt_acct), GFP_KERNEL); if (!dst) return -ENOMEM; for_each_possible_cpu(i) { src = (struct ip_rt_acct *)per_cpu_ptr(ip_rt_acct, i); for (j = 0; j < 256; j++) { dst[j].o_bytes += src[j].o_bytes; dst[j].o_packets += src[j].o_packets; dst[j].i_bytes += src[j].i_bytes; dst[j].i_packets += src[j].i_packets; } } seq_write(m, dst, 256 * sizeof(struct ip_rt_acct)); kfree(dst); return 0; } #endif static int __net_init ip_rt_do_proc_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_create("rt_cache", 0444, net->proc_net, &rt_cache_seq_fops); if (!pde) goto err1; pde = proc_create("rt_cache", 0444, net->proc_net_stat, &rt_cpu_seq_fops); if (!pde) goto err2; #ifdef CONFIG_IP_ROUTE_CLASSID pde = proc_create_single("rt_acct", 0, net->proc_net, rt_acct_proc_show); if (!pde) goto err3; #endif return 0; #ifdef CONFIG_IP_ROUTE_CLASSID err3: remove_proc_entry("rt_cache", net->proc_net_stat); #endif err2: remove_proc_entry("rt_cache", net->proc_net); err1: return -ENOMEM; } static void __net_exit ip_rt_do_proc_exit(struct net *net) { remove_proc_entry("rt_cache", net->proc_net_stat); remove_proc_entry("rt_cache", net->proc_net); #ifdef CONFIG_IP_ROUTE_CLASSID remove_proc_entry("rt_acct", net->proc_net); #endif } static struct pernet_operations ip_rt_proc_ops __net_initdata = { .init = ip_rt_do_proc_init, .exit = ip_rt_do_proc_exit, }; static int __init ip_rt_proc_init(void) { return register_pernet_subsys(&ip_rt_proc_ops); } #else static inline int ip_rt_proc_init(void) { return 0; } #endif /* CONFIG_PROC_FS */ static inline bool rt_is_expired(const struct rtable *rth) { return rth->rt_genid != rt_genid_ipv4(dev_net(rth->dst.dev)); } void rt_cache_flush(struct net *net) { rt_genid_bump_ipv4(net); } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr) { struct net_device *dev = dst->dev; const __be32 *pkey = daddr; const struct rtable *rt; struct neighbour *n; rt = (const struct rtable *) dst; if (rt->rt_gateway) pkey = (const __be32 *) &rt->rt_gateway; else if (skb) pkey = &ip_hdr(skb)->daddr; n = __ipv4_neigh_lookup(dev, *(__force u32 *)pkey); if (n) return n; return neigh_create(&arp_tbl, pkey, dev); } static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr) { struct net_device *dev = dst->dev; const __be32 *pkey = daddr; const struct rtable *rt; rt = (const struct rtable *)dst; if (rt->rt_gateway) pkey = (const __be32 *)&rt->rt_gateway; else if (!daddr || (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST | RTCF_LOCAL))) return; __ipv4_confirm_neigh(dev, *(__force u32 *)pkey); } #define IP_IDENTS_SZ 2048u static atomic_t *ip_idents __read_mostly; static u32 *ip_tstamps __read_mostly; /* In order to protect privacy, we add a perturbation to identifiers * if one generator is seldom used. This makes hard for an attacker * to infer how many packets were sent between two points in time. */ u32 ip_idents_reserve(u32 hash, int segs) { u32 *p_tstamp = ip_tstamps + hash % IP_IDENTS_SZ; atomic_t *p_id = ip_idents + hash % IP_IDENTS_SZ; u32 old = READ_ONCE(*p_tstamp); u32 now = (u32)jiffies; u32 new, delta = 0; if (old != now && cmpxchg(p_tstamp, old, now) == old) delta = prandom_u32_max(now - old); /* Do not use atomic_add_return() as it makes UBSAN unhappy */ do { old = (u32)atomic_read(p_id); new = old + delta + segs; } while (atomic_cmpxchg(p_id, old, new) != old); return new - segs; } EXPORT_SYMBOL(ip_idents_reserve); void __ip_select_ident(struct net *net, struct iphdr *iph, int segs) { u32 hash, id; /* Note the following code is not safe, but this is okay. */ if (unlikely(siphash_key_is_zero(&net->ipv4.ip_id_key))) get_random_bytes(&net->ipv4.ip_id_key, sizeof(net->ipv4.ip_id_key)); hash = siphash_3u32((__force u32)iph->daddr, (__force u32)iph->saddr, iph->protocol, &net->ipv4.ip_id_key); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } EXPORT_SYMBOL(__ip_select_ident); static void __build_flow_key(const struct net *net, struct flowi4 *fl4, const struct sock *sk, const struct iphdr *iph, int oif, u8 tos, u8 prot, u32 mark, int flow_flags) { if (sk) { const struct inet_sock *inet = inet_sk(sk); oif = sk->sk_bound_dev_if; mark = sk->sk_mark; tos = RT_CONN_FLAGS(sk); prot = inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol; } flowi4_init_output(fl4, oif, mark, tos, RT_SCOPE_UNIVERSE, prot, flow_flags, iph->daddr, iph->saddr, 0, 0, sock_net_uid(net, sk)); } static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { const struct net *net = dev_net(skb->dev); const struct iphdr *iph = ip_hdr(skb); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; __build_flow_key(net, fl4, sk, iph, oif, tos, prot, mark, 0); } static void build_sk_flow_key(struct flowi4 *fl4, const struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; flowi4_init_output(fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk), daddr, inet->inet_saddr, 0, 0, sk->sk_uid); rcu_read_unlock(); } static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct sk_buff *skb) { if (skb) build_skb_flow_key(fl4, skb, sk); else build_sk_flow_key(fl4, sk); } static DEFINE_SPINLOCK(fnhe_lock); static void fnhe_flush_routes(struct fib_nh_exception *fnhe) { struct rtable *rt; rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL); dst_dev_put(&rt->dst); dst_release(&rt->dst); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); dst_dev_put(&rt->dst); dst_release(&rt->dst); } } static struct fib_nh_exception *fnhe_oldest(struct fnhe_hash_bucket *hash) { struct fib_nh_exception *fnhe, *oldest; oldest = rcu_dereference(hash->chain); for (fnhe = rcu_dereference(oldest->fnhe_next); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (time_before(fnhe->fnhe_stamp, oldest->fnhe_stamp)) oldest = fnhe; } fnhe_flush_routes(oldest); return oldest; } static inline u32 fnhe_hashfun(__be32 daddr) { static u32 fnhe_hashrnd __read_mostly; u32 hval; net_get_random_once(&fnhe_hashrnd, sizeof(fnhe_hashrnd)); hval = jhash_1word((__force u32) daddr, fnhe_hashrnd); return hash_32(hval, FNHE_HASH_SHIFT); } static void fill_route_from_fnhe(struct rtable *rt, struct fib_nh_exception *fnhe) { rt->rt_pmtu = fnhe->fnhe_pmtu; rt->rt_mtu_locked = fnhe->fnhe_mtu_locked; rt->dst.expires = fnhe->fnhe_expires; if (fnhe->fnhe_gw) { rt->rt_flags |= RTCF_REDIRECTED; rt->rt_gateway = fnhe->fnhe_gw; rt->rt_uses_gateway = 1; } } static void update_or_create_fnhe(struct fib_nh *nh, __be32 daddr, __be32 gw, u32 pmtu, bool lock, unsigned long expires) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe; struct rtable *rt; u32 genid, hval; unsigned int i; int depth; genid = fnhe_genid(dev_net(nh->nh_dev)); hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = rcu_dereference(nh->nh_exceptions); if (!hash) { hash = kcalloc(FNHE_HASH_SIZE, sizeof(*hash), GFP_ATOMIC); if (!hash) goto out_unlock; rcu_assign_pointer(nh->nh_exceptions, hash); } hash += hval; depth = 0; for (fnhe = rcu_dereference(hash->chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) break; depth++; } if (fnhe) { if (fnhe->fnhe_genid != genid) fnhe->fnhe_genid = genid; if (gw) fnhe->fnhe_gw = gw; if (pmtu) { fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_mtu_locked = lock; } fnhe->fnhe_expires = max(1UL, expires); /* Update all cached dsts too */ rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) fill_route_from_fnhe(rt, fnhe); rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) fill_route_from_fnhe(rt, fnhe); } else { if (depth > FNHE_RECLAIM_DEPTH) fnhe = fnhe_oldest(hash); else { fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC); if (!fnhe) goto out_unlock; fnhe->fnhe_next = hash->chain; rcu_assign_pointer(hash->chain, fnhe); } fnhe->fnhe_genid = genid; fnhe->fnhe_daddr = daddr; fnhe->fnhe_gw = gw; fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_mtu_locked = lock; fnhe->fnhe_expires = max(1UL, expires); /* Exception created; mark the cached routes for the nexthop * stale, so anyone caching it rechecks if this exception * applies to them. */ rt = rcu_dereference(nh->nh_rth_input); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; for_each_possible_cpu(i) { struct rtable __rcu **prt; prt = per_cpu_ptr(nh->nh_pcpu_rth_output, i); rt = rcu_dereference(*prt); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; } } fnhe->fnhe_stamp = jiffies; out_unlock: spin_unlock_bh(&fnhe_lock); } static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4, bool kill_route) { __be32 new_gw = icmp_hdr(skb)->un.gateway; __be32 old_gw = ip_hdr(skb)->saddr; struct net_device *dev = skb->dev; struct in_device *in_dev; struct fib_result res; struct neighbour *n; struct net *net; switch (icmp_hdr(skb)->code & 7) { case ICMP_REDIR_NET: case ICMP_REDIR_NETTOS: case ICMP_REDIR_HOST: case ICMP_REDIR_HOSTTOS: break; default: return; } if (rt->rt_gateway != old_gw) return; in_dev = __in_dev_get_rcu(dev); if (!in_dev) return; net = dev_net(dev); if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) || ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) || ipv4_is_zeronet(new_gw)) goto reject_redirect; if (!IN_DEV_SHARED_MEDIA(in_dev)) { if (!inet_addr_onlink(in_dev, new_gw, old_gw)) goto reject_redirect; if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev)) goto reject_redirect; } else { if (inet_addr_type(net, new_gw) != RTN_UNICAST) goto reject_redirect; } n = __ipv4_neigh_lookup(rt->dst.dev, new_gw); if (!n) n = neigh_create(&arp_tbl, &new_gw, rt->dst.dev); if (!IS_ERR(n)) { if (!(n->nud_state & NUD_VALID)) { neigh_event_send(n, NULL); } else { if (fib_lookup(net, fl4, &res, 0) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, new_gw, 0, false, jiffies + ip_rt_gc_timeout); } if (kill_route) rt->dst.obsolete = DST_OBSOLETE_KILL; call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n); } neigh_release(n); } return; reject_redirect: #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) { const struct iphdr *iph = (const struct iphdr *) skb->data; __be32 daddr = iph->daddr; __be32 saddr = iph->saddr; net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n" " Advised path = %pI4 -> %pI4\n", &old_gw, dev->name, &new_gw, &saddr, &daddr); } #endif ; } static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { struct rtable *rt; struct flowi4 fl4; const struct iphdr *iph = (const struct iphdr *) skb->data; struct net *net = dev_net(skb->dev); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; rt = (struct rtable *) dst; __build_flow_key(net, &fl4, sk, iph, oif, tos, prot, mark, 0); __ip_do_redirect(rt, skb, &fl4, true); } static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst) { struct rtable *rt = (struct rtable *)dst; struct dst_entry *ret = dst; if (rt) { if (dst->obsolete > 0) { ip_rt_put(rt); ret = NULL; } else if ((rt->rt_flags & RTCF_REDIRECTED) || rt->dst.expires) { ip_rt_put(rt); ret = NULL; } } return ret; } /* * Algorithm: * 1. The first ip_rt_redirect_number redirects are sent * with exponential backoff, then we stop sending them at all, * assuming that the host ignores our redirects. * 2. If we did not see packets requiring redirects * during ip_rt_redirect_silence, we assume that the host * forgot redirected route and start to send redirects again. * * This algorithm is much cheaper and more intelligent than dumb load limiting * in icmp.c. * * NOTE. Do not forget to inhibit load limiting for redirects (redundant) * and "frag. need" (breaks PMTU discovery) in icmp.c. */ void ip_rt_send_redirect(struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct in_device *in_dev; struct inet_peer *peer; struct net *net; int log_martians; int vif; rcu_read_lock(); in_dev = __in_dev_get_rcu(rt->dst.dev); if (!in_dev || !IN_DEV_TX_REDIRECTS(in_dev)) { rcu_read_unlock(); return; } log_martians = IN_DEV_LOG_MARTIANS(in_dev); vif = l3mdev_master_ifindex_rcu(rt->dst.dev); rcu_read_unlock(); net = dev_net(rt->dst.dev); peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, vif, 1); if (!peer) { icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, rt_nexthop(rt, ip_hdr(skb)->daddr)); return; } /* No redirected packets during ip_rt_redirect_silence; * reset the algorithm. */ if (time_after(jiffies, peer->rate_last + ip_rt_redirect_silence)) { peer->rate_tokens = 0; peer->n_redirects = 0; } /* Too many ignored redirects; do not send anything * set dst.rate_last to the last seen redirected packet. */ if (peer->n_redirects >= ip_rt_redirect_number) { peer->rate_last = jiffies; goto out_put_peer; } /* Check for load limit; set rate_last to the latest sent * redirect. */ if (peer->rate_tokens == 0 || time_after(jiffies, (peer->rate_last + (ip_rt_redirect_load << peer->rate_tokens)))) { __be32 gw = rt_nexthop(rt, ip_hdr(skb)->daddr); icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, gw); peer->rate_last = jiffies; ++peer->rate_tokens; ++peer->n_redirects; #ifdef CONFIG_IP_ROUTE_VERBOSE if (log_martians && peer->rate_tokens == ip_rt_redirect_number) net_warn_ratelimited("host %pI4/if%d ignores redirects for %pI4 to %pI4\n", &ip_hdr(skb)->saddr, inet_iif(skb), &ip_hdr(skb)->daddr, &gw); #endif } out_put_peer: inet_putpeer(peer); } static int ip_error(struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct net_device *dev = skb->dev; struct in_device *in_dev; struct inet_peer *peer; unsigned long now; struct net *net; bool send; int code; if (netif_is_l3_master(skb->dev)) { dev = __dev_get_by_index(dev_net(skb->dev), IPCB(skb)->iif); if (!dev) goto out; } in_dev = __in_dev_get_rcu(dev); /* IP on this device is disabled. */ if (!in_dev) goto out; net = dev_net(rt->dst.dev); if (!IN_DEV_FORWARD(in_dev)) { switch (rt->dst.error) { case EHOSTUNREACH: __IP_INC_STATS(net, IPSTATS_MIB_INADDRERRORS); break; case ENETUNREACH: __IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES); break; } goto out; } switch (rt->dst.error) { case EINVAL: default: goto out; case EHOSTUNREACH: code = ICMP_HOST_UNREACH; break; case ENETUNREACH: code = ICMP_NET_UNREACH; __IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES); break; case EACCES: code = ICMP_PKT_FILTERED; break; } peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, l3mdev_master_ifindex(skb->dev), 1); send = true; if (peer) { now = jiffies; peer->rate_tokens += now - peer->rate_last; if (peer->rate_tokens > ip_rt_error_burst) peer->rate_tokens = ip_rt_error_burst; peer->rate_last = now; if (peer->rate_tokens >= ip_rt_error_cost) peer->rate_tokens -= ip_rt_error_cost; else send = false; inet_putpeer(peer); } if (send) icmp_send(skb, ICMP_DEST_UNREACH, code, 0); out: kfree_skb(skb); return 0; } static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu) { struct dst_entry *dst = &rt->dst; u32 old_mtu = ipv4_mtu(dst); struct fib_result res; bool lock = false; if (ip_mtu_locked(dst)) return; if (old_mtu < mtu) return; if (mtu < ip_rt_min_pmtu) { lock = true; mtu = min(old_mtu, ip_rt_min_pmtu); } if (rt->rt_pmtu == mtu && !lock && time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2)) return; rcu_read_lock(); if (fib_lookup(dev_net(dst->dev), fl4, &res, 0) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, 0, mtu, lock, jiffies + ip_rt_mtu_expires); } rcu_read_unlock(); } static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { struct rtable *rt = (struct rtable *) dst; struct flowi4 fl4; ip_rt_build_flow_key(&fl4, sk, skb); __ip_rt_update_pmtu(rt, &fl4, mtu); } void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu, int oif, u8 protocol) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; u32 mark = IP4_REPLY_MARK(net, skb->mark); __build_flow_key(net, &fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, 0); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_update_pmtu); static void __ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(sock_net(sk), &fl4, sk, iph, 0, 0, 0, 0, 0); if (!fl4.flowi4_mark) fl4.flowi4_mark = IP4_REPLY_MARK(sock_net(sk), skb->mark); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; struct dst_entry *odst = NULL; bool new = false; struct net *net = sock_net(sk); bh_lock_sock(sk); if (!ip_sk_accept_pmtu(sk)) goto out; odst = sk_dst_get(sk); if (sock_owned_by_user(sk) || !odst) { __ipv4_sk_update_pmtu(skb, sk, mtu); goto out; } __build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0); rt = (struct rtable *)odst; if (odst->obsolete && !odst->ops->check(odst, 0)) { rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } __ip_rt_update_pmtu((struct rtable *) xfrm_dst_path(&rt->dst), &fl4, mtu); if (!dst_check(&rt->dst, 0)) { if (new) dst_release(&rt->dst); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } if (new) sk_dst_set(sk, &rt->dst); out: bh_unlock_sock(sk); dst_release(odst); } EXPORT_SYMBOL_GPL(ipv4_sk_update_pmtu); void ipv4_redirect(struct sk_buff *skb, struct net *net, int oif, u8 protocol) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(net, &fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, 0, 0); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_redirect); void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; struct net *net = sock_net(sk); __build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_sk_redirect); static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie) { struct rtable *rt = (struct rtable *) dst; /* All IPV4 dsts are created with ->obsolete set to the value * DST_OBSOLETE_FORCE_CHK which forces validation calls down * into this function always. * * When a PMTU/redirect information update invalidates a route, * this is indicated by setting obsolete to DST_OBSOLETE_KILL or * DST_OBSOLETE_DEAD. */ if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt)) return NULL; return dst; } static void ipv4_link_failure(struct sk_buff *skb) { struct rtable *rt; icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); rt = skb_rtable(skb); if (rt) dst_set_expires(&rt->dst, 0); } static int ip_rt_bug(struct net *net, struct sock *sk, struct sk_buff *skb) { pr_debug("%s: %pI4 -> %pI4, %s\n", __func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr, skb->dev ? skb->dev->name : "?"); kfree_skb(skb); WARN_ON(1); return 0; } /* We do not cache source address of outgoing interface, because it is used only by IP RR, TS and SRR options, so that it out of fast path. BTW remember: "addr" is allowed to be not aligned in IP options! */ void ip_rt_get_source(u8 *addr, struct sk_buff *skb, struct rtable *rt) { __be32 src; if (rt_is_output_route(rt)) src = ip_hdr(skb)->saddr; else { struct fib_result res; struct iphdr *iph = ip_hdr(skb); struct flowi4 fl4 = { .daddr = iph->daddr, .saddr = iph->saddr, .flowi4_tos = RT_TOS(iph->tos), .flowi4_oif = rt->dst.dev->ifindex, .flowi4_iif = skb->dev->ifindex, .flowi4_mark = skb->mark, }; rcu_read_lock(); if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res, 0) == 0) src = FIB_RES_PREFSRC(dev_net(rt->dst.dev), res); else src = inet_select_addr(rt->dst.dev, rt_nexthop(rt, iph->daddr), RT_SCOPE_UNIVERSE); rcu_read_unlock(); } memcpy(addr, &src, 4); } #ifdef CONFIG_IP_ROUTE_CLASSID static void set_class_tag(struct rtable *rt, u32 tag) { if (!(rt->dst.tclassid & 0xFFFF)) rt->dst.tclassid |= tag & 0xFFFF; if (!(rt->dst.tclassid & 0xFFFF0000)) rt->dst.tclassid |= tag & 0xFFFF0000; } #endif static unsigned int ipv4_default_advmss(const struct dst_entry *dst) { unsigned int header_size = sizeof(struct tcphdr) + sizeof(struct iphdr); unsigned int advmss = max_t(unsigned int, ipv4_mtu(dst) - header_size, ip_rt_min_advmss); return min(advmss, IPV4_MAX_PMTU - header_size); } static unsigned int ipv4_mtu(const struct dst_entry *dst) { const struct rtable *rt = (const struct rtable *) dst; unsigned int mtu = rt->rt_pmtu; if (!mtu || time_after_eq(jiffies, rt->dst.expires)) mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; mtu = READ_ONCE(dst->dev->mtu); if (unlikely(ip_mtu_locked(dst))) { if (rt->rt_uses_gateway && mtu > 576) mtu = 576; } mtu = min_t(unsigned int, mtu, IP_MAX_MTU); return mtu - lwtunnel_headroom(dst->lwtstate, mtu); } static void ip_del_fnhe(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe, __rcu **fnhe_p; u32 hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = rcu_dereference_protected(nh->nh_exceptions, lockdep_is_held(&fnhe_lock)); hash += hval; fnhe_p = &hash->chain; fnhe = rcu_dereference_protected(*fnhe_p, lockdep_is_held(&fnhe_lock)); while (fnhe) { if (fnhe->fnhe_daddr == daddr) { rcu_assign_pointer(*fnhe_p, rcu_dereference_protected( fnhe->fnhe_next, lockdep_is_held(&fnhe_lock))); /* set fnhe_daddr to 0 to ensure it won't bind with * new dsts in rt_bind_exception(). */ fnhe->fnhe_daddr = 0; fnhe_flush_routes(fnhe); kfree_rcu(fnhe, rcu); break; } fnhe_p = &fnhe->fnhe_next; fnhe = rcu_dereference_protected(fnhe->fnhe_next, lockdep_is_held(&fnhe_lock)); } spin_unlock_bh(&fnhe_lock); } static struct fib_nh_exception *find_exception(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash = rcu_dereference(nh->nh_exceptions); struct fib_nh_exception *fnhe; u32 hval; if (!hash) return NULL; hval = fnhe_hashfun(daddr); for (fnhe = rcu_dereference(hash[hval].chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) { if (fnhe->fnhe_expires && time_after(jiffies, fnhe->fnhe_expires)) { ip_del_fnhe(nh, daddr); break; } return fnhe; } } return NULL; } /* MTU selection: * 1. mtu on route is locked - use it * 2. mtu from nexthop exception * 3. mtu from egress device */ u32 ip_mtu_from_fib_result(struct fib_result *res, __be32 daddr) { struct fib_info *fi = res->fi; struct fib_nh *nh = &fi->fib_nh[res->nh_sel]; struct net_device *dev = nh->nh_dev; u32 mtu = 0; if (dev_net(dev)->ipv4.sysctl_ip_fwd_use_pmtu || fi->fib_metrics->metrics[RTAX_LOCK - 1] & (1 << RTAX_MTU)) mtu = fi->fib_mtu; if (likely(!mtu)) { struct fib_nh_exception *fnhe; fnhe = find_exception(nh, daddr); if (fnhe && !time_after_eq(jiffies, fnhe->fnhe_expires)) mtu = fnhe->fnhe_pmtu; } if (likely(!mtu)) mtu = min(READ_ONCE(dev->mtu), IP_MAX_MTU); return mtu - lwtunnel_headroom(nh->nh_lwtstate, mtu); } static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, __be32 daddr, const bool do_cache) { bool ret = false; spin_lock_bh(&fnhe_lock); if (daddr == fnhe->fnhe_daddr) { struct rtable __rcu **porig; struct rtable *orig; int genid = fnhe_genid(dev_net(rt->dst.dev)); if (rt_is_input_route(rt)) porig = &fnhe->fnhe_rth_input; else porig = &fnhe->fnhe_rth_output; orig = rcu_dereference(*porig); if (fnhe->fnhe_genid != genid) { fnhe->fnhe_genid = genid; fnhe->fnhe_gw = 0; fnhe->fnhe_pmtu = 0; fnhe->fnhe_expires = 0; fnhe->fnhe_mtu_locked = false; fnhe_flush_routes(fnhe); orig = NULL; } fill_route_from_fnhe(rt, fnhe); if (!rt->rt_gateway) rt->rt_gateway = daddr; if (do_cache) { dst_hold(&rt->dst); rcu_assign_pointer(*porig, rt); if (orig) { dst_dev_put(&orig->dst); dst_release(&orig->dst); } ret = true; } fnhe->fnhe_stamp = jiffies; } spin_unlock_bh(&fnhe_lock); return ret; } static bool rt_cache_route(struct fib_nh *nh, struct rtable *rt) { struct rtable *orig, *prev, **p; bool ret = true; if (rt_is_input_route(rt)) { p = (struct rtable **)&nh->nh_rth_input; } else { p = (struct rtable **)raw_cpu_ptr(nh->nh_pcpu_rth_output); } orig = *p; /* hold dst before doing cmpxchg() to avoid race condition * on this dst */ dst_hold(&rt->dst); prev = cmpxchg(p, orig, rt); if (prev == orig) { if (orig) { dst_dev_put(&orig->dst); dst_release(&orig->dst); } } else { dst_release(&rt->dst); ret = false; } return ret; } struct uncached_list { spinlock_t lock; struct list_head head; }; static DEFINE_PER_CPU_ALIGNED(struct uncached_list, rt_uncached_list); void rt_add_uncached_list(struct rtable *rt) { struct uncached_list *ul = raw_cpu_ptr(&rt_uncached_list); rt->rt_uncached_list = ul; spin_lock_bh(&ul->lock); list_add_tail(&rt->rt_uncached, &ul->head); spin_unlock_bh(&ul->lock); } void rt_del_uncached_list(struct rtable *rt) { if (!list_empty(&rt->rt_uncached)) { struct uncached_list *ul = rt->rt_uncached_list; spin_lock_bh(&ul->lock); list_del(&rt->rt_uncached); spin_unlock_bh(&ul->lock); } } static void ipv4_dst_destroy(struct dst_entry *dst) { struct rtable *rt = (struct rtable *)dst; ip_dst_metrics_put(dst); rt_del_uncached_list(rt); } void rt_flush_dev(struct net_device *dev) { struct net *net = dev_net(dev); struct rtable *rt; int cpu; for_each_possible_cpu(cpu) { struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu); spin_lock_bh(&ul->lock); list_for_each_entry(rt, &ul->head, rt_uncached) { if (rt->dst.dev != dev) continue; rt->dst.dev = net->loopback_dev; dev_hold(rt->dst.dev); dev_put(dev); } spin_unlock_bh(&ul->lock); } } static bool rt_cache_valid(const struct rtable *rt) { return rt && rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK && !rt_is_expired(rt); } static void rt_set_nexthop(struct rtable *rt, __be32 daddr, const struct fib_result *res, struct fib_nh_exception *fnhe, struct fib_info *fi, u16 type, u32 itag, const bool do_cache) { bool cached = false; if (fi) { struct fib_nh *nh = &FIB_RES_NH(*res); if (nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK) { rt->rt_gateway = nh->nh_gw; rt->rt_uses_gateway = 1; } ip_dst_init_metrics(&rt->dst, fi->fib_metrics); #ifdef CONFIG_IP_ROUTE_CLASSID rt->dst.tclassid = nh->nh_tclassid; #endif rt->dst.lwtstate = lwtstate_get(nh->nh_lwtstate); if (unlikely(fnhe)) cached = rt_bind_exception(rt, fnhe, daddr, do_cache); else if (do_cache) cached = rt_cache_route(nh, rt); if (unlikely(!cached)) { /* Routes we intend to cache in nexthop exception or * FIB nexthop have the DST_NOCACHE bit clear. * However, if we are unsuccessful at storing this * route into the cache we really need to set it. */ if (!rt->rt_gateway) rt->rt_gateway = daddr; rt_add_uncached_list(rt); } } else rt_add_uncached_list(rt); #ifdef CONFIG_IP_ROUTE_CLASSID #ifdef CONFIG_IP_MULTIPLE_TABLES set_class_tag(rt, res->tclassid); #endif set_class_tag(rt, itag); #endif } struct rtable *rt_dst_alloc(struct net_device *dev, unsigned int flags, u16 type, bool nopolicy, bool noxfrm, bool will_cache) { struct rtable *rt; rt = dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK, (will_cache ? 0 : DST_HOST) | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 0)); if (rt) { rt->rt_genid = rt_genid_ipv4(dev_net(dev)); rt->rt_flags = flags; rt->rt_type = type; rt->rt_is_input = 0; rt->rt_iif = 0; rt->rt_pmtu = 0; rt->rt_mtu_locked = 0; rt->rt_gateway = 0; rt->rt_uses_gateway = 0; INIT_LIST_HEAD(&rt->rt_uncached); rt->dst.output = ip_output; if (flags & RTCF_LOCAL) rt->dst.input = ip_local_deliver; } return rt; } EXPORT_SYMBOL(rt_dst_alloc); /* called in rcu_read_lock() section */ int ip_mc_validate_source(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct in_device *in_dev, u32 *itag) { int err; /* Primary sanity checks. */ if (!in_dev) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) return -EINVAL; if (ipv4_is_loopback(saddr) && !IN_DEV_ROUTE_LOCALNET(in_dev)) return -EINVAL; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr) && ip_hdr(skb)->protocol != IPPROTO_IGMP) return -EINVAL; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, itag); if (err < 0) return err; } return 0; } /* called in rcu_read_lock() section */ static int ip_route_input_mc(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, int our) { struct in_device *in_dev = __in_dev_get_rcu(dev); unsigned int flags = RTCF_MULTICAST; struct rtable *rth; u32 itag = 0; int err; err = ip_mc_validate_source(skb, daddr, saddr, tos, dev, in_dev, &itag); if (err) return err; if (our) flags |= RTCF_LOCAL; rth = rt_dst_alloc(dev_net(dev)->loopback_dev, flags, RTN_MULTICAST, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false); if (!rth) return -ENOBUFS; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->dst.output = ip_rt_bug; rth->rt_is_input= 1; #ifdef CONFIG_IP_MROUTE if (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) rth->dst.input = ip_mr_input; #endif RT_CACHE_STAT_INC(in_slow_mc); skb_dst_set(skb, &rth->dst); return 0; } static void ip_handle_martian_source(struct net_device *dev, struct in_device *in_dev, struct sk_buff *skb, __be32 daddr, __be32 saddr) { RT_CACHE_STAT_INC(in_martian_src); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev) && net_ratelimit()) { /* * RFC1812 recommendation, if source is martian, * the only hint is MAC header. */ pr_warn("martian source %pI4 from %pI4, on dev %s\n", &daddr, &saddr, dev->name); if (dev->hard_header_len && skb_mac_header_was_set(skb)) { print_hex_dump(KERN_WARNING, "ll header: ", DUMP_PREFIX_OFFSET, 16, 1, skb_mac_header(skb), dev->hard_header_len, false); } } #endif } /* called in rcu_read_lock() section */ static int __mkroute_input(struct sk_buff *skb, const struct fib_result *res, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { struct fib_nh_exception *fnhe; struct rtable *rth; int err; struct in_device *out_dev; bool do_cache; u32 itag = 0; /* get a working reference to the output device */ out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res)); if (!out_dev) { net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n"); return -EINVAL; } err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res), in_dev->dev, in_dev, &itag); if (err < 0) { ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr, saddr); goto cleanup; } do_cache = res->fi && !itag; if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) && skb->protocol == htons(ETH_P_IP) && (IN_DEV_SHARED_MEDIA(out_dev) || inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) IPCB(skb)->flags |= IPSKB_DOREDIRECT; if (skb->protocol != htons(ETH_P_IP)) { /* Not IP (i.e. ARP). Do not create route, if it is * invalid for proxy arp. DNAT routes are always valid. * * Proxy arp feature have been extended to allow, ARP * replies back to the same interface, to support * Private VLAN switch technologies. See arp.c. */ if (out_dev == in_dev && IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) { err = -EINVAL; goto cleanup; } } fnhe = find_exception(&FIB_RES_NH(*res), daddr); if (do_cache) { if (fnhe) rth = rcu_dereference(fnhe->fnhe_rth_input); else rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); goto out; } } rth = rt_dst_alloc(out_dev->dev, 0, res->type, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache); if (!rth) { err = -ENOBUFS; goto cleanup; } rth->rt_is_input = 1; RT_CACHE_STAT_INC(in_slow_tot); rth->dst.input = ip_forward; rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag, do_cache); lwtunnel_set_redirect(&rth->dst); skb_dst_set(skb, &rth->dst); out: err = 0; cleanup: return err; } #ifdef CONFIG_IP_ROUTE_MULTIPATH /* To make ICMP packets follow the right flow, the multipath hash is * calculated from the inner IP addresses. */ static void ip_multipath_l3_keys(const struct sk_buff *skb, struct flow_keys *hash_keys) { const struct iphdr *outer_iph = ip_hdr(skb); const struct iphdr *key_iph = outer_iph; const struct iphdr *inner_iph; const struct icmphdr *icmph; struct iphdr _inner_iph; struct icmphdr _icmph; if (likely(outer_iph->protocol != IPPROTO_ICMP)) goto out; if (unlikely((outer_iph->frag_off & htons(IP_OFFSET)) != 0)) goto out; icmph = skb_header_pointer(skb, outer_iph->ihl * 4, sizeof(_icmph), &_icmph); if (!icmph) goto out; if (icmph->type != ICMP_DEST_UNREACH && icmph->type != ICMP_REDIRECT && icmph->type != ICMP_TIME_EXCEEDED && icmph->type != ICMP_PARAMETERPROB) goto out; inner_iph = skb_header_pointer(skb, outer_iph->ihl * 4 + sizeof(_icmph), sizeof(_inner_iph), &_inner_iph); if (!inner_iph) goto out; key_iph = inner_iph; out: hash_keys->addrs.v4addrs.src = key_iph->saddr; hash_keys->addrs.v4addrs.dst = key_iph->daddr; } /* if skb is set it will be used and fl4 can be NULL */ int fib_multipath_hash(const struct net *net, const struct flowi4 *fl4, const struct sk_buff *skb, struct flow_keys *flkeys) { u32 multipath_hash = fl4 ? fl4->flowi4_multipath_hash : 0; struct flow_keys hash_keys; u32 mhash; switch (net->ipv4.sysctl_fib_multipath_hash_policy) { case 0: memset(&hash_keys, 0, sizeof(hash_keys)); hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; if (skb) { ip_multipath_l3_keys(skb, &hash_keys); } else { hash_keys.addrs.v4addrs.src = fl4->saddr; hash_keys.addrs.v4addrs.dst = fl4->daddr; } break; case 1: /* skb is currently provided only when forwarding */ if (skb) { unsigned int flag = FLOW_DISSECTOR_F_STOP_AT_ENCAP; struct flow_keys keys; /* short-circuit if we already have L4 hash present */ if (skb->l4_hash) return skb_get_hash_raw(skb) >> 1; memset(&hash_keys, 0, sizeof(hash_keys)); if (!flkeys) { skb_flow_dissect_flow_keys(skb, &keys, flag); flkeys = &keys; } hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; hash_keys.addrs.v4addrs.src = flkeys->addrs.v4addrs.src; hash_keys.addrs.v4addrs.dst = flkeys->addrs.v4addrs.dst; hash_keys.ports.src = flkeys->ports.src; hash_keys.ports.dst = flkeys->ports.dst; hash_keys.basic.ip_proto = flkeys->basic.ip_proto; } else { memset(&hash_keys, 0, sizeof(hash_keys)); hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; hash_keys.addrs.v4addrs.src = fl4->saddr; hash_keys.addrs.v4addrs.dst = fl4->daddr; hash_keys.ports.src = fl4->fl4_sport; hash_keys.ports.dst = fl4->fl4_dport; hash_keys.basic.ip_proto = fl4->flowi4_proto; } break; } mhash = flow_hash_from_keys(&hash_keys); if (multipath_hash) mhash = jhash_2words(mhash, multipath_hash, 0); return mhash >> 1; } #endif /* CONFIG_IP_ROUTE_MULTIPATH */ static int ip_mkroute_input(struct sk_buff *skb, struct fib_result *res, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos, struct flow_keys *hkeys) { #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res->fi && res->fi->fib_nhs > 1) { int h = fib_multipath_hash(res->fi->fib_net, NULL, skb, hkeys); fib_select_multipath(res, h); } #endif /* create a routing cache entry */ return __mkroute_input(skb, res, in_dev, daddr, saddr, tos); } /* * NOTE. We drop all the packets that has local source * addresses, because every properly looped back packet * must have correct destination already attached by output routine. * * Such approach solves two big problems: * 1. Not simplex devices are handled properly. * 2. IP spoofing attempts are filtered with 100% of guarantee. * called with rcu_read_lock() */ static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct fib_result *res) { struct in_device *in_dev = __in_dev_get_rcu(dev); struct flow_keys *flkeys = NULL, _flkeys; struct net *net = dev_net(dev); struct ip_tunnel_info *tun_info; int err = -EINVAL; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; struct flowi4 fl4; bool do_cache; /* IP on this device is disabled. */ if (!in_dev) goto out; /* Check for the most weird martians, which can be not detected by fib_lookup. */ tun_info = skb_tunnel_info(skb); if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX)) fl4.flowi4_tun_key.tun_id = tun_info->key.tun_id; else fl4.flowi4_tun_key.tun_id = 0; skb_dst_drop(skb); if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res->fi = NULL; res->table = NULL; if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0)) goto brd_input; /* Accept zero addresses only to limited broadcast; * I even do not know to fix it or not. Waiting for complains :-) */ if (ipv4_is_zeronet(saddr)) goto martian_source; if (ipv4_is_zeronet(daddr)) goto martian_destination; /* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(), * and call it once if daddr or/and saddr are loopback addresses */ if (ipv4_is_loopback(daddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_destination; } else if (ipv4_is_loopback(saddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_source; } /* * Now we are ready to route packet. */ fl4.flowi4_oif = 0; fl4.flowi4_iif = dev->ifindex; fl4.flowi4_mark = skb->mark; fl4.flowi4_tos = tos; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.flowi4_flags = 0; fl4.daddr = daddr; fl4.saddr = saddr; fl4.flowi4_uid = sock_net_uid(net, NULL); if (fib4_rules_early_flow_dissect(net, skb, &fl4, &_flkeys)) { flkeys = &_flkeys; } else { fl4.flowi4_proto = 0; fl4.fl4_sport = 0; fl4.fl4_dport = 0; } err = fib_lookup(net, &fl4, res, 0); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res->type == RTN_BROADCAST) { if (IN_DEV_BFORWARD(in_dev)) goto make_route; goto brd_input; } if (res->type == RTN_LOCAL) { err = fib_validate_source(skb, saddr, daddr, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res->type != RTN_UNICAST) goto martian_destination; make_route: err = ip_mkroute_input(skb, res, in_dev, daddr, saddr, tos, flkeys); out: return err; brd_input: if (skb->protocol != htons(ETH_P_IP)) goto e_inval; if (!ipv4_is_zeronet(saddr)) { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; } flags |= RTCF_BROADCAST; res->type = RTN_BROADCAST; RT_CACHE_STAT_INC(in_brd); local_input: do_cache = false; if (res->fi) { if (!itag) { rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); err = 0; goto out; } do_cache = true; } } rth = rt_dst_alloc(l3mdev_master_dev_rcu(dev) ? : net->loopback_dev, flags | RTCF_LOCAL, res->type, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_is_input = 1; RT_CACHE_STAT_INC(in_slow_tot); if (res->type == RTN_UNREACHABLE) { rth->dst.input= ip_error; rth->dst.error= -err; rth->rt_flags &= ~RTCF_LOCAL; } if (do_cache) { struct fib_nh *nh = &FIB_RES_NH(*res); rth->dst.lwtstate = lwtstate_get(nh->nh_lwtstate); if (lwtunnel_input_redirect(rth->dst.lwtstate)) { WARN_ON(rth->dst.input == lwtunnel_input); rth->dst.lwtstate->orig_input = rth->dst.input; rth->dst.input = lwtunnel_input; } if (unlikely(!rt_cache_route(nh, rth))) rt_add_uncached_list(rth); } skb_dst_set(skb, &rth->dst); err = 0; goto out; no_route: RT_CACHE_STAT_INC(in_no_route); res->type = RTN_UNREACHABLE; res->fi = NULL; res->table = NULL; goto local_input; /* * Do not cache martian addresses: they should be logged (RFC1812) */ martian_destination: RT_CACHE_STAT_INC(in_martian_dst); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n", &daddr, &saddr, dev->name); #endif e_inval: err = -EINVAL; goto out; e_nobufs: err = -ENOBUFS; goto out; martian_source: ip_handle_martian_source(dev, in_dev, skb, daddr, saddr); goto out; } int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { struct fib_result res; int err; tos &= IPTOS_RT_MASK; rcu_read_lock(); err = ip_route_input_rcu(skb, daddr, saddr, tos, dev, &res); rcu_read_unlock(); return err; } EXPORT_SYMBOL(ip_route_input_noref); /* called with rcu_read_lock held */ int ip_route_input_rcu(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct fib_result *res) { /* Multicast recognition logic is moved from route cache to here. The problem was that too many Ethernet cards have broken/missing hardware multicast filters :-( As result the host on multicasting network acquires a lot of useless route cache entries, sort of SDR messages from all the world. Now we try to get rid of them. Really, provided software IP multicast filter is organized reasonably (at least, hashed), it does not result in a slowdown comparing with route cache reject entries. Note, that multicast routers are not affected, because route cache entry is created eventually. */ if (ipv4_is_multicast(daddr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); int our = 0; int err = -EINVAL; if (!in_dev) return err; our = ip_check_mc_rcu(in_dev, daddr, saddr, ip_hdr(skb)->protocol); /* check l3 master if no match yet */ if (!our && netif_is_l3_slave(dev)) { struct in_device *l3_in_dev; l3_in_dev = __in_dev_get_rcu(skb->dev); if (l3_in_dev) our = ip_check_mc_rcu(l3_in_dev, daddr, saddr, ip_hdr(skb)->protocol); } if (our #ifdef CONFIG_IP_MROUTE || (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) #endif ) { err = ip_route_input_mc(skb, daddr, saddr, tos, dev, our); } return err; } return ip_route_input_slow(skb, daddr, saddr, tos, dev, res); } /* called with rcu_read_lock() */ static struct rtable *__mkroute_output(const struct fib_result *res, const struct flowi4 *fl4, int orig_oif, struct net_device *dev_out, unsigned int flags) { struct fib_info *fi = res->fi; struct fib_nh_exception *fnhe; struct in_device *in_dev; u16 type = res->type; struct rtable *rth; bool do_cache; in_dev = __in_dev_get_rcu(dev_out); if (!in_dev) return ERR_PTR(-EINVAL); if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK) && !netif_is_l3_master(dev_out)) return ERR_PTR(-EINVAL); if (ipv4_is_lbcast(fl4->daddr)) type = RTN_BROADCAST; else if (ipv4_is_multicast(fl4->daddr)) type = RTN_MULTICAST; else if (ipv4_is_zeronet(fl4->daddr)) return ERR_PTR(-EINVAL); if (dev_out->flags & IFF_LOOPBACK) flags |= RTCF_LOCAL; do_cache = true; if (type == RTN_BROADCAST) { flags |= RTCF_BROADCAST | RTCF_LOCAL; fi = NULL; } else if (type == RTN_MULTICAST) { flags |= RTCF_MULTICAST | RTCF_LOCAL; if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr, fl4->flowi4_proto)) flags &= ~RTCF_LOCAL; else do_cache = false; /* If multicast route do not exist use * default one, but do not gateway in this case. * Yes, it is hack. */ if (fi && res->prefixlen < 4) fi = NULL; } else if ((type == RTN_LOCAL) && (orig_oif != 0) && (orig_oif != dev_out->ifindex)) { /* For local routes that require a particular output interface * we do not want to cache the result. Caching the result * causes incorrect behaviour when there are multiple source * addresses on the interface, the end result being that if the * intended recipient is waiting on that interface for the * packet he won't receive it because it will be delivered on * the loopback interface and the IP_PKTINFO ipi_ifindex will * be set to the loopback interface as well. */ do_cache = false; } fnhe = NULL; do_cache &= fi != NULL; if (fi) { struct rtable __rcu **prth; struct fib_nh *nh = &FIB_RES_NH(*res); fnhe = find_exception(nh, fl4->daddr); if (!do_cache) goto add; if (fnhe) { prth = &fnhe->fnhe_rth_output; } else { if (unlikely(fl4->flowi4_flags & FLOWI_FLAG_KNOWN_NH && !(nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK))) { do_cache = false; goto add; } prth = raw_cpu_ptr(nh->nh_pcpu_rth_output); } rth = rcu_dereference(*prth); if (rt_cache_valid(rth) && dst_hold_safe(&rth->dst)) return rth; } add: rth = rt_dst_alloc(dev_out, flags, type, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(in_dev, NOXFRM), do_cache); if (!rth) return ERR_PTR(-ENOBUFS); rth->rt_iif = orig_oif; RT_CACHE_STAT_INC(out_slow_tot); if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { if (flags & RTCF_LOCAL && !(dev_out->flags & IFF_LOOPBACK)) { rth->dst.output = ip_mc_output; RT_CACHE_STAT_INC(out_slow_mc); } #ifdef CONFIG_IP_MROUTE if (type == RTN_MULTICAST) { if (IN_DEV_MFORWARD(in_dev) && !ipv4_is_local_multicast(fl4->daddr)) { rth->dst.input = ip_mr_input; rth->dst.output = ip_mc_output; } } #endif } rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0, do_cache); lwtunnel_set_redirect(&rth->dst); return rth; } /* * Major route resolver routine. */ struct rtable *ip_route_output_key_hash(struct net *net, struct flowi4 *fl4, const struct sk_buff *skb) { __u8 tos = RT_FL_TOS(fl4); struct fib_result res = { .type = RTN_UNSPEC, .fi = NULL, .table = NULL, .tclassid = 0, }; struct rtable *rth; fl4->flowi4_iif = LOOPBACK_IFINDEX; fl4->flowi4_tos = tos & IPTOS_RT_MASK; fl4->flowi4_scope = ((tos & RTO_ONLINK) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE); rcu_read_lock(); rth = ip_route_output_key_hash_rcu(net, fl4, &res, skb); rcu_read_unlock(); return rth; } EXPORT_SYMBOL_GPL(ip_route_output_key_hash); struct rtable *ip_route_output_key_hash_rcu(struct net *net, struct flowi4 *fl4, struct fib_result *res, const struct sk_buff *skb) { struct net_device *dev_out = NULL; int orig_oif = fl4->flowi4_oif; unsigned int flags = 0; struct rtable *rth; int err = -ENETUNREACH; if (fl4->saddr) { rth = ERR_PTR(-EINVAL); if (ipv4_is_multicast(fl4->saddr) || ipv4_is_lbcast(fl4->saddr) || ipv4_is_zeronet(fl4->saddr)) goto out; /* I removed check for oif == dev_out->oif here. It was wrong for two reasons: 1. ip_dev_find(net, saddr) can return wrong iface, if saddr is assigned to multiple interfaces. 2. Moreover, we are allowed to send packets with saddr of another iface. --ANK */ if (fl4->flowi4_oif == 0 && (ipv4_is_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr))) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ dev_out = __ip_dev_find(net, fl4->saddr, false); if (!dev_out) goto out; /* Special hack: user can direct multicasts and limited broadcast via necessary interface without fiddling with IP_MULTICAST_IF or IP_PKTINFO. This hack is not just for fun, it allows vic,vat and friends to work. They bind socket to loopback, set ttl to zero and expect that it will work. From the viewpoint of routing cache they are broken, because we are not allowed to build multicast path with loopback source addr (look, routing cache cannot know, that ttl is zero, so that packet will not leave this host and route is valid). Luckily, this hack is good workaround. */ fl4->flowi4_oif = dev_out->ifindex; goto make_route; } if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ if (!__ip_dev_find(net, fl4->saddr, false)) goto out; } } if (fl4->flowi4_oif) { dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif); rth = ERR_PTR(-ENODEV); if (!dev_out) goto out; /* RACE: Check return value of inet_select_addr instead. */ if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) { rth = ERR_PTR(-ENETUNREACH); goto out; } if (ipv4_is_local_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr) || fl4->flowi4_proto == IPPROTO_IGMP) { if (!fl4->saddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); goto make_route; } if (!fl4->saddr) { if (ipv4_is_multicast(fl4->daddr)) fl4->saddr = inet_select_addr(dev_out, 0, fl4->flowi4_scope); else if (!fl4->daddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_HOST); } } if (!fl4->daddr) { fl4->daddr = fl4->saddr; if (!fl4->daddr) fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK); dev_out = net->loopback_dev; fl4->flowi4_oif = LOOPBACK_IFINDEX; res->type = RTN_LOCAL; flags |= RTCF_LOCAL; goto make_route; } err = fib_lookup(net, fl4, res, 0); if (err) { res->fi = NULL; res->table = NULL; if (fl4->flowi4_oif && (ipv4_is_multicast(fl4->daddr) || !netif_index_is_l3_master(net, fl4->flowi4_oif))) { /* Apparently, routing tables are wrong. Assume, that the destination is on link. WHY? DW. Because we are allowed to send to iface even if it has NO routes and NO assigned addresses. When oif is specified, routing tables are looked up with only one purpose: to catch if destination is gatewayed, rather than direct. Moreover, if MSG_DONTROUTE is set, we send packet, ignoring both routing tables and ifaddr state. --ANK We could make it even if oif is unknown, likely IPv6, but we do not. */ if (fl4->saddr == 0) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); res->type = RTN_UNICAST; goto make_route; } rth = ERR_PTR(err); goto out; } if (res->type == RTN_LOCAL) { if (!fl4->saddr) { if (res->fi->fib_prefsrc) fl4->saddr = res->fi->fib_prefsrc; else fl4->saddr = fl4->daddr; } /* L3 master device is the loopback for that domain */ dev_out = l3mdev_master_dev_rcu(FIB_RES_DEV(*res)) ? : net->loopback_dev; /* make sure orig_oif points to fib result device even * though packet rx/tx happens over loopback or l3mdev */ orig_oif = FIB_RES_OIF(*res); fl4->flowi4_oif = dev_out->ifindex; flags |= RTCF_LOCAL; goto make_route; } fib_select_path(net, res, fl4, skb); dev_out = FIB_RES_DEV(*res); fl4->flowi4_oif = dev_out->ifindex; make_route: rth = __mkroute_output(res, fl4, orig_oif, dev_out, flags); out: return rth; } static struct dst_entry *ipv4_blackhole_dst_check(struct dst_entry *dst, u32 cookie) { return NULL; } static unsigned int ipv4_blackhole_mtu(const struct dst_entry *dst) { unsigned int mtu = dst_metric_raw(dst, RTAX_MTU); return mtu ? : dst->dev->mtu; } static void ipv4_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { } static void ipv4_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { } static u32 *ipv4_rt_blackhole_cow_metrics(struct dst_entry *dst, unsigned long old) { return NULL; } static struct dst_ops ipv4_dst_blackhole_ops = { .family = AF_INET, .check = ipv4_blackhole_dst_check, .mtu = ipv4_blackhole_mtu, .default_advmss = ipv4_default_advmss, .update_pmtu = ipv4_rt_blackhole_update_pmtu, .redirect = ipv4_rt_blackhole_redirect, .cow_metrics = ipv4_rt_blackhole_cow_metrics, .neigh_lookup = ipv4_neigh_lookup, }; struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig) { struct rtable *ort = (struct rtable *) dst_orig; struct rtable *rt; rt = dst_alloc(&ipv4_dst_blackhole_ops, NULL, 1, DST_OBSOLETE_DEAD, 0); if (rt) { struct dst_entry *new = &rt->dst; new->__use = 1; new->input = dst_discard; new->output = dst_discard_out; new->dev = net->loopback_dev; if (new->dev) dev_hold(new->dev); rt->rt_is_input = ort->rt_is_input; rt->rt_iif = ort->rt_iif; rt->rt_pmtu = ort->rt_pmtu; rt->rt_mtu_locked = ort->rt_mtu_locked; rt->rt_genid = rt_genid_ipv4(net); rt->rt_flags = ort->rt_flags; rt->rt_type = ort->rt_type; rt->rt_gateway = ort->rt_gateway; rt->rt_uses_gateway = ort->rt_uses_gateway; INIT_LIST_HEAD(&rt->rt_uncached); } dst_release(dst_orig); return rt ? &rt->dst : ERR_PTR(-ENOMEM); } struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, const struct sock *sk) { struct rtable *rt = __ip_route_output_key(net, flp4); if (IS_ERR(rt)) return rt; if (flp4->flowi4_proto) rt = (struct rtable *)xfrm_lookup_route(net, &rt->dst, flowi4_to_flowi(flp4), sk, 0); return rt; } EXPORT_SYMBOL_GPL(ip_route_output_flow); /* called with rcu_read_lock held */ static int rt_fill_info(struct net *net, __be32 dst, __be32 src, struct rtable *rt, u32 table_id, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq) { struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, RTM_NEWROUTE, sizeof(*r), 0); if (!nlh) return -EMSGSIZE; r = nlmsg_data(nlh); r->rtm_family = AF_INET; r->rtm_dst_len = 32; r->rtm_src_len = 0; r->rtm_tos = fl4->flowi4_tos; r->rtm_table = table_id < 256 ? table_id : RT_TABLE_COMPAT; if (nla_put_u32(skb, RTA_TABLE, table_id)) goto nla_put_failure; r->rtm_type = rt->rt_type; r->rtm_scope = RT_SCOPE_UNIVERSE; r->rtm_protocol = RTPROT_UNSPEC; r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; if (rt->rt_flags & RTCF_NOTIFY) r->rtm_flags |= RTM_F_NOTIFY; if (IPCB(skb)->flags & IPSKB_DOREDIRECT) r->rtm_flags |= RTCF_DOREDIRECT; if (nla_put_in_addr(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_in_addr(skb, RTA_SRC, src)) goto nla_put_failure; } if (rt->dst.dev && nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) goto nla_put_failure; #ifdef CONFIG_IP_ROUTE_CLASSID if (rt->dst.tclassid && nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) goto nla_put_failure; #endif if (!rt_is_input_route(rt) && fl4->saddr != src) { if (nla_put_in_addr(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_in_addr(skb, RTA_GATEWAY, rt->rt_gateway)) goto nla_put_failure; expires = rt->dst.expires; if (expires) { unsigned long now = jiffies; if (time_before(now, expires)) expires -= now; else expires = 0; } memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); if (rt->rt_pmtu && expires) metrics[RTAX_MTU - 1] = rt->rt_pmtu; if (rt->rt_mtu_locked && expires) metrics[RTAX_LOCK - 1] |= BIT(RTAX_MTU); if (rtnetlink_put_metrics(skb, metrics) < 0) goto nla_put_failure; if (fl4->flowi4_mark && nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) goto nla_put_failure; if (!uid_eq(fl4->flowi4_uid, INVALID_UID) && nla_put_u32(skb, RTA_UID, from_kuid_munged(current_user_ns(), fl4->flowi4_uid))) goto nla_put_failure; error = rt->dst.error; if (rt_is_input_route(rt)) { #ifdef CONFIG_IP_MROUTE if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { int err = ipmr_get_route(net, skb, fl4->saddr, fl4->daddr, r, portid); if (err <= 0) { if (err == 0) return 0; goto nla_put_failure; } } else #endif if (nla_put_u32(skb, RTA_IIF, fl4->flowi4_iif)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static struct sk_buff *inet_rtm_getroute_build_skb(__be32 src, __be32 dst, u8 ip_proto, __be16 sport, __be16 dport) { struct sk_buff *skb; struct iphdr *iph; skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) return NULL; /* Reserve room for dummy headers, this skb can pass * through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); skb->protocol = htons(ETH_P_IP); iph = skb_put(skb, sizeof(struct iphdr)); iph->protocol = ip_proto; iph->saddr = src; iph->daddr = dst; iph->version = 0x4; iph->frag_off = 0; iph->ihl = 0x5; skb_set_transport_header(skb, skb->len); switch (iph->protocol) { case IPPROTO_UDP: { struct udphdr *udph; udph = skb_put_zero(skb, sizeof(struct udphdr)); udph->source = sport; udph->dest = dport; udph->len = sizeof(struct udphdr); udph->check = 0; break; } case IPPROTO_TCP: { struct tcphdr *tcph; tcph = skb_put_zero(skb, sizeof(struct tcphdr)); tcph->source = sport; tcph->dest = dport; tcph->doff = sizeof(struct tcphdr) / 4; tcph->rst = 1; tcph->check = ~tcp_v4_check(sizeof(struct tcphdr), src, dst, 0); break; } case IPPROTO_ICMP: { struct icmphdr *icmph; icmph = skb_put_zero(skb, sizeof(struct icmphdr)); icmph->type = ICMP_ECHO; icmph->code = 0; } } return skb; } static int inet_rtm_valid_getroute_req(struct sk_buff *skb, const struct nlmsghdr *nlh, struct nlattr **tb, struct netlink_ext_ack *extack) { struct rtmsg *rtm; int i, err; if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*rtm))) { NL_SET_ERR_MSG(extack, "ipv4: Invalid header for route get request"); return -EINVAL; } if (!netlink_strict_get_check(skb)) return nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); rtm = nlmsg_data(nlh); if ((rtm->rtm_src_len && rtm->rtm_src_len != 32) || (rtm->rtm_dst_len && rtm->rtm_dst_len != 32) || rtm->rtm_table || rtm->rtm_protocol || rtm->rtm_scope || rtm->rtm_type) { NL_SET_ERR_MSG(extack, "ipv4: Invalid values in header for route get request"); return -EINVAL; } if (rtm->rtm_flags & ~(RTM_F_NOTIFY | RTM_F_LOOKUP_TABLE | RTM_F_FIB_MATCH)) { NL_SET_ERR_MSG(extack, "ipv4: Unsupported rtm_flags for route get request"); return -EINVAL; } err = nlmsg_parse_strict(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); if (err) return err; if ((tb[RTA_SRC] && !rtm->rtm_src_len) || (tb[RTA_DST] && !rtm->rtm_dst_len)) { NL_SET_ERR_MSG(extack, "ipv4: rtm_src_len and rtm_dst_len must be 32 for IPv4"); return -EINVAL; } for (i = 0; i <= RTA_MAX; i++) { if (!tb[i]) continue; switch (i) { case RTA_IIF: case RTA_OIF: case RTA_SRC: case RTA_DST: case RTA_IP_PROTO: case RTA_SPORT: case RTA_DPORT: case RTA_MARK: case RTA_UID: break; default: NL_SET_ERR_MSG(extack, "ipv4: Unsupported attribute in route get request"); return -EINVAL; } } return 0; } static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(in_skb->sk); struct nlattr *tb[RTA_MAX+1]; u32 table_id = RT_TABLE_MAIN; __be16 sport = 0, dport = 0; struct fib_result res = {}; u8 ip_proto = IPPROTO_UDP; struct rtable *rt = NULL; struct sk_buff *skb; struct rtmsg *rtm; struct flowi4 fl4 = {}; __be32 dst = 0; __be32 src = 0; kuid_t uid; u32 iif; int err; int mark; err = inet_rtm_valid_getroute_req(in_skb, nlh, tb, extack); if (err < 0) return err; rtm = nlmsg_data(nlh); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; if (tb[RTA_UID]) uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID])); else uid = (iif ? INVALID_UID : current_uid()); if (tb[RTA_IP_PROTO]) { err = rtm_getroute_parse_ip_proto(tb[RTA_IP_PROTO], &ip_proto, AF_INET, extack); if (err) return err; } if (tb[RTA_SPORT]) sport = nla_get_be16(tb[RTA_SPORT]); if (tb[RTA_DPORT]) dport = nla_get_be16(tb[RTA_DPORT]); skb = inet_rtm_getroute_build_skb(src, dst, ip_proto, sport, dport); if (!skb) return -ENOBUFS; fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; fl4.flowi4_uid = uid; if (sport) fl4.fl4_sport = sport; if (dport) fl4.fl4_dport = dport; fl4.flowi4_proto = ip_proto; rcu_read_lock(); if (iif) { struct net_device *dev; dev = dev_get_by_index_rcu(net, iif); if (!dev) { err = -ENODEV; goto errout_rcu; } fl4.flowi4_iif = iif; /* for rt_fill_info */ skb->dev = dev; skb->mark = mark; err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos, dev, &res); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { fl4.flowi4_iif = LOOPBACK_IFINDEX; skb->dev = net->loopback_dev; rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); else skb_dst_set(skb, &rt->dst); } if (err) goto errout_rcu; if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = res.table ? res.table->tb_id : 0; /* reset skb for netlink reply msg */ skb_trim(skb, 0); skb_reset_network_header(skb); skb_reset_transport_header(skb); skb_reset_mac_header(skb); if (rtm->rtm_flags & RTM_F_FIB_MATCH) { if (!res.fi) { err = fib_props[res.type].error; if (!err) err = -EHOSTUNREACH; goto errout_rcu; } err = fib_dump_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, table_id, rt->rt_type, res.prefix, res.prefixlen, fl4.flowi4_tos, res.fi, 0); } else { err = rt_fill_info(net, dst, src, rt, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq); } if (err < 0) goto errout_rcu; rcu_read_unlock(); err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout_free: return err; errout_rcu: rcu_read_unlock(); kfree_skb(skb); goto errout_free; } void ip_rt_multicast_event(struct in_device *in_dev) { rt_cache_flush(dev_net(in_dev->dev)); } #ifdef CONFIG_SYSCTL static int ip_rt_gc_interval __read_mostly = 60 * HZ; static int ip_rt_gc_min_interval __read_mostly = HZ / 2; static int ip_rt_gc_elasticity __read_mostly = 8; static int ip_min_valid_pmtu __read_mostly = IPV4_MIN_MTU; static int ipv4_sysctl_rtcache_flush(struct ctl_table *__ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net *net = (struct net *)__ctl->extra1; if (write) { rt_cache_flush(net); fnhe_genid_bump(net); return 0; } return -EINVAL; } static struct ctl_table ipv4_route_table[] = { { .procname = "gc_thresh", .data = &ipv4_dst_ops.gc_thresh, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_size", .data = &ip_rt_max_size, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { /* Deprecated. Use gc_min_interval_ms */ .procname = "gc_min_interval", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_min_interval_ms", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_ms_jiffies, }, { .procname = "gc_timeout", .data = &ip_rt_gc_timeout, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_interval", .data = &ip_rt_gc_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "redirect_load", .data = &ip_rt_redirect_load, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_number", .data = &ip_rt_redirect_number, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_silence", .data = &ip_rt_redirect_silence, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_cost", .data = &ip_rt_error_cost, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_burst", .data = &ip_rt_error_burst, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "gc_elasticity", .data = &ip_rt_gc_elasticity, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mtu_expires", .data = &ip_rt_mtu_expires, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "min_pmtu", .data = &ip_rt_min_pmtu, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &ip_min_valid_pmtu, }, { .procname = "min_adv_mss", .data = &ip_rt_min_advmss, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; static struct ctl_table ipv4_route_flush_table[] = { { .procname = "flush", .maxlen = sizeof(int), .mode = 0200, .proc_handler = ipv4_sysctl_rtcache_flush, }, { }, }; static __net_init int sysctl_route_net_init(struct net *net) { struct ctl_table *tbl; tbl = ipv4_route_flush_table; if (!net_eq(net, &init_net)) { tbl = kmemdup(tbl, sizeof(ipv4_route_flush_table), GFP_KERNEL); if (!tbl) goto err_dup; /* Don't export sysctls to unprivileged users */ if (net->user_ns != &init_user_ns) tbl[0].procname = NULL; } tbl[0].extra1 = net; net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", tbl); if (!net->ipv4.route_hdr) goto err_reg; return 0; err_reg: if (tbl != ipv4_route_flush_table) kfree(tbl); err_dup: return -ENOMEM; } static __net_exit void sysctl_route_net_exit(struct net *net) { struct ctl_table *tbl; tbl = net->ipv4.route_hdr->ctl_table_arg; unregister_net_sysctl_table(net->ipv4.route_hdr); BUG_ON(tbl == ipv4_route_flush_table); kfree(tbl); } static __net_initdata struct pernet_operations sysctl_route_ops = { .init = sysctl_route_net_init, .exit = sysctl_route_net_exit, }; #endif static __net_init int rt_genid_init(struct net *net) { atomic_set(&net->ipv4.rt_genid, 0); atomic_set(&net->fnhe_genid, 0); atomic_set(&net->ipv4.dev_addr_genid, get_random_int()); return 0; } static __net_initdata struct pernet_operations rt_genid_ops = { .init = rt_genid_init, }; static int __net_init ipv4_inetpeer_init(struct net *net) { struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL); if (!bp) return -ENOMEM; inet_peer_base_init(bp); net->ipv4.peers = bp; return 0; } static void __net_exit ipv4_inetpeer_exit(struct net *net) { struct inet_peer_base *bp = net->ipv4.peers; net->ipv4.peers = NULL; inetpeer_invalidate_tree(bp); kfree(bp); } static __net_initdata struct pernet_operations ipv4_inetpeer_ops = { .init = ipv4_inetpeer_init, .exit = ipv4_inetpeer_exit, }; #ifdef CONFIG_IP_ROUTE_CLASSID struct ip_rt_acct __percpu *ip_rt_acct __read_mostly; #endif /* CONFIG_IP_ROUTE_CLASSID */ int __init ip_rt_init(void) { int cpu; ip_idents = kmalloc_array(IP_IDENTS_SZ, sizeof(*ip_idents), GFP_KERNEL); if (!ip_idents) panic("IP: failed to allocate ip_idents\n"); prandom_bytes(ip_idents, IP_IDENTS_SZ * sizeof(*ip_idents)); ip_tstamps = kcalloc(IP_IDENTS_SZ, sizeof(*ip_tstamps), GFP_KERNEL); if (!ip_tstamps) panic("IP: failed to allocate ip_tstamps\n"); for_each_possible_cpu(cpu) { struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu); INIT_LIST_HEAD(&ul->head); spin_lock_init(&ul->lock); } #ifdef CONFIG_IP_ROUTE_CLASSID ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct)); if (!ip_rt_acct) panic("IP: failed to allocate ip_rt_acct\n"); #endif ipv4_dst_ops.kmem_cachep = kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep; if (dst_entries_init(&ipv4_dst_ops) < 0) panic("IP: failed to allocate ipv4_dst_ops counter\n"); if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0) panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n"); ipv4_dst_ops.gc_thresh = ~0; ip_rt_max_size = INT_MAX; devinet_init(); ip_fib_init(); if (ip_rt_proc_init()) pr_err("Unable to create route proc files\n"); #ifdef CONFIG_XFRM xfrm_init(); xfrm4_init(); #endif rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL, RTNL_FLAG_DOIT_UNLOCKED); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return 0; } #ifdef CONFIG_SYSCTL /* * We really need to sanitize the damn ipv4 init order, then all * this nonsense will go away. */ void __init ip_static_sysctl_init(void) { register_net_sysctl(&init_net, "net/ipv4/route", ipv4_route_table); } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/good_760_2
crossvul-cpp_data_good_4240_2
// SPDX-License-Identifier: GPL-2.0 /* * Kernel internal timers * * Copyright (C) 1991, 1992 Linus Torvalds * * 1997-01-28 Modified by Finn Arne Gangstad to make timers scale better. * * 1997-09-10 Updated NTP code according to technical memorandum Jan '96 * "A Kernel Model for Precision Timekeeping" by Dave Mills * 1998-12-24 Fixed a xtime SMP race (we need the xtime_lock rw spinlock to * serialize accesses to xtime/lost_ticks). * Copyright (C) 1998 Andrea Arcangeli * 1999-03-10 Improved NTP compatibility by Ulrich Windl * 2002-05-31 Move sys_sysinfo here and make its locking sane, Robert Love * 2000-10-05 Implemented scalable SMP per-CPU timer handling. * Copyright (C) 2000, 2001, 2002 Ingo Molnar * Designed by David S. Miller, Alexey Kuznetsov and Ingo Molnar */ #include <linux/kernel_stat.h> #include <linux/export.h> #include <linux/interrupt.h> #include <linux/percpu.h> #include <linux/init.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/pid_namespace.h> #include <linux/notifier.h> #include <linux/thread_info.h> #include <linux/time.h> #include <linux/jiffies.h> #include <linux/posix-timers.h> #include <linux/cpu.h> #include <linux/syscalls.h> #include <linux/delay.h> #include <linux/tick.h> #include <linux/kallsyms.h> #include <linux/irq_work.h> #include <linux/sched/signal.h> #include <linux/sched/sysctl.h> #include <linux/sched/nohz.h> #include <linux/sched/debug.h> #include <linux/slab.h> #include <linux/compat.h> #include <linux/random.h> #include <linux/uaccess.h> #include <asm/unistd.h> #include <asm/div64.h> #include <asm/timex.h> #include <asm/io.h> #include "tick-internal.h" #define CREATE_TRACE_POINTS #include <trace/events/timer.h> __visible u64 jiffies_64 __cacheline_aligned_in_smp = INITIAL_JIFFIES; EXPORT_SYMBOL(jiffies_64); /* * The timer wheel has LVL_DEPTH array levels. Each level provides an array of * LVL_SIZE buckets. Each level is driven by its own clock and therefor each * level has a different granularity. * * The level granularity is: LVL_CLK_DIV ^ lvl * The level clock frequency is: HZ / (LVL_CLK_DIV ^ level) * * The array level of a newly armed timer depends on the relative expiry * time. The farther the expiry time is away the higher the array level and * therefor the granularity becomes. * * Contrary to the original timer wheel implementation, which aims for 'exact' * expiry of the timers, this implementation removes the need for recascading * the timers into the lower array levels. The previous 'classic' timer wheel * implementation of the kernel already violated the 'exact' expiry by adding * slack to the expiry time to provide batched expiration. The granularity * levels provide implicit batching. * * This is an optimization of the original timer wheel implementation for the * majority of the timer wheel use cases: timeouts. The vast majority of * timeout timers (networking, disk I/O ...) are canceled before expiry. If * the timeout expires it indicates that normal operation is disturbed, so it * does not matter much whether the timeout comes with a slight delay. * * The only exception to this are networking timers with a small expiry * time. They rely on the granularity. Those fit into the first wheel level, * which has HZ granularity. * * We don't have cascading anymore. timers with a expiry time above the * capacity of the last wheel level are force expired at the maximum timeout * value of the last wheel level. From data sampling we know that the maximum * value observed is 5 days (network connection tracking), so this should not * be an issue. * * The currently chosen array constants values are a good compromise between * array size and granularity. * * This results in the following granularity and range levels: * * HZ 1000 steps * Level Offset Granularity Range * 0 0 1 ms 0 ms - 63 ms * 1 64 8 ms 64 ms - 511 ms * 2 128 64 ms 512 ms - 4095 ms (512ms - ~4s) * 3 192 512 ms 4096 ms - 32767 ms (~4s - ~32s) * 4 256 4096 ms (~4s) 32768 ms - 262143 ms (~32s - ~4m) * 5 320 32768 ms (~32s) 262144 ms - 2097151 ms (~4m - ~34m) * 6 384 262144 ms (~4m) 2097152 ms - 16777215 ms (~34m - ~4h) * 7 448 2097152 ms (~34m) 16777216 ms - 134217727 ms (~4h - ~1d) * 8 512 16777216 ms (~4h) 134217728 ms - 1073741822 ms (~1d - ~12d) * * HZ 300 * Level Offset Granularity Range * 0 0 3 ms 0 ms - 210 ms * 1 64 26 ms 213 ms - 1703 ms (213ms - ~1s) * 2 128 213 ms 1706 ms - 13650 ms (~1s - ~13s) * 3 192 1706 ms (~1s) 13653 ms - 109223 ms (~13s - ~1m) * 4 256 13653 ms (~13s) 109226 ms - 873810 ms (~1m - ~14m) * 5 320 109226 ms (~1m) 873813 ms - 6990503 ms (~14m - ~1h) * 6 384 873813 ms (~14m) 6990506 ms - 55924050 ms (~1h - ~15h) * 7 448 6990506 ms (~1h) 55924053 ms - 447392423 ms (~15h - ~5d) * 8 512 55924053 ms (~15h) 447392426 ms - 3579139406 ms (~5d - ~41d) * * HZ 250 * Level Offset Granularity Range * 0 0 4 ms 0 ms - 255 ms * 1 64 32 ms 256 ms - 2047 ms (256ms - ~2s) * 2 128 256 ms 2048 ms - 16383 ms (~2s - ~16s) * 3 192 2048 ms (~2s) 16384 ms - 131071 ms (~16s - ~2m) * 4 256 16384 ms (~16s) 131072 ms - 1048575 ms (~2m - ~17m) * 5 320 131072 ms (~2m) 1048576 ms - 8388607 ms (~17m - ~2h) * 6 384 1048576 ms (~17m) 8388608 ms - 67108863 ms (~2h - ~18h) * 7 448 8388608 ms (~2h) 67108864 ms - 536870911 ms (~18h - ~6d) * 8 512 67108864 ms (~18h) 536870912 ms - 4294967288 ms (~6d - ~49d) * * HZ 100 * Level Offset Granularity Range * 0 0 10 ms 0 ms - 630 ms * 1 64 80 ms 640 ms - 5110 ms (640ms - ~5s) * 2 128 640 ms 5120 ms - 40950 ms (~5s - ~40s) * 3 192 5120 ms (~5s) 40960 ms - 327670 ms (~40s - ~5m) * 4 256 40960 ms (~40s) 327680 ms - 2621430 ms (~5m - ~43m) * 5 320 327680 ms (~5m) 2621440 ms - 20971510 ms (~43m - ~5h) * 6 384 2621440 ms (~43m) 20971520 ms - 167772150 ms (~5h - ~1d) * 7 448 20971520 ms (~5h) 167772160 ms - 1342177270 ms (~1d - ~15d) */ /* Clock divisor for the next level */ #define LVL_CLK_SHIFT 3 #define LVL_CLK_DIV (1UL << LVL_CLK_SHIFT) #define LVL_CLK_MASK (LVL_CLK_DIV - 1) #define LVL_SHIFT(n) ((n) * LVL_CLK_SHIFT) #define LVL_GRAN(n) (1UL << LVL_SHIFT(n)) /* * The time start value for each level to select the bucket at enqueue * time. */ #define LVL_START(n) ((LVL_SIZE - 1) << (((n) - 1) * LVL_CLK_SHIFT)) /* Size of each clock level */ #define LVL_BITS 6 #define LVL_SIZE (1UL << LVL_BITS) #define LVL_MASK (LVL_SIZE - 1) #define LVL_OFFS(n) ((n) * LVL_SIZE) /* Level depth */ #if HZ > 100 # define LVL_DEPTH 9 # else # define LVL_DEPTH 8 #endif /* The cutoff (max. capacity of the wheel) */ #define WHEEL_TIMEOUT_CUTOFF (LVL_START(LVL_DEPTH)) #define WHEEL_TIMEOUT_MAX (WHEEL_TIMEOUT_CUTOFF - LVL_GRAN(LVL_DEPTH - 1)) /* * The resulting wheel size. If NOHZ is configured we allocate two * wheels so we have a separate storage for the deferrable timers. */ #define WHEEL_SIZE (LVL_SIZE * LVL_DEPTH) #ifdef CONFIG_NO_HZ_COMMON # define NR_BASES 2 # define BASE_STD 0 # define BASE_DEF 1 #else # define NR_BASES 1 # define BASE_STD 0 # define BASE_DEF 0 #endif struct timer_base { raw_spinlock_t lock; struct timer_list *running_timer; #ifdef CONFIG_PREEMPT_RT spinlock_t expiry_lock; atomic_t timer_waiters; #endif unsigned long clk; unsigned long next_expiry; unsigned int cpu; bool is_idle; bool must_forward_clk; DECLARE_BITMAP(pending_map, WHEEL_SIZE); struct hlist_head vectors[WHEEL_SIZE]; } ____cacheline_aligned; static DEFINE_PER_CPU(struct timer_base, timer_bases[NR_BASES]); #ifdef CONFIG_NO_HZ_COMMON static DEFINE_STATIC_KEY_FALSE(timers_nohz_active); static DEFINE_MUTEX(timer_keys_mutex); static void timer_update_keys(struct work_struct *work); static DECLARE_WORK(timer_update_work, timer_update_keys); #ifdef CONFIG_SMP unsigned int sysctl_timer_migration = 1; DEFINE_STATIC_KEY_FALSE(timers_migration_enabled); static void timers_update_migration(void) { if (sysctl_timer_migration && tick_nohz_active) static_branch_enable(&timers_migration_enabled); else static_branch_disable(&timers_migration_enabled); } #else static inline void timers_update_migration(void) { } #endif /* !CONFIG_SMP */ static void timer_update_keys(struct work_struct *work) { mutex_lock(&timer_keys_mutex); timers_update_migration(); static_branch_enable(&timers_nohz_active); mutex_unlock(&timer_keys_mutex); } void timers_update_nohz(void) { schedule_work(&timer_update_work); } int timer_migration_handler(struct ctl_table *table, int write, void *buffer, size_t *lenp, loff_t *ppos) { int ret; mutex_lock(&timer_keys_mutex); ret = proc_dointvec_minmax(table, write, buffer, lenp, ppos); if (!ret && write) timers_update_migration(); mutex_unlock(&timer_keys_mutex); return ret; } static inline bool is_timers_nohz_active(void) { return static_branch_unlikely(&timers_nohz_active); } #else static inline bool is_timers_nohz_active(void) { return false; } #endif /* NO_HZ_COMMON */ static unsigned long round_jiffies_common(unsigned long j, int cpu, bool force_up) { int rem; unsigned long original = j; /* * We don't want all cpus firing their timers at once hitting the * same lock or cachelines, so we skew each extra cpu with an extra * 3 jiffies. This 3 jiffies came originally from the mm/ code which * already did this. * The skew is done by adding 3*cpunr, then round, then subtract this * extra offset again. */ j += cpu * 3; rem = j % HZ; /* * If the target jiffie is just after a whole second (which can happen * due to delays of the timer irq, long irq off times etc etc) then * we should round down to the whole second, not up. Use 1/4th second * as cutoff for this rounding as an extreme upper bound for this. * But never round down if @force_up is set. */ if (rem < HZ/4 && !force_up) /* round down */ j = j - rem; else /* round up */ j = j - rem + HZ; /* now that we have rounded, subtract the extra skew again */ j -= cpu * 3; /* * Make sure j is still in the future. Otherwise return the * unmodified value. */ return time_is_after_jiffies(j) ? j : original; } /** * __round_jiffies - function to round jiffies to a full second * @j: the time in (absolute) jiffies that should be rounded * @cpu: the processor number on which the timeout will happen * * __round_jiffies() rounds an absolute time in the future (in jiffies) * up or down to (approximately) full seconds. This is useful for timers * for which the exact time they fire does not matter too much, as long as * they fire approximately every X seconds. * * By rounding these timers to whole seconds, all such timers will fire * at the same time, rather than at various times spread out. The goal * of this is to have the CPU wake up less, which saves power. * * The exact rounding is skewed for each processor to avoid all * processors firing at the exact same time, which could lead * to lock contention or spurious cache line bouncing. * * The return value is the rounded version of the @j parameter. */ unsigned long __round_jiffies(unsigned long j, int cpu) { return round_jiffies_common(j, cpu, false); } EXPORT_SYMBOL_GPL(__round_jiffies); /** * __round_jiffies_relative - function to round jiffies to a full second * @j: the time in (relative) jiffies that should be rounded * @cpu: the processor number on which the timeout will happen * * __round_jiffies_relative() rounds a time delta in the future (in jiffies) * up or down to (approximately) full seconds. This is useful for timers * for which the exact time they fire does not matter too much, as long as * they fire approximately every X seconds. * * By rounding these timers to whole seconds, all such timers will fire * at the same time, rather than at various times spread out. The goal * of this is to have the CPU wake up less, which saves power. * * The exact rounding is skewed for each processor to avoid all * processors firing at the exact same time, which could lead * to lock contention or spurious cache line bouncing. * * The return value is the rounded version of the @j parameter. */ unsigned long __round_jiffies_relative(unsigned long j, int cpu) { unsigned long j0 = jiffies; /* Use j0 because jiffies might change while we run */ return round_jiffies_common(j + j0, cpu, false) - j0; } EXPORT_SYMBOL_GPL(__round_jiffies_relative); /** * round_jiffies - function to round jiffies to a full second * @j: the time in (absolute) jiffies that should be rounded * * round_jiffies() rounds an absolute time in the future (in jiffies) * up or down to (approximately) full seconds. This is useful for timers * for which the exact time they fire does not matter too much, as long as * they fire approximately every X seconds. * * By rounding these timers to whole seconds, all such timers will fire * at the same time, rather than at various times spread out. The goal * of this is to have the CPU wake up less, which saves power. * * The return value is the rounded version of the @j parameter. */ unsigned long round_jiffies(unsigned long j) { return round_jiffies_common(j, raw_smp_processor_id(), false); } EXPORT_SYMBOL_GPL(round_jiffies); /** * round_jiffies_relative - function to round jiffies to a full second * @j: the time in (relative) jiffies that should be rounded * * round_jiffies_relative() rounds a time delta in the future (in jiffies) * up or down to (approximately) full seconds. This is useful for timers * for which the exact time they fire does not matter too much, as long as * they fire approximately every X seconds. * * By rounding these timers to whole seconds, all such timers will fire * at the same time, rather than at various times spread out. The goal * of this is to have the CPU wake up less, which saves power. * * The return value is the rounded version of the @j parameter. */ unsigned long round_jiffies_relative(unsigned long j) { return __round_jiffies_relative(j, raw_smp_processor_id()); } EXPORT_SYMBOL_GPL(round_jiffies_relative); /** * __round_jiffies_up - function to round jiffies up to a full second * @j: the time in (absolute) jiffies that should be rounded * @cpu: the processor number on which the timeout will happen * * This is the same as __round_jiffies() except that it will never * round down. This is useful for timeouts for which the exact time * of firing does not matter too much, as long as they don't fire too * early. */ unsigned long __round_jiffies_up(unsigned long j, int cpu) { return round_jiffies_common(j, cpu, true); } EXPORT_SYMBOL_GPL(__round_jiffies_up); /** * __round_jiffies_up_relative - function to round jiffies up to a full second * @j: the time in (relative) jiffies that should be rounded * @cpu: the processor number on which the timeout will happen * * This is the same as __round_jiffies_relative() except that it will never * round down. This is useful for timeouts for which the exact time * of firing does not matter too much, as long as they don't fire too * early. */ unsigned long __round_jiffies_up_relative(unsigned long j, int cpu) { unsigned long j0 = jiffies; /* Use j0 because jiffies might change while we run */ return round_jiffies_common(j + j0, cpu, true) - j0; } EXPORT_SYMBOL_GPL(__round_jiffies_up_relative); /** * round_jiffies_up - function to round jiffies up to a full second * @j: the time in (absolute) jiffies that should be rounded * * This is the same as round_jiffies() except that it will never * round down. This is useful for timeouts for which the exact time * of firing does not matter too much, as long as they don't fire too * early. */ unsigned long round_jiffies_up(unsigned long j) { return round_jiffies_common(j, raw_smp_processor_id(), true); } EXPORT_SYMBOL_GPL(round_jiffies_up); /** * round_jiffies_up_relative - function to round jiffies up to a full second * @j: the time in (relative) jiffies that should be rounded * * This is the same as round_jiffies_relative() except that it will never * round down. This is useful for timeouts for which the exact time * of firing does not matter too much, as long as they don't fire too * early. */ unsigned long round_jiffies_up_relative(unsigned long j) { return __round_jiffies_up_relative(j, raw_smp_processor_id()); } EXPORT_SYMBOL_GPL(round_jiffies_up_relative); static inline unsigned int timer_get_idx(struct timer_list *timer) { return (timer->flags & TIMER_ARRAYMASK) >> TIMER_ARRAYSHIFT; } static inline void timer_set_idx(struct timer_list *timer, unsigned int idx) { timer->flags = (timer->flags & ~TIMER_ARRAYMASK) | idx << TIMER_ARRAYSHIFT; } /* * Helper function to calculate the array index for a given expiry * time. */ static inline unsigned calc_index(unsigned expires, unsigned lvl) { expires = (expires + LVL_GRAN(lvl)) >> LVL_SHIFT(lvl); return LVL_OFFS(lvl) + (expires & LVL_MASK); } static int calc_wheel_index(unsigned long expires, unsigned long clk) { unsigned long delta = expires - clk; unsigned int idx; if (delta < LVL_START(1)) { idx = calc_index(expires, 0); } else if (delta < LVL_START(2)) { idx = calc_index(expires, 1); } else if (delta < LVL_START(3)) { idx = calc_index(expires, 2); } else if (delta < LVL_START(4)) { idx = calc_index(expires, 3); } else if (delta < LVL_START(5)) { idx = calc_index(expires, 4); } else if (delta < LVL_START(6)) { idx = calc_index(expires, 5); } else if (delta < LVL_START(7)) { idx = calc_index(expires, 6); } else if (LVL_DEPTH > 8 && delta < LVL_START(8)) { idx = calc_index(expires, 7); } else if ((long) delta < 0) { idx = clk & LVL_MASK; } else { /* * Force expire obscene large timeouts to expire at the * capacity limit of the wheel. */ if (delta >= WHEEL_TIMEOUT_CUTOFF) expires = clk + WHEEL_TIMEOUT_MAX; idx = calc_index(expires, LVL_DEPTH - 1); } return idx; } /* * Enqueue the timer into the hash bucket, mark it pending in * the bitmap and store the index in the timer flags. */ static void enqueue_timer(struct timer_base *base, struct timer_list *timer, unsigned int idx) { hlist_add_head(&timer->entry, base->vectors + idx); __set_bit(idx, base->pending_map); timer_set_idx(timer, idx); trace_timer_start(timer, timer->expires, timer->flags); } static void __internal_add_timer(struct timer_base *base, struct timer_list *timer) { unsigned int idx; idx = calc_wheel_index(timer->expires, base->clk); enqueue_timer(base, timer, idx); } static void trigger_dyntick_cpu(struct timer_base *base, struct timer_list *timer) { if (!is_timers_nohz_active()) return; /* * TODO: This wants some optimizing similar to the code below, but we * will do that when we switch from push to pull for deferrable timers. */ if (timer->flags & TIMER_DEFERRABLE) { if (tick_nohz_full_cpu(base->cpu)) wake_up_nohz_cpu(base->cpu); return; } /* * We might have to IPI the remote CPU if the base is idle and the * timer is not deferrable. If the other CPU is on the way to idle * then it can't set base->is_idle as we hold the base lock: */ if (!base->is_idle) return; /* Check whether this is the new first expiring timer: */ if (time_after_eq(timer->expires, base->next_expiry)) return; /* * Set the next expiry time and kick the CPU so it can reevaluate the * wheel: */ if (time_before(timer->expires, base->clk)) { /* * Prevent from forward_timer_base() moving the base->clk * backward */ base->next_expiry = base->clk; } else { base->next_expiry = timer->expires; } wake_up_nohz_cpu(base->cpu); } static void internal_add_timer(struct timer_base *base, struct timer_list *timer) { __internal_add_timer(base, timer); trigger_dyntick_cpu(base, timer); } #ifdef CONFIG_DEBUG_OBJECTS_TIMERS static struct debug_obj_descr timer_debug_descr; static void *timer_debug_hint(void *addr) { return ((struct timer_list *) addr)->function; } static bool timer_is_static_object(void *addr) { struct timer_list *timer = addr; return (timer->entry.pprev == NULL && timer->entry.next == TIMER_ENTRY_STATIC); } /* * fixup_init is called when: * - an active object is initialized */ static bool timer_fixup_init(void *addr, enum debug_obj_state state) { struct timer_list *timer = addr; switch (state) { case ODEBUG_STATE_ACTIVE: del_timer_sync(timer); debug_object_init(timer, &timer_debug_descr); return true; default: return false; } } /* Stub timer callback for improperly used timers. */ static void stub_timer(struct timer_list *unused) { WARN_ON(1); } /* * fixup_activate is called when: * - an active object is activated * - an unknown non-static object is activated */ static bool timer_fixup_activate(void *addr, enum debug_obj_state state) { struct timer_list *timer = addr; switch (state) { case ODEBUG_STATE_NOTAVAILABLE: timer_setup(timer, stub_timer, 0); return true; case ODEBUG_STATE_ACTIVE: WARN_ON(1); /* fall through */ default: return false; } } /* * fixup_free is called when: * - an active object is freed */ static bool timer_fixup_free(void *addr, enum debug_obj_state state) { struct timer_list *timer = addr; switch (state) { case ODEBUG_STATE_ACTIVE: del_timer_sync(timer); debug_object_free(timer, &timer_debug_descr); return true; default: return false; } } /* * fixup_assert_init is called when: * - an untracked/uninit-ed object is found */ static bool timer_fixup_assert_init(void *addr, enum debug_obj_state state) { struct timer_list *timer = addr; switch (state) { case ODEBUG_STATE_NOTAVAILABLE: timer_setup(timer, stub_timer, 0); return true; default: return false; } } static struct debug_obj_descr timer_debug_descr = { .name = "timer_list", .debug_hint = timer_debug_hint, .is_static_object = timer_is_static_object, .fixup_init = timer_fixup_init, .fixup_activate = timer_fixup_activate, .fixup_free = timer_fixup_free, .fixup_assert_init = timer_fixup_assert_init, }; static inline void debug_timer_init(struct timer_list *timer) { debug_object_init(timer, &timer_debug_descr); } static inline void debug_timer_activate(struct timer_list *timer) { debug_object_activate(timer, &timer_debug_descr); } static inline void debug_timer_deactivate(struct timer_list *timer) { debug_object_deactivate(timer, &timer_debug_descr); } static inline void debug_timer_free(struct timer_list *timer) { debug_object_free(timer, &timer_debug_descr); } static inline void debug_timer_assert_init(struct timer_list *timer) { debug_object_assert_init(timer, &timer_debug_descr); } static void do_init_timer(struct timer_list *timer, void (*func)(struct timer_list *), unsigned int flags, const char *name, struct lock_class_key *key); void init_timer_on_stack_key(struct timer_list *timer, void (*func)(struct timer_list *), unsigned int flags, const char *name, struct lock_class_key *key) { debug_object_init_on_stack(timer, &timer_debug_descr); do_init_timer(timer, func, flags, name, key); } EXPORT_SYMBOL_GPL(init_timer_on_stack_key); void destroy_timer_on_stack(struct timer_list *timer) { debug_object_free(timer, &timer_debug_descr); } EXPORT_SYMBOL_GPL(destroy_timer_on_stack); #else static inline void debug_timer_init(struct timer_list *timer) { } static inline void debug_timer_activate(struct timer_list *timer) { } static inline void debug_timer_deactivate(struct timer_list *timer) { } static inline void debug_timer_assert_init(struct timer_list *timer) { } #endif static inline void debug_init(struct timer_list *timer) { debug_timer_init(timer); trace_timer_init(timer); } static inline void debug_deactivate(struct timer_list *timer) { debug_timer_deactivate(timer); trace_timer_cancel(timer); } static inline void debug_assert_init(struct timer_list *timer) { debug_timer_assert_init(timer); } static void do_init_timer(struct timer_list *timer, void (*func)(struct timer_list *), unsigned int flags, const char *name, struct lock_class_key *key) { timer->entry.pprev = NULL; timer->function = func; timer->flags = flags | raw_smp_processor_id(); lockdep_init_map(&timer->lockdep_map, name, key, 0); } /** * init_timer_key - initialize a timer * @timer: the timer to be initialized * @func: timer callback function * @flags: timer flags * @name: name of the timer * @key: lockdep class key of the fake lock used for tracking timer * sync lock dependencies * * init_timer_key() must be done to a timer prior calling *any* of the * other timer functions. */ void init_timer_key(struct timer_list *timer, void (*func)(struct timer_list *), unsigned int flags, const char *name, struct lock_class_key *key) { debug_init(timer); do_init_timer(timer, func, flags, name, key); } EXPORT_SYMBOL(init_timer_key); static inline void detach_timer(struct timer_list *timer, bool clear_pending) { struct hlist_node *entry = &timer->entry; debug_deactivate(timer); __hlist_del(entry); if (clear_pending) entry->pprev = NULL; entry->next = LIST_POISON2; } static int detach_if_pending(struct timer_list *timer, struct timer_base *base, bool clear_pending) { unsigned idx = timer_get_idx(timer); if (!timer_pending(timer)) return 0; if (hlist_is_singular_node(&timer->entry, base->vectors + idx)) __clear_bit(idx, base->pending_map); detach_timer(timer, clear_pending); return 1; } static inline struct timer_base *get_timer_cpu_base(u32 tflags, u32 cpu) { struct timer_base *base = per_cpu_ptr(&timer_bases[BASE_STD], cpu); /* * If the timer is deferrable and NO_HZ_COMMON is set then we need * to use the deferrable base. */ if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE)) base = per_cpu_ptr(&timer_bases[BASE_DEF], cpu); return base; } static inline struct timer_base *get_timer_this_cpu_base(u32 tflags) { struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]); /* * If the timer is deferrable and NO_HZ_COMMON is set then we need * to use the deferrable base. */ if (IS_ENABLED(CONFIG_NO_HZ_COMMON) && (tflags & TIMER_DEFERRABLE)) base = this_cpu_ptr(&timer_bases[BASE_DEF]); return base; } static inline struct timer_base *get_timer_base(u32 tflags) { return get_timer_cpu_base(tflags, tflags & TIMER_CPUMASK); } static inline struct timer_base * get_target_base(struct timer_base *base, unsigned tflags) { #if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON) if (static_branch_likely(&timers_migration_enabled) && !(tflags & TIMER_PINNED)) return get_timer_cpu_base(tflags, get_nohz_timer_target()); #endif return get_timer_this_cpu_base(tflags); } static inline void forward_timer_base(struct timer_base *base) { #ifdef CONFIG_NO_HZ_COMMON unsigned long jnow; /* * We only forward the base when we are idle or have just come out of * idle (must_forward_clk logic), and have a delta between base clock * and jiffies. In the common case, run_timers will take care of it. */ if (likely(!base->must_forward_clk)) return; jnow = READ_ONCE(jiffies); base->must_forward_clk = base->is_idle; if ((long)(jnow - base->clk) < 2) return; /* * If the next expiry value is > jiffies, then we fast forward to * jiffies otherwise we forward to the next expiry value. */ if (time_after(base->next_expiry, jnow)) { base->clk = jnow; } else { if (WARN_ON_ONCE(time_before(base->next_expiry, base->clk))) return; base->clk = base->next_expiry; } #endif } /* * We are using hashed locking: Holding per_cpu(timer_bases[x]).lock means * that all timers which are tied to this base are locked, and the base itself * is locked too. * * So __run_timers/migrate_timers can safely modify all timers which could * be found in the base->vectors array. * * When a timer is migrating then the TIMER_MIGRATING flag is set and we need * to wait until the migration is done. */ static struct timer_base *lock_timer_base(struct timer_list *timer, unsigned long *flags) __acquires(timer->base->lock) { for (;;) { struct timer_base *base; u32 tf; /* * We need to use READ_ONCE() here, otherwise the compiler * might re-read @tf between the check for TIMER_MIGRATING * and spin_lock(). */ tf = READ_ONCE(timer->flags); if (!(tf & TIMER_MIGRATING)) { base = get_timer_base(tf); raw_spin_lock_irqsave(&base->lock, *flags); if (timer->flags == tf) return base; raw_spin_unlock_irqrestore(&base->lock, *flags); } cpu_relax(); } } #define MOD_TIMER_PENDING_ONLY 0x01 #define MOD_TIMER_REDUCE 0x02 #define MOD_TIMER_NOTPENDING 0x04 static inline int __mod_timer(struct timer_list *timer, unsigned long expires, unsigned int options) { struct timer_base *base, *new_base; unsigned int idx = UINT_MAX; unsigned long clk = 0, flags; int ret = 0; BUG_ON(!timer->function); /* * This is a common optimization triggered by the networking code - if * the timer is re-modified to have the same timeout or ends up in the * same array bucket then just return: */ if (!(options & MOD_TIMER_NOTPENDING) && timer_pending(timer)) { /* * The downside of this optimization is that it can result in * larger granularity than you would get from adding a new * timer with this expiry. */ long diff = timer->expires - expires; if (!diff) return 1; if (options & MOD_TIMER_REDUCE && diff <= 0) return 1; /* * We lock timer base and calculate the bucket index right * here. If the timer ends up in the same bucket, then we * just update the expiry time and avoid the whole * dequeue/enqueue dance. */ base = lock_timer_base(timer, &flags); forward_timer_base(base); if (timer_pending(timer) && (options & MOD_TIMER_REDUCE) && time_before_eq(timer->expires, expires)) { ret = 1; goto out_unlock; } clk = base->clk; idx = calc_wheel_index(expires, clk); /* * Retrieve and compare the array index of the pending * timer. If it matches set the expiry to the new value so a * subsequent call will exit in the expires check above. */ if (idx == timer_get_idx(timer)) { if (!(options & MOD_TIMER_REDUCE)) timer->expires = expires; else if (time_after(timer->expires, expires)) timer->expires = expires; ret = 1; goto out_unlock; } } else { base = lock_timer_base(timer, &flags); forward_timer_base(base); } ret = detach_if_pending(timer, base, false); if (!ret && (options & MOD_TIMER_PENDING_ONLY)) goto out_unlock; new_base = get_target_base(base, timer->flags); if (base != new_base) { /* * We are trying to schedule the timer on the new base. * However we can't change timer's base while it is running, * otherwise del_timer_sync() can't detect that the timer's * handler yet has not finished. This also guarantees that the * timer is serialized wrt itself. */ if (likely(base->running_timer != timer)) { /* See the comment in lock_timer_base() */ timer->flags |= TIMER_MIGRATING; raw_spin_unlock(&base->lock); base = new_base; raw_spin_lock(&base->lock); WRITE_ONCE(timer->flags, (timer->flags & ~TIMER_BASEMASK) | base->cpu); forward_timer_base(base); } } debug_timer_activate(timer); timer->expires = expires; /* * If 'idx' was calculated above and the base time did not advance * between calculating 'idx' and possibly switching the base, only * enqueue_timer() and trigger_dyntick_cpu() is required. Otherwise * we need to (re)calculate the wheel index via * internal_add_timer(). */ if (idx != UINT_MAX && clk == base->clk) { enqueue_timer(base, timer, idx); trigger_dyntick_cpu(base, timer); } else { internal_add_timer(base, timer); } out_unlock: raw_spin_unlock_irqrestore(&base->lock, flags); return ret; } /** * mod_timer_pending - modify a pending timer's timeout * @timer: the pending timer to be modified * @expires: new timeout in jiffies * * mod_timer_pending() is the same for pending timers as mod_timer(), * but will not re-activate and modify already deleted timers. * * It is useful for unserialized use of timers. */ int mod_timer_pending(struct timer_list *timer, unsigned long expires) { return __mod_timer(timer, expires, MOD_TIMER_PENDING_ONLY); } EXPORT_SYMBOL(mod_timer_pending); /** * mod_timer - modify a timer's timeout * @timer: the timer to be modified * @expires: new timeout in jiffies * * mod_timer() is a more efficient way to update the expire field of an * active timer (if the timer is inactive it will be activated) * * mod_timer(timer, expires) is equivalent to: * * del_timer(timer); timer->expires = expires; add_timer(timer); * * Note that if there are multiple unserialized concurrent users of the * same timer, then mod_timer() is the only safe way to modify the timeout, * since add_timer() cannot modify an already running timer. * * The function returns whether it has modified a pending timer or not. * (ie. mod_timer() of an inactive timer returns 0, mod_timer() of an * active timer returns 1.) */ int mod_timer(struct timer_list *timer, unsigned long expires) { return __mod_timer(timer, expires, 0); } EXPORT_SYMBOL(mod_timer); /** * timer_reduce - Modify a timer's timeout if it would reduce the timeout * @timer: The timer to be modified * @expires: New timeout in jiffies * * timer_reduce() is very similar to mod_timer(), except that it will only * modify a running timer if that would reduce the expiration time (it will * start a timer that isn't running). */ int timer_reduce(struct timer_list *timer, unsigned long expires) { return __mod_timer(timer, expires, MOD_TIMER_REDUCE); } EXPORT_SYMBOL(timer_reduce); /** * add_timer - start a timer * @timer: the timer to be added * * The kernel will do a ->function(@timer) callback from the * timer interrupt at the ->expires point in the future. The * current time is 'jiffies'. * * The timer's ->expires, ->function fields must be set prior calling this * function. * * Timers with an ->expires field in the past will be executed in the next * timer tick. */ void add_timer(struct timer_list *timer) { BUG_ON(timer_pending(timer)); __mod_timer(timer, timer->expires, MOD_TIMER_NOTPENDING); } EXPORT_SYMBOL(add_timer); /** * add_timer_on - start a timer on a particular CPU * @timer: the timer to be added * @cpu: the CPU to start it on * * This is not very scalable on SMP. Double adds are not possible. */ void add_timer_on(struct timer_list *timer, int cpu) { struct timer_base *new_base, *base; unsigned long flags; BUG_ON(timer_pending(timer) || !timer->function); new_base = get_timer_cpu_base(timer->flags, cpu); /* * If @timer was on a different CPU, it should be migrated with the * old base locked to prevent other operations proceeding with the * wrong base locked. See lock_timer_base(). */ base = lock_timer_base(timer, &flags); if (base != new_base) { timer->flags |= TIMER_MIGRATING; raw_spin_unlock(&base->lock); base = new_base; raw_spin_lock(&base->lock); WRITE_ONCE(timer->flags, (timer->flags & ~TIMER_BASEMASK) | cpu); } forward_timer_base(base); debug_timer_activate(timer); internal_add_timer(base, timer); raw_spin_unlock_irqrestore(&base->lock, flags); } EXPORT_SYMBOL_GPL(add_timer_on); /** * del_timer - deactivate a timer. * @timer: the timer to be deactivated * * del_timer() deactivates a timer - this works on both active and inactive * timers. * * The function returns whether it has deactivated a pending timer or not. * (ie. del_timer() of an inactive timer returns 0, del_timer() of an * active timer returns 1.) */ int del_timer(struct timer_list *timer) { struct timer_base *base; unsigned long flags; int ret = 0; debug_assert_init(timer); if (timer_pending(timer)) { base = lock_timer_base(timer, &flags); ret = detach_if_pending(timer, base, true); raw_spin_unlock_irqrestore(&base->lock, flags); } return ret; } EXPORT_SYMBOL(del_timer); /** * try_to_del_timer_sync - Try to deactivate a timer * @timer: timer to delete * * This function tries to deactivate a timer. Upon successful (ret >= 0) * exit the timer is not queued and the handler is not running on any CPU. */ int try_to_del_timer_sync(struct timer_list *timer) { struct timer_base *base; unsigned long flags; int ret = -1; debug_assert_init(timer); base = lock_timer_base(timer, &flags); if (base->running_timer != timer) ret = detach_if_pending(timer, base, true); raw_spin_unlock_irqrestore(&base->lock, flags); return ret; } EXPORT_SYMBOL(try_to_del_timer_sync); #ifdef CONFIG_PREEMPT_RT static __init void timer_base_init_expiry_lock(struct timer_base *base) { spin_lock_init(&base->expiry_lock); } static inline void timer_base_lock_expiry(struct timer_base *base) { spin_lock(&base->expiry_lock); } static inline void timer_base_unlock_expiry(struct timer_base *base) { spin_unlock(&base->expiry_lock); } /* * The counterpart to del_timer_wait_running(). * * If there is a waiter for base->expiry_lock, then it was waiting for the * timer callback to finish. Drop expiry_lock and reaquire it. That allows * the waiter to acquire the lock and make progress. */ static void timer_sync_wait_running(struct timer_base *base) { if (atomic_read(&base->timer_waiters)) { spin_unlock(&base->expiry_lock); spin_lock(&base->expiry_lock); } } /* * This function is called on PREEMPT_RT kernels when the fast path * deletion of a timer failed because the timer callback function was * running. * * This prevents priority inversion, if the softirq thread on a remote CPU * got preempted, and it prevents a life lock when the task which tries to * delete a timer preempted the softirq thread running the timer callback * function. */ static void del_timer_wait_running(struct timer_list *timer) { u32 tf; tf = READ_ONCE(timer->flags); if (!(tf & TIMER_MIGRATING)) { struct timer_base *base = get_timer_base(tf); /* * Mark the base as contended and grab the expiry lock, * which is held by the softirq across the timer * callback. Drop the lock immediately so the softirq can * expire the next timer. In theory the timer could already * be running again, but that's more than unlikely and just * causes another wait loop. */ atomic_inc(&base->timer_waiters); spin_lock_bh(&base->expiry_lock); atomic_dec(&base->timer_waiters); spin_unlock_bh(&base->expiry_lock); } } #else static inline void timer_base_init_expiry_lock(struct timer_base *base) { } static inline void timer_base_lock_expiry(struct timer_base *base) { } static inline void timer_base_unlock_expiry(struct timer_base *base) { } static inline void timer_sync_wait_running(struct timer_base *base) { } static inline void del_timer_wait_running(struct timer_list *timer) { } #endif #if defined(CONFIG_SMP) || defined(CONFIG_PREEMPT_RT) /** * del_timer_sync - deactivate a timer and wait for the handler to finish. * @timer: the timer to be deactivated * * This function only differs from del_timer() on SMP: besides deactivating * the timer it also makes sure the handler has finished executing on other * CPUs. * * Synchronization rules: Callers must prevent restarting of the timer, * otherwise this function is meaningless. It must not be called from * interrupt contexts unless the timer is an irqsafe one. The caller must * not hold locks which would prevent completion of the timer's * handler. The timer's handler must not call add_timer_on(). Upon exit the * timer is not queued and the handler is not running on any CPU. * * Note: For !irqsafe timers, you must not hold locks that are held in * interrupt context while calling this function. Even if the lock has * nothing to do with the timer in question. Here's why:: * * CPU0 CPU1 * ---- ---- * <SOFTIRQ> * call_timer_fn(); * base->running_timer = mytimer; * spin_lock_irq(somelock); * <IRQ> * spin_lock(somelock); * del_timer_sync(mytimer); * while (base->running_timer == mytimer); * * Now del_timer_sync() will never return and never release somelock. * The interrupt on the other CPU is waiting to grab somelock but * it has interrupted the softirq that CPU0 is waiting to finish. * * The function returns whether it has deactivated a pending timer or not. */ int del_timer_sync(struct timer_list *timer) { int ret; #ifdef CONFIG_LOCKDEP unsigned long flags; /* * If lockdep gives a backtrace here, please reference * the synchronization rules above. */ local_irq_save(flags); lock_map_acquire(&timer->lockdep_map); lock_map_release(&timer->lockdep_map); local_irq_restore(flags); #endif /* * don't use it in hardirq context, because it * could lead to deadlock. */ WARN_ON(in_irq() && !(timer->flags & TIMER_IRQSAFE)); do { ret = try_to_del_timer_sync(timer); if (unlikely(ret < 0)) { del_timer_wait_running(timer); cpu_relax(); } } while (ret < 0); return ret; } EXPORT_SYMBOL(del_timer_sync); #endif static void call_timer_fn(struct timer_list *timer, void (*fn)(struct timer_list *), unsigned long baseclk) { int count = preempt_count(); #ifdef CONFIG_LOCKDEP /* * It is permissible to free the timer from inside the * function that is called from it, this we need to take into * account for lockdep too. To avoid bogus "held lock freed" * warnings as well as problems when looking into * timer->lockdep_map, make a copy and use that here. */ struct lockdep_map lockdep_map; lockdep_copy_map(&lockdep_map, &timer->lockdep_map); #endif /* * Couple the lock chain with the lock chain at * del_timer_sync() by acquiring the lock_map around the fn() * call here and in del_timer_sync(). */ lock_map_acquire(&lockdep_map); trace_timer_expire_entry(timer, baseclk); fn(timer); trace_timer_expire_exit(timer); lock_map_release(&lockdep_map); if (count != preempt_count()) { WARN_ONCE(1, "timer: %pS preempt leak: %08x -> %08x\n", fn, count, preempt_count()); /* * Restore the preempt count. That gives us a decent * chance to survive and extract information. If the * callback kept a lock held, bad luck, but not worse * than the BUG() we had. */ preempt_count_set(count); } } static void expire_timers(struct timer_base *base, struct hlist_head *head) { /* * This value is required only for tracing. base->clk was * incremented directly before expire_timers was called. But expiry * is related to the old base->clk value. */ unsigned long baseclk = base->clk - 1; while (!hlist_empty(head)) { struct timer_list *timer; void (*fn)(struct timer_list *); timer = hlist_entry(head->first, struct timer_list, entry); base->running_timer = timer; detach_timer(timer, true); fn = timer->function; if (timer->flags & TIMER_IRQSAFE) { raw_spin_unlock(&base->lock); call_timer_fn(timer, fn, baseclk); base->running_timer = NULL; raw_spin_lock(&base->lock); } else { raw_spin_unlock_irq(&base->lock); call_timer_fn(timer, fn, baseclk); base->running_timer = NULL; timer_sync_wait_running(base); raw_spin_lock_irq(&base->lock); } } } static int __collect_expired_timers(struct timer_base *base, struct hlist_head *heads) { unsigned long clk = base->clk; struct hlist_head *vec; int i, levels = 0; unsigned int idx; for (i = 0; i < LVL_DEPTH; i++) { idx = (clk & LVL_MASK) + i * LVL_SIZE; if (__test_and_clear_bit(idx, base->pending_map)) { vec = base->vectors + idx; hlist_move_list(vec, heads++); levels++; } /* Is it time to look at the next level? */ if (clk & LVL_CLK_MASK) break; /* Shift clock for the next level granularity */ clk >>= LVL_CLK_SHIFT; } return levels; } #ifdef CONFIG_NO_HZ_COMMON /* * Find the next pending bucket of a level. Search from level start (@offset) * + @clk upwards and if nothing there, search from start of the level * (@offset) up to @offset + clk. */ static int next_pending_bucket(struct timer_base *base, unsigned offset, unsigned clk) { unsigned pos, start = offset + clk; unsigned end = offset + LVL_SIZE; pos = find_next_bit(base->pending_map, end, start); if (pos < end) return pos - start; pos = find_next_bit(base->pending_map, start, offset); return pos < start ? pos + LVL_SIZE - start : -1; } /* * Search the first expiring timer in the various clock levels. Caller must * hold base->lock. */ static unsigned long __next_timer_interrupt(struct timer_base *base) { unsigned long clk, next, adj; unsigned lvl, offset = 0; next = base->clk + NEXT_TIMER_MAX_DELTA; clk = base->clk; for (lvl = 0; lvl < LVL_DEPTH; lvl++, offset += LVL_SIZE) { int pos = next_pending_bucket(base, offset, clk & LVL_MASK); if (pos >= 0) { unsigned long tmp = clk + (unsigned long) pos; tmp <<= LVL_SHIFT(lvl); if (time_before(tmp, next)) next = tmp; } /* * Clock for the next level. If the current level clock lower * bits are zero, we look at the next level as is. If not we * need to advance it by one because that's going to be the * next expiring bucket in that level. base->clk is the next * expiring jiffie. So in case of: * * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0 * 0 0 0 0 0 0 * * we have to look at all levels @index 0. With * * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0 * 0 0 0 0 0 2 * * LVL0 has the next expiring bucket @index 2. The upper * levels have the next expiring bucket @index 1. * * In case that the propagation wraps the next level the same * rules apply: * * LVL5 LVL4 LVL3 LVL2 LVL1 LVL0 * 0 0 0 0 F 2 * * So after looking at LVL0 we get: * * LVL5 LVL4 LVL3 LVL2 LVL1 * 0 0 0 1 0 * * So no propagation from LVL1 to LVL2 because that happened * with the add already, but then we need to propagate further * from LVL2 to LVL3. * * So the simple check whether the lower bits of the current * level are 0 or not is sufficient for all cases. */ adj = clk & LVL_CLK_MASK ? 1 : 0; clk >>= LVL_CLK_SHIFT; clk += adj; } return next; } /* * Check, if the next hrtimer event is before the next timer wheel * event: */ static u64 cmp_next_hrtimer_event(u64 basem, u64 expires) { u64 nextevt = hrtimer_get_next_event(); /* * If high resolution timers are enabled * hrtimer_get_next_event() returns KTIME_MAX. */ if (expires <= nextevt) return expires; /* * If the next timer is already expired, return the tick base * time so the tick is fired immediately. */ if (nextevt <= basem) return basem; /* * Round up to the next jiffie. High resolution timers are * off, so the hrtimers are expired in the tick and we need to * make sure that this tick really expires the timer to avoid * a ping pong of the nohz stop code. * * Use DIV_ROUND_UP_ULL to prevent gcc calling __divdi3 */ return DIV_ROUND_UP_ULL(nextevt, TICK_NSEC) * TICK_NSEC; } /** * get_next_timer_interrupt - return the time (clock mono) of the next timer * @basej: base time jiffies * @basem: base time clock monotonic * * Returns the tick aligned clock monotonic time of the next pending * timer or KTIME_MAX if no timer is pending. */ u64 get_next_timer_interrupt(unsigned long basej, u64 basem) { struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]); u64 expires = KTIME_MAX; unsigned long nextevt; bool is_max_delta; /* * Pretend that there is no timer pending if the cpu is offline. * Possible pending timers will be migrated later to an active cpu. */ if (cpu_is_offline(smp_processor_id())) return expires; raw_spin_lock(&base->lock); nextevt = __next_timer_interrupt(base); is_max_delta = (nextevt == base->clk + NEXT_TIMER_MAX_DELTA); base->next_expiry = nextevt; /* * We have a fresh next event. Check whether we can forward the * base. We can only do that when @basej is past base->clk * otherwise we might rewind base->clk. */ if (time_after(basej, base->clk)) { if (time_after(nextevt, basej)) base->clk = basej; else if (time_after(nextevt, base->clk)) base->clk = nextevt; } if (time_before_eq(nextevt, basej)) { expires = basem; base->is_idle = false; } else { if (!is_max_delta) expires = basem + (u64)(nextevt - basej) * TICK_NSEC; /* * If we expect to sleep more than a tick, mark the base idle. * Also the tick is stopped so any added timer must forward * the base clk itself to keep granularity small. This idle * logic is only maintained for the BASE_STD base, deferrable * timers may still see large granularity skew (by design). */ if ((expires - basem) > TICK_NSEC) { base->must_forward_clk = true; base->is_idle = true; } } raw_spin_unlock(&base->lock); return cmp_next_hrtimer_event(basem, expires); } /** * timer_clear_idle - Clear the idle state of the timer base * * Called with interrupts disabled */ void timer_clear_idle(void) { struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]); /* * We do this unlocked. The worst outcome is a remote enqueue sending * a pointless IPI, but taking the lock would just make the window for * sending the IPI a few instructions smaller for the cost of taking * the lock in the exit from idle path. */ base->is_idle = false; } static int collect_expired_timers(struct timer_base *base, struct hlist_head *heads) { unsigned long now = READ_ONCE(jiffies); /* * NOHZ optimization. After a long idle sleep we need to forward the * base to current jiffies. Avoid a loop by searching the bitfield for * the next expiring timer. */ if ((long)(now - base->clk) > 2) { unsigned long next = __next_timer_interrupt(base); /* * If the next timer is ahead of time forward to current * jiffies, otherwise forward to the next expiry time: */ if (time_after(next, now)) { /* * The call site will increment base->clk and then * terminate the expiry loop immediately. */ base->clk = now; return 0; } base->clk = next; } return __collect_expired_timers(base, heads); } #else static inline int collect_expired_timers(struct timer_base *base, struct hlist_head *heads) { return __collect_expired_timers(base, heads); } #endif /* * Called from the timer interrupt handler to charge one tick to the current * process. user_tick is 1 if the tick is user time, 0 for system. */ void update_process_times(int user_tick) { struct task_struct *p = current; /* Note: this timer irq context must be accounted for as well. */ account_process_tick(p, user_tick); run_local_timers(); rcu_sched_clock_irq(user_tick); #ifdef CONFIG_IRQ_WORK if (in_irq()) irq_work_tick(); #endif scheduler_tick(); if (IS_ENABLED(CONFIG_POSIX_TIMERS)) run_posix_cpu_timers(); /* The current CPU might make use of net randoms without receiving IRQs * to renew them often enough. Let's update the net_rand_state from a * non-constant value that's not affine to the number of calls to make * sure it's updated when there's some activity (we don't care in idle). */ this_cpu_add(net_rand_state.s1, rol32(jiffies, 24) + user_tick); } /** * __run_timers - run all expired timers (if any) on this CPU. * @base: the timer vector to be processed. */ static inline void __run_timers(struct timer_base *base) { struct hlist_head heads[LVL_DEPTH]; int levels; if (!time_after_eq(jiffies, base->clk)) return; timer_base_lock_expiry(base); raw_spin_lock_irq(&base->lock); /* * timer_base::must_forward_clk must be cleared before running * timers so that any timer functions that call mod_timer() will * not try to forward the base. Idle tracking / clock forwarding * logic is only used with BASE_STD timers. * * The must_forward_clk flag is cleared unconditionally also for * the deferrable base. The deferrable base is not affected by idle * tracking and never forwarded, so clearing the flag is a NOOP. * * The fact that the deferrable base is never forwarded can cause * large variations in granularity for deferrable timers, but they * can be deferred for long periods due to idle anyway. */ base->must_forward_clk = false; while (time_after_eq(jiffies, base->clk)) { levels = collect_expired_timers(base, heads); base->clk++; while (levels--) expire_timers(base, heads + levels); } raw_spin_unlock_irq(&base->lock); timer_base_unlock_expiry(base); } /* * This function runs timers and the timer-tq in bottom half context. */ static __latent_entropy void run_timer_softirq(struct softirq_action *h) { struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]); __run_timers(base); if (IS_ENABLED(CONFIG_NO_HZ_COMMON)) __run_timers(this_cpu_ptr(&timer_bases[BASE_DEF])); } /* * Called by the local, per-CPU timer interrupt on SMP. */ void run_local_timers(void) { struct timer_base *base = this_cpu_ptr(&timer_bases[BASE_STD]); hrtimer_run_queues(); /* Raise the softirq only if required. */ if (time_before(jiffies, base->clk)) { if (!IS_ENABLED(CONFIG_NO_HZ_COMMON)) return; /* CPU is awake, so check the deferrable base. */ base++; if (time_before(jiffies, base->clk)) return; } raise_softirq(TIMER_SOFTIRQ); } /* * Since schedule_timeout()'s timer is defined on the stack, it must store * the target task on the stack as well. */ struct process_timer { struct timer_list timer; struct task_struct *task; }; static void process_timeout(struct timer_list *t) { struct process_timer *timeout = from_timer(timeout, t, timer); wake_up_process(timeout->task); } /** * schedule_timeout - sleep until timeout * @timeout: timeout value in jiffies * * Make the current task sleep until @timeout jiffies have elapsed. * The function behavior depends on the current task state * (see also set_current_state() description): * * %TASK_RUNNING - the scheduler is called, but the task does not sleep * at all. That happens because sched_submit_work() does nothing for * tasks in %TASK_RUNNING state. * * %TASK_UNINTERRUPTIBLE - at least @timeout jiffies are guaranteed to * pass before the routine returns unless the current task is explicitly * woken up, (e.g. by wake_up_process()). * * %TASK_INTERRUPTIBLE - the routine may return early if a signal is * delivered to the current task or the current task is explicitly woken * up. * * The current task state is guaranteed to be %TASK_RUNNING when this * routine returns. * * Specifying a @timeout value of %MAX_SCHEDULE_TIMEOUT will schedule * the CPU away without a bound on the timeout. In this case the return * value will be %MAX_SCHEDULE_TIMEOUT. * * Returns 0 when the timer has expired otherwise the remaining time in * jiffies will be returned. In all cases the return value is guaranteed * to be non-negative. */ signed long __sched schedule_timeout(signed long timeout) { struct process_timer timer; unsigned long expire; switch (timeout) { case MAX_SCHEDULE_TIMEOUT: /* * These two special cases are useful to be comfortable * in the caller. Nothing more. We could take * MAX_SCHEDULE_TIMEOUT from one of the negative value * but I' d like to return a valid offset (>=0) to allow * the caller to do everything it want with the retval. */ schedule(); goto out; default: /* * Another bit of PARANOID. Note that the retval will be * 0 since no piece of kernel is supposed to do a check * for a negative retval of schedule_timeout() (since it * should never happens anyway). You just have the printk() * that will tell you if something is gone wrong and where. */ if (timeout < 0) { printk(KERN_ERR "schedule_timeout: wrong timeout " "value %lx\n", timeout); dump_stack(); current->state = TASK_RUNNING; goto out; } } expire = timeout + jiffies; timer.task = current; timer_setup_on_stack(&timer.timer, process_timeout, 0); __mod_timer(&timer.timer, expire, MOD_TIMER_NOTPENDING); schedule(); del_singleshot_timer_sync(&timer.timer); /* Remove the timer from the object tracker */ destroy_timer_on_stack(&timer.timer); timeout = expire - jiffies; out: return timeout < 0 ? 0 : timeout; } EXPORT_SYMBOL(schedule_timeout); /* * We can use __set_current_state() here because schedule_timeout() calls * schedule() unconditionally. */ signed long __sched schedule_timeout_interruptible(signed long timeout) { __set_current_state(TASK_INTERRUPTIBLE); return schedule_timeout(timeout); } EXPORT_SYMBOL(schedule_timeout_interruptible); signed long __sched schedule_timeout_killable(signed long timeout) { __set_current_state(TASK_KILLABLE); return schedule_timeout(timeout); } EXPORT_SYMBOL(schedule_timeout_killable); signed long __sched schedule_timeout_uninterruptible(signed long timeout) { __set_current_state(TASK_UNINTERRUPTIBLE); return schedule_timeout(timeout); } EXPORT_SYMBOL(schedule_timeout_uninterruptible); /* * Like schedule_timeout_uninterruptible(), except this task will not contribute * to load average. */ signed long __sched schedule_timeout_idle(signed long timeout) { __set_current_state(TASK_IDLE); return schedule_timeout(timeout); } EXPORT_SYMBOL(schedule_timeout_idle); #ifdef CONFIG_HOTPLUG_CPU static void migrate_timer_list(struct timer_base *new_base, struct hlist_head *head) { struct timer_list *timer; int cpu = new_base->cpu; while (!hlist_empty(head)) { timer = hlist_entry(head->first, struct timer_list, entry); detach_timer(timer, false); timer->flags = (timer->flags & ~TIMER_BASEMASK) | cpu; internal_add_timer(new_base, timer); } } int timers_prepare_cpu(unsigned int cpu) { struct timer_base *base; int b; for (b = 0; b < NR_BASES; b++) { base = per_cpu_ptr(&timer_bases[b], cpu); base->clk = jiffies; base->next_expiry = base->clk + NEXT_TIMER_MAX_DELTA; base->is_idle = false; base->must_forward_clk = true; } return 0; } int timers_dead_cpu(unsigned int cpu) { struct timer_base *old_base; struct timer_base *new_base; int b, i; BUG_ON(cpu_online(cpu)); for (b = 0; b < NR_BASES; b++) { old_base = per_cpu_ptr(&timer_bases[b], cpu); new_base = get_cpu_ptr(&timer_bases[b]); /* * The caller is globally serialized and nobody else * takes two locks at once, deadlock is not possible. */ raw_spin_lock_irq(&new_base->lock); raw_spin_lock_nested(&old_base->lock, SINGLE_DEPTH_NESTING); /* * The current CPUs base clock might be stale. Update it * before moving the timers over. */ forward_timer_base(new_base); BUG_ON(old_base->running_timer); for (i = 0; i < WHEEL_SIZE; i++) migrate_timer_list(new_base, old_base->vectors + i); raw_spin_unlock(&old_base->lock); raw_spin_unlock_irq(&new_base->lock); put_cpu_ptr(&timer_bases); } return 0; } #endif /* CONFIG_HOTPLUG_CPU */ static void __init init_timer_cpu(int cpu) { struct timer_base *base; int i; for (i = 0; i < NR_BASES; i++) { base = per_cpu_ptr(&timer_bases[i], cpu); base->cpu = cpu; raw_spin_lock_init(&base->lock); base->clk = jiffies; timer_base_init_expiry_lock(base); } } static void __init init_timer_cpus(void) { int cpu; for_each_possible_cpu(cpu) init_timer_cpu(cpu); } void __init init_timers(void) { init_timer_cpus(); open_softirq(TIMER_SOFTIRQ, run_timer_softirq); } /** * msleep - sleep safely even with waitqueue interruptions * @msecs: Time in milliseconds to sleep for */ void msleep(unsigned int msecs) { unsigned long timeout = msecs_to_jiffies(msecs) + 1; while (timeout) timeout = schedule_timeout_uninterruptible(timeout); } EXPORT_SYMBOL(msleep); /** * msleep_interruptible - sleep waiting for signals * @msecs: Time in milliseconds to sleep for */ unsigned long msleep_interruptible(unsigned int msecs) { unsigned long timeout = msecs_to_jiffies(msecs) + 1; while (timeout && !signal_pending(current)) timeout = schedule_timeout_interruptible(timeout); return jiffies_to_msecs(timeout); } EXPORT_SYMBOL(msleep_interruptible); /** * usleep_range - Sleep for an approximate time * @min: Minimum time in usecs to sleep * @max: Maximum time in usecs to sleep * * In non-atomic context where the exact wakeup time is flexible, use * usleep_range() instead of udelay(). The sleep improves responsiveness * by avoiding the CPU-hogging busy-wait of udelay(), and the range reduces * power usage by allowing hrtimers to take advantage of an already- * scheduled interrupt instead of scheduling a new one just for this sleep. */ void __sched usleep_range(unsigned long min, unsigned long max) { ktime_t exp = ktime_add_us(ktime_get(), min); u64 delta = (u64)(max - min) * NSEC_PER_USEC; for (;;) { __set_current_state(TASK_UNINTERRUPTIBLE); /* Do not return before the requested sleep time has elapsed */ if (!schedule_hrtimeout_range(&exp, delta, HRTIMER_MODE_ABS)) break; } } EXPORT_SYMBOL(usleep_range);
./CrossVul/dataset_final_sorted/CWE-200/c/good_4240_2
crossvul-cpp_data_good_2853_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % GGGG IIIII FFFFF % % G I F % % G GG I FFF % % G G I F % % GGG IIIII F % % % % % % Read/Write Compuserv Graphics Interchange Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % */ /* Include declarations. */ #include "MagickCore/studio.h" #include "MagickCore/attribute.h" #include "MagickCore/blob.h" #include "MagickCore/blob-private.h" #include "MagickCore/cache.h" #include "MagickCore/color.h" #include "MagickCore/color-private.h" #include "MagickCore/colormap.h" #include "MagickCore/colormap-private.h" #include "MagickCore/colorspace.h" #include "MagickCore/colorspace-private.h" #include "MagickCore/exception.h" #include "MagickCore/exception-private.h" #include "MagickCore/image.h" #include "MagickCore/image-private.h" #include "MagickCore/list.h" #include "MagickCore/profile.h" #include "MagickCore/magick.h" #include "MagickCore/memory_.h" #include "MagickCore/monitor.h" #include "MagickCore/monitor-private.h" #include "MagickCore/option.h" #include "MagickCore/pixel.h" #include "MagickCore/pixel-accessor.h" #include "MagickCore/property.h" #include "MagickCore/quantize.h" #include "MagickCore/quantum-private.h" #include "MagickCore/static.h" #include "MagickCore/string_.h" #include "MagickCore/string-private.h" #include "MagickCore/module.h" /* Define declarations. */ #define MaximumLZWBits 12 #define MaximumLZWCode (1UL << MaximumLZWBits) /* Typdef declarations. */ typedef struct _LZWCodeInfo { unsigned char buffer[280]; size_t count, bit; MagickBooleanType eof; } LZWCodeInfo; typedef struct _LZWStack { size_t *codes, *index, *top; } LZWStack; typedef struct _LZWInfo { Image *image; LZWStack *stack; MagickBooleanType genesis; size_t data_size, maximum_data_value, clear_code, end_code, bits, first_code, last_code, maximum_code, slot, *table[2]; LZWCodeInfo code_info; } LZWInfo; /* Forward declarations. */ static inline int GetNextLZWCode(LZWInfo *,const size_t); static MagickBooleanType WriteGIFImage(const ImageInfo *,Image *,ExceptionInfo *); static ssize_t ReadBlobBlock(Image *,unsigned char *); /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % D e c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % DecodeImage uncompresses an image via GIF-coding. % % The format of the DecodeImage method is: % % MagickBooleanType DecodeImage(Image *image,const ssize_t opacity) % % A description of each parameter follows: % % o image: the address of a structure of type Image. % % o opacity: The colormap index associated with the transparent color. % */ static LZWInfo *RelinquishLZWInfo(LZWInfo *lzw_info) { if (lzw_info->table[0] != (size_t *) NULL) lzw_info->table[0]=(size_t *) RelinquishMagickMemory( lzw_info->table[0]); if (lzw_info->table[1] != (size_t *) NULL) lzw_info->table[1]=(size_t *) RelinquishMagickMemory( lzw_info->table[1]); if (lzw_info->stack != (LZWStack *) NULL) { if (lzw_info->stack->codes != (size_t *) NULL) lzw_info->stack->codes=(size_t *) RelinquishMagickMemory( lzw_info->stack->codes); lzw_info->stack=(LZWStack *) RelinquishMagickMemory(lzw_info->stack); } lzw_info=(LZWInfo *) RelinquishMagickMemory(lzw_info); return((LZWInfo *) NULL); } static inline void ResetLZWInfo(LZWInfo *lzw_info) { size_t one; lzw_info->bits=lzw_info->data_size+1; one=1; lzw_info->maximum_code=one << lzw_info->bits; lzw_info->slot=lzw_info->maximum_data_value+3; lzw_info->genesis=MagickTrue; } static LZWInfo *AcquireLZWInfo(Image *image,const size_t data_size) { LZWInfo *lzw_info; register ssize_t i; size_t one; lzw_info=(LZWInfo *) AcquireMagickMemory(sizeof(*lzw_info)); if (lzw_info == (LZWInfo *) NULL) return((LZWInfo *) NULL); (void) ResetMagickMemory(lzw_info,0,sizeof(*lzw_info)); lzw_info->image=image; lzw_info->data_size=data_size; one=1; lzw_info->maximum_data_value=(one << data_size)-1; lzw_info->clear_code=lzw_info->maximum_data_value+1; lzw_info->end_code=lzw_info->maximum_data_value+2; lzw_info->table[0]=(size_t *) AcquireQuantumMemory(MaximumLZWCode, sizeof(**lzw_info->table)); lzw_info->table[1]=(size_t *) AcquireQuantumMemory(MaximumLZWCode, sizeof(**lzw_info->table)); if ((lzw_info->table[0] == (size_t *) NULL) || (lzw_info->table[1] == (size_t *) NULL)) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } for (i=0; i <= (ssize_t) lzw_info->maximum_data_value; i++) { lzw_info->table[0][i]=0; lzw_info->table[1][i]=(size_t) i; } ResetLZWInfo(lzw_info); lzw_info->code_info.buffer[0]='\0'; lzw_info->code_info.buffer[1]='\0'; lzw_info->code_info.count=2; lzw_info->code_info.bit=8*lzw_info->code_info.count; lzw_info->code_info.eof=MagickFalse; lzw_info->genesis=MagickTrue; lzw_info->stack=(LZWStack *) AcquireMagickMemory(sizeof(*lzw_info->stack)); if (lzw_info->stack == (LZWStack *) NULL) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } lzw_info->stack->codes=(size_t *) AcquireQuantumMemory(2UL* MaximumLZWCode,sizeof(*lzw_info->stack->codes)); if (lzw_info->stack->codes == (size_t *) NULL) { lzw_info=RelinquishLZWInfo(lzw_info); return((LZWInfo *) NULL); } lzw_info->stack->index=lzw_info->stack->codes; lzw_info->stack->top=lzw_info->stack->codes+2*MaximumLZWCode; return(lzw_info); } static inline int GetNextLZWCode(LZWInfo *lzw_info,const size_t bits) { int code; register ssize_t i; size_t one; while (((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) && (lzw_info->code_info.eof == MagickFalse)) { ssize_t count; lzw_info->code_info.buffer[0]=lzw_info->code_info.buffer[ lzw_info->code_info.count-2]; lzw_info->code_info.buffer[1]=lzw_info->code_info.buffer[ lzw_info->code_info.count-1]; lzw_info->code_info.bit-=8*(lzw_info->code_info.count-2); lzw_info->code_info.count=2; count=ReadBlobBlock(lzw_info->image,&lzw_info->code_info.buffer[ lzw_info->code_info.count]); if (count > 0) lzw_info->code_info.count+=count; else lzw_info->code_info.eof=MagickTrue; } if ((lzw_info->code_info.bit+bits) > (8*lzw_info->code_info.count)) return(-1); code=0; one=1; for (i=0; i < (ssize_t) bits; i++) { code|=((lzw_info->code_info.buffer[lzw_info->code_info.bit/8] & (one << (lzw_info->code_info.bit % 8))) != 0) << i; lzw_info->code_info.bit++; } return(code); } static inline int PopLZWStack(LZWStack *stack_info) { if (stack_info->index <= stack_info->codes) return(-1); stack_info->index--; return((int) *stack_info->index); } static inline void PushLZWStack(LZWStack *stack_info,const size_t value) { if (stack_info->index >= stack_info->top) return; *stack_info->index=value; stack_info->index++; } static int ReadBlobLZWByte(LZWInfo *lzw_info) { int code; size_t one, value; ssize_t count; if (lzw_info->stack->index != lzw_info->stack->codes) return(PopLZWStack(lzw_info->stack)); if (lzw_info->genesis != MagickFalse) { lzw_info->genesis=MagickFalse; do { lzw_info->first_code=(size_t) GetNextLZWCode(lzw_info,lzw_info->bits); lzw_info->last_code=lzw_info->first_code; } while (lzw_info->first_code == lzw_info->clear_code); return((int) lzw_info->first_code); } code=GetNextLZWCode(lzw_info,lzw_info->bits); if (code < 0) return(code); if ((size_t) code == lzw_info->clear_code) { ResetLZWInfo(lzw_info); return(ReadBlobLZWByte(lzw_info)); } if ((size_t) code == lzw_info->end_code) return(-1); if ((size_t) code < lzw_info->slot) value=(size_t) code; else { PushLZWStack(lzw_info->stack,lzw_info->first_code); value=lzw_info->last_code; } count=0; while (value > lzw_info->maximum_data_value) { if ((size_t) count > MaximumLZWCode) return(-1); count++; if ((size_t) value > MaximumLZWCode) return(-1); PushLZWStack(lzw_info->stack,lzw_info->table[1][value]); value=lzw_info->table[0][value]; } lzw_info->first_code=lzw_info->table[1][value]; PushLZWStack(lzw_info->stack,lzw_info->first_code); one=1; if (lzw_info->slot < MaximumLZWCode) { lzw_info->table[0][lzw_info->slot]=lzw_info->last_code; lzw_info->table[1][lzw_info->slot]=lzw_info->first_code; lzw_info->slot++; if ((lzw_info->slot >= lzw_info->maximum_code) && (lzw_info->bits < MaximumLZWBits)) { lzw_info->bits++; lzw_info->maximum_code=one << lzw_info->bits; } } lzw_info->last_code=(size_t) code; return(PopLZWStack(lzw_info->stack)); } static MagickBooleanType DecodeImage(Image *image,const ssize_t opacity, ExceptionInfo *exception) { int c; LZWInfo *lzw_info; size_t pass; ssize_t index, offset, y; unsigned char data_size; /* Allocate decoder tables. */ assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); data_size=(unsigned char) ReadBlobByte(image); if (data_size > MaximumLZWBits) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); lzw_info=AcquireLZWInfo(image,data_size); if (lzw_info == (LZWInfo *) NULL) ThrowBinaryException(ResourceLimitError,"MemoryAllocationFailed", image->filename); pass=0; offset=0; for (y=0; y < (ssize_t) image->rows; y++) { register ssize_t x; register Quantum *magick_restrict q; q=QueueAuthenticPixels(image,0,offset,image->columns,1,exception); if (q == (Quantum *) NULL) break; for (x=0; x < (ssize_t) image->columns; ) { c=ReadBlobLZWByte(lzw_info); if (c < 0) break; index=ConstrainColormapIndex(image,(ssize_t) c,exception); SetPixelIndex(image,(Quantum) index,q); SetPixelViaPixelInfo(image,image->colormap+index,q); SetPixelAlpha(image,index == opacity ? TransparentAlpha : OpaqueAlpha,q); x++; q+=GetPixelChannels(image); } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; if (x < (ssize_t) image->columns) break; if (image->interlace == NoInterlace) offset++; else { switch (pass) { case 0: default: { offset+=8; break; } case 1: { offset+=8; break; } case 2: { offset+=4; break; } case 3: { offset+=2; break; } } if ((pass == 0) && (offset >= (ssize_t) image->rows)) { pass++; offset=4; } if ((pass == 1) && (offset >= (ssize_t) image->rows)) { pass++; offset=2; } if ((pass == 2) && (offset >= (ssize_t) image->rows)) { pass++; offset=1; } } } lzw_info=RelinquishLZWInfo(lzw_info); if (y < (ssize_t) image->rows) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % E n c o d e I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % EncodeImage compresses an image via GIF-coding. % % The format of the EncodeImage method is: % % MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image, % const size_t data_size) % % A description of each parameter follows: % % o image_info: the image info. % % o image: the address of a structure of type Image. % % o data_size: The number of bits in the compressed packet. % */ static MagickBooleanType EncodeImage(const ImageInfo *image_info,Image *image, const size_t data_size,ExceptionInfo *exception) { #define MaxCode(number_bits) ((one << (number_bits))-1) #define MaxHashTable 5003 #define MaxGIFBits 12UL #define MaxGIFTable (1UL << MaxGIFBits) #define GIFOutputCode(code) \ { \ /* \ Emit a code. \ */ \ if (bits > 0) \ datum|=(code) << bits; \ else \ datum=code; \ bits+=number_bits; \ while (bits >= 8) \ { \ /* \ Add a character to current packet. \ */ \ packet[length++]=(unsigned char) (datum & 0xff); \ if (length >= 254) \ { \ (void) WriteBlobByte(image,(unsigned char) length); \ (void) WriteBlob(image,length,packet); \ length=0; \ } \ datum>>=8; \ bits-=8; \ } \ if (free_code > max_code) \ { \ number_bits++; \ if (number_bits == MaxGIFBits) \ max_code=MaxGIFTable; \ else \ max_code=MaxCode(number_bits); \ } \ } Quantum index; short *hash_code, *hash_prefix, waiting_code; size_t bits, clear_code, datum, end_of_information_code, free_code, length, max_code, next_pixel, number_bits, one, pass; ssize_t displacement, offset, k, y; unsigned char *packet, *hash_suffix; /* Allocate encoder tables. */ assert(image != (Image *) NULL); one=1; packet=(unsigned char *) AcquireQuantumMemory(256,sizeof(*packet)); hash_code=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_code)); hash_prefix=(short *) AcquireQuantumMemory(MaxHashTable,sizeof(*hash_prefix)); hash_suffix=(unsigned char *) AcquireQuantumMemory(MaxHashTable, sizeof(*hash_suffix)); if ((packet == (unsigned char *) NULL) || (hash_code == (short *) NULL) || (hash_prefix == (short *) NULL) || (hash_suffix == (unsigned char *) NULL)) { if (packet != (unsigned char *) NULL) packet=(unsigned char *) RelinquishMagickMemory(packet); if (hash_code != (short *) NULL) hash_code=(short *) RelinquishMagickMemory(hash_code); if (hash_prefix != (short *) NULL) hash_prefix=(short *) RelinquishMagickMemory(hash_prefix); if (hash_suffix != (unsigned char *) NULL) hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix); return(MagickFalse); } /* Initialize GIF encoder. */ (void) ResetMagickMemory(hash_code,0,MaxHashTable*sizeof(*hash_code)); (void) ResetMagickMemory(hash_prefix,0,MaxHashTable*sizeof(*hash_prefix)); (void) ResetMagickMemory(hash_suffix,0,MaxHashTable*sizeof(*hash_suffix)); number_bits=data_size; max_code=MaxCode(number_bits); clear_code=((short) one << (data_size-1)); end_of_information_code=clear_code+1; free_code=clear_code+2; length=0; datum=0; bits=0; GIFOutputCode(clear_code); /* Encode pixels. */ offset=0; pass=0; waiting_code=0; for (y=0; y < (ssize_t) image->rows; y++) { register const Quantum *magick_restrict p; register ssize_t x; p=GetVirtualPixels(image,0,offset,image->columns,1,exception); if (p == (const Quantum *) NULL) break; if (y == 0) { waiting_code=(short) GetPixelIndex(image,p); p+=GetPixelChannels(image); } for (x=(ssize_t) (y == 0 ? 1 : 0); x < (ssize_t) image->columns; x++) { /* Probe hash table. */ index=(Quantum) ((size_t) GetPixelIndex(image,p) & 0xff); p+=GetPixelChannels(image); k=(ssize_t) (((size_t) index << (MaxGIFBits-8))+waiting_code); if (k >= MaxHashTable) k-=MaxHashTable; next_pixel=MagickFalse; displacement=1; if (hash_code[k] > 0) { if ((hash_prefix[k] == waiting_code) && (hash_suffix[k] == (unsigned char) index)) { waiting_code=hash_code[k]; continue; } if (k != 0) displacement=MaxHashTable-k; for ( ; ; ) { k-=displacement; if (k < 0) k+=MaxHashTable; if (hash_code[k] == 0) break; if ((hash_prefix[k] == waiting_code) && (hash_suffix[k] == (unsigned char) index)) { waiting_code=hash_code[k]; next_pixel=MagickTrue; break; } } if (next_pixel != MagickFalse) continue; } GIFOutputCode((size_t) waiting_code); if (free_code < MaxGIFTable) { hash_code[k]=(short) free_code++; hash_prefix[k]=waiting_code; hash_suffix[k]=(unsigned char) index; } else { /* Fill the hash table with empty entries. */ for (k=0; k < MaxHashTable; k++) hash_code[k]=0; /* Reset compressor and issue a clear code. */ free_code=clear_code+2; GIFOutputCode(clear_code); number_bits=data_size; max_code=MaxCode(number_bits); } waiting_code=(short) index; } if (image_info->interlace == NoInterlace) offset++; else switch (pass) { case 0: default: { offset+=8; if (offset >= (ssize_t) image->rows) { pass++; offset=4; } break; } case 1: { offset+=8; if (offset >= (ssize_t) image->rows) { pass++; offset=2; } break; } case 2: { offset+=4; if (offset >= (ssize_t) image->rows) { pass++; offset=1; } break; } case 3: { offset+=2; break; } } } /* Flush out the buffered code. */ GIFOutputCode((size_t) waiting_code); GIFOutputCode(end_of_information_code); if (bits > 0) { /* Add a character to current packet. */ packet[length++]=(unsigned char) (datum & 0xff); if (length >= 254) { (void) WriteBlobByte(image,(unsigned char) length); (void) WriteBlob(image,length,packet); length=0; } } /* Flush accumulated data. */ if (length > 0) { (void) WriteBlobByte(image,(unsigned char) length); (void) WriteBlob(image,length,packet); } /* Free encoder memory. */ hash_suffix=(unsigned char *) RelinquishMagickMemory(hash_suffix); hash_prefix=(short *) RelinquishMagickMemory(hash_prefix); hash_code=(short *) RelinquishMagickMemory(hash_code); packet=(unsigned char *) RelinquishMagickMemory(packet); return(MagickTrue); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s G I F % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsGIF() returns MagickTrue if the image format type, identified by the % magick string, is GIF. % % The format of the IsGIF method is: % % MagickBooleanType IsGIF(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsGIF(const unsigned char *magick,const size_t length) { if (length < 4) return(MagickFalse); if (LocaleNCompare((char *) magick,"GIF8",4) == 0) return(MagickTrue); return(MagickFalse); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % + R e a d B l o b B l o c k % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadBlobBlock() reads data from the image file and returns it. The % amount of data is determined by first reading a count byte. The number % of bytes read is returned. % % The format of the ReadBlobBlock method is: % % ssize_t ReadBlobBlock(Image *image,unsigned char *data) % % A description of each parameter follows: % % o image: the image. % % o data: Specifies an area to place the information requested from % the file. % */ static ssize_t ReadBlobBlock(Image *image,unsigned char *data) { ssize_t count; unsigned char block_count; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); assert(data != (unsigned char *) NULL); count=ReadBlob(image,1,&block_count); if (count != 1) return(0); count=ReadBlob(image,(size_t) block_count,data); if (count != (ssize_t) block_count) return(0); return(count); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadGIFImage() reads a Compuserve Graphics image file and returns it. % It allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the ReadGIFImage method is: % % Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType PingGIFImage(Image *image,ExceptionInfo *exception) { unsigned char buffer[256], length, data_size; assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); if (ReadBlob(image,1,&data_size) != 1) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); if (data_size > MaximumLZWBits) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); while (length != 0) { if (ReadBlob(image,length,buffer) != (ssize_t) length) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); if (ReadBlob(image,1,&length) != 1) ThrowBinaryException(CorruptImageError,"CorruptImage",image->filename); } return(MagickTrue); } static Image *ReadGIFImage(const ImageInfo *image_info,ExceptionInfo *exception) { #define BitSet(byte,bit) (((byte) & (bit)) == (bit)) #define LSBFirstOrder(x,y) (((y) << 8) | (x)) Image *image, *meta_image; int number_extensionss=0; MagickBooleanType status; RectangleInfo page; register ssize_t i; register unsigned char *p; size_t delay, dispose, duration, global_colors, image_count, iterations, one; ssize_t count, opacity; unsigned char background, c, flag, *global_colormap, buffer[257]; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); image=AcquireImage(image_info,exception); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Determine if this a GIF file. */ count=ReadBlob(image,6,buffer); if ((count != 6) || ((LocaleNCompare((char *) buffer,"GIF87",5) != 0) && (LocaleNCompare((char *) buffer,"GIF89",5) != 0))) ThrowReaderException(CorruptImageError,"ImproperImageHeader"); page.width=ReadBlobLSBShort(image); page.height=ReadBlobLSBShort(image); flag=(unsigned char) ReadBlobByte(image); background=(unsigned char) ReadBlobByte(image); c=(unsigned char) ReadBlobByte(image); /* reserved */ one=1; global_colors=one << (((size_t) flag & 0x07)+1); global_colormap=(unsigned char *) AcquireQuantumMemory((size_t) MagickMax(global_colors,256),3UL*sizeof(*global_colormap)); if (global_colormap == (unsigned char *) NULL) ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); (void) ResetMagickMemory(global_colormap,0,3*MagickMax(global_colors,256)* sizeof(*global_colormap)); if (BitSet((int) flag,0x80) != 0) { count=ReadBlob(image,(size_t) (3*global_colors),global_colormap); if (count != (ssize_t) (3*global_colors)) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); } } delay=0; dispose=0; duration=0; iterations=1; opacity=(-1); image_count=0; meta_image=AcquireImage(image_info,exception); /* metadata container */ for ( ; ; ) { count=ReadBlob(image,1,&c); if (count != 1) break; if (c == (unsigned char) ';') break; /* terminator */ if (c == (unsigned char) '!') { /* GIF Extension block. */ count=ReadBlob(image,1,&c); if (count != 1) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); meta_image=DestroyImage(meta_image); ThrowReaderException(CorruptImageError, "UnableToReadExtensionBlock"); } switch (c) { case 0xf9: { /* Read graphics control extension. */ while (ReadBlobBlock(image,buffer) != 0) ; dispose=(size_t) (buffer[0] >> 2); delay=(size_t) ((buffer[2] << 8) | buffer[1]); if ((ssize_t) (buffer[0] & 0x01) == 0x01) opacity=(ssize_t) buffer[3]; break; } case 0xfe: { char *comments; size_t length; /* Read comment extension. */ comments=AcquireString((char *) NULL); for (length=0; ; length+=count) { count=(ssize_t) ReadBlobBlock(image,buffer); if (count == 0) break; buffer[count]='\0'; (void) ConcatenateString(&comments,(const char *) buffer); } (void) SetImageProperty(meta_image,"comment",comments,exception); comments=DestroyString(comments); break; } case 0xff: { MagickBooleanType loop; /* Read Netscape Loop extension. */ loop=MagickFalse; if (ReadBlobBlock(image,buffer) != 0) loop=LocaleNCompare((char *) buffer,"NETSCAPE2.0",11) == 0 ? MagickTrue : MagickFalse; if (loop != MagickFalse) { while (ReadBlobBlock(image,buffer) != 0) iterations=(size_t) ((buffer[2] << 8) | buffer[1]); break; } else { char name[MagickPathExtent]; int block_length, info_length, reserved_length; MagickBooleanType i8bim, icc, iptc, magick; StringInfo *profile; unsigned char *info; /* Store GIF application extension as a generic profile. */ icc=LocaleNCompare((char *) buffer,"ICCRGBG1012",11) == 0 ? MagickTrue : MagickFalse; magick=LocaleNCompare((char *) buffer,"ImageMagick",11) == 0 ? MagickTrue : MagickFalse; i8bim=LocaleNCompare((char *) buffer,"MGK8BIM0000",11) == 0 ? MagickTrue : MagickFalse; iptc=LocaleNCompare((char *) buffer,"MGKIPTC0000",11) == 0 ? MagickTrue : MagickFalse; number_extensionss++; (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Reading GIF application extension"); info=(unsigned char *) AcquireQuantumMemory(255UL, sizeof(*info)); if (info == (unsigned char *) NULL) { meta_image=DestroyImage(meta_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } reserved_length=255; for (info_length=0; ; ) { block_length=(int) ReadBlobBlock(image,&info[info_length]); if (block_length == 0) break; info_length+=block_length; if (info_length > (reserved_length-255)) { reserved_length+=4096; info=(unsigned char *) ResizeQuantumMemory(info,(size_t) reserved_length,sizeof(*info)); if (info == (unsigned char *) NULL) { meta_image=DestroyImage(meta_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } } } profile=BlobToStringInfo(info,(size_t) info_length); if (profile == (StringInfo *) NULL) { meta_image=DestroyImage(meta_image); ThrowReaderException(ResourceLimitError, "MemoryAllocationFailed"); } if (i8bim != MagickFalse) (void) CopyMagickString(name,"8bim",sizeof(name)); else if (icc != MagickFalse) (void) CopyMagickString(name,"icc",sizeof(name)); else if (iptc != MagickFalse) (void) CopyMagickString(name,"iptc",sizeof(name)); else if (magick != MagickFalse) { (void) CopyMagickString(name,"magick",sizeof(name)); meta_image->gamma=StringToDouble((char *) info+6, (char **) NULL); } else (void) FormatLocaleString(name,sizeof(name),"gif:%.11s", buffer); info=(unsigned char *) RelinquishMagickMemory(info); if (magick == MagickFalse) (void) SetImageProfile(meta_image,name,profile,exception); profile=DestroyStringInfo(profile); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " profile name=%s",name); } break; } default: { while (ReadBlobBlock(image,buffer) != 0) ; break; } } } if (c != (unsigned char) ',') continue; if (image_count != 0) { /* Allocate next image structure. */ AcquireNextImage(image_info,image,exception); if (GetNextImageInList(image) == (Image *) NULL) { image=DestroyImageList(image); global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); return((Image *) NULL); } image=SyncNextImageInList(image); } image_count++; /* Read image attributes. */ meta_image->scene=image->scene; (void) CloneImageProperties(image,meta_image); DestroyImageProperties(meta_image); (void) CloneImageProfiles(image,meta_image); DestroyImageProfiles(meta_image); image->storage_class=PseudoClass; image->compression=LZWCompression; page.x=(ssize_t) ReadBlobLSBShort(image); page.y=(ssize_t) ReadBlobLSBShort(image); image->columns=ReadBlobLSBShort(image); image->rows=ReadBlobLSBShort(image); image->depth=8; flag=(unsigned char) ReadBlobByte(image); image->interlace=BitSet((int) flag,0x40) != 0 ? GIFInterlace : NoInterlace; image->colors=BitSet((int) flag,0x80) == 0 ? global_colors : one << ((size_t) (flag & 0x07)+1); if (opacity >= (ssize_t) image->colors) opacity=(-1); image->page.width=page.width; image->page.height=page.height; image->page.y=page.y; image->page.x=page.x; image->delay=delay; image->ticks_per_second=100; image->dispose=(DisposeType) dispose; image->iterations=iterations; image->alpha_trait=opacity >= 0 ? BlendPixelTrait : UndefinedPixelTrait; delay=0; dispose=0; if ((image->columns == 0) || (image->rows == 0)) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); meta_image=DestroyImage(meta_image); ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); } /* Inititialize colormap. */ if (AcquireImageColormap(image,image->colors,exception) == MagickFalse) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); meta_image=DestroyImage(meta_image); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } if (BitSet((int) flag,0x80) == 0) { /* Use global colormap. */ p=global_colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(double) ScaleCharToQuantum(*p++); image->colormap[i].green=(double) ScaleCharToQuantum(*p++); image->colormap[i].blue=(double) ScaleCharToQuantum(*p++); if (i == opacity) { image->colormap[i].alpha=(double) TransparentAlpha; image->transparent_color=image->colormap[opacity]; } } image->background_color=image->colormap[MagickMin((ssize_t) background, (ssize_t) image->colors-1)]; } else { unsigned char *colormap; /* Read local colormap. */ colormap=(unsigned char *) AcquireQuantumMemory(image->colors,3* sizeof(*colormap)); if (colormap == (unsigned char *) NULL) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); meta_image=DestroyImage(meta_image); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } count=ReadBlob(image,(3*image->colors)*sizeof(*colormap),colormap); if (count != (ssize_t) (3*image->colors)) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); meta_image=DestroyImage(meta_image); ThrowReaderException(CorruptImageError, "InsufficientImageDataInFile"); } p=colormap; for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=(double) ScaleCharToQuantum(*p++); image->colormap[i].green=(double) ScaleCharToQuantum(*p++); image->colormap[i].blue=(double) ScaleCharToQuantum(*p++); if (i == opacity) image->colormap[i].alpha=(double) TransparentAlpha; } colormap=(unsigned char *) RelinquishMagickMemory(colormap); } if (image->gamma == 1.0) { for (i=0; i < (ssize_t) image->colors; i++) if (IsPixelInfoGray(image->colormap+i) == MagickFalse) break; (void) SetImageColorspace(image,i == (ssize_t) image->colors ? GRAYColorspace : RGBColorspace,exception); } if ((image_info->ping != MagickFalse) && (image_info->number_scenes != 0)) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; status=SetImageExtent(image,image->columns,image->rows,exception); if (status == MagickFalse) return(DestroyImageList(image)); /* Decode image. */ if (image_info->ping != MagickFalse) status=PingGIFImage(image,exception); else status=DecodeImage(image,opacity,exception); if ((image_info->ping == MagickFalse) && (status == MagickFalse)) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); meta_image=DestroyImage(meta_image); ThrowReaderException(CorruptImageError,"CorruptImage"); } duration+=image->delay*image->iterations; if (image_info->number_scenes != 0) if (image->scene >= (image_info->scene+image_info->number_scenes-1)) break; opacity=(-1); status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) image->scene- 1,image->scene); if (status == MagickFalse) break; } image->duration=duration; meta_image=DestroyImage(meta_image); global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); if ((image->columns == 0) || (image->rows == 0)) ThrowReaderException(CorruptImageError,"NegativeOrZeroImageSize"); (void) CloseBlob(image); return(GetFirstImageInList(image)); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterGIFImage() adds properties for the GIF image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterGIFImage method is: % % size_t RegisterGIFImage(void) % */ ModuleExport size_t RegisterGIFImage(void) { MagickInfo *entry; entry=AcquireMagickInfo("GIF","GIF", "CompuServe graphics interchange format"); entry->decoder=(DecodeImageHandler *) ReadGIFImage; entry->encoder=(EncodeImageHandler *) WriteGIFImage; entry->magick=(IsImageFormatHandler *) IsGIF; entry->mime_type=ConstantString("image/gif"); (void) RegisterMagickInfo(entry); entry=AcquireMagickInfo("GIF","GIF87", "CompuServe graphics interchange format"); entry->decoder=(DecodeImageHandler *) ReadGIFImage; entry->encoder=(EncodeImageHandler *) WriteGIFImage; entry->magick=(IsImageFormatHandler *) IsGIF; entry->flags^=CoderAdjoinFlag; entry->version=ConstantString("version 87a"); entry->mime_type=ConstantString("image/gif"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterGIFImage() removes format registrations made by the % GIF module from the list of supported formats. % % The format of the UnregisterGIFImage method is: % % UnregisterGIFImage(void) % */ ModuleExport void UnregisterGIFImage(void) { (void) UnregisterMagickInfo("GIF"); (void) UnregisterMagickInfo("GIF87"); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e G I F I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteGIFImage() writes an image to a file in the Compuserve Graphics % image format. % % The format of the WriteGIFImage method is: % % MagickBooleanType WriteGIFImage(const ImageInfo *image_info, % Image *image,ExceptionInfo *exception) % % A description of each parameter follows. % % o image_info: the image info. % % o image: The image. % % o exception: return any errors or warnings in this structure. % */ static MagickBooleanType WriteGIFImage(const ImageInfo *image_info,Image *image, ExceptionInfo *exception) { int c; ImageInfo *write_info; MagickBooleanType status; MagickOffsetType scene; RectangleInfo page; register ssize_t i; register unsigned char *q; size_t bits_per_pixel, delay, length, one; ssize_t j, opacity; unsigned char *colormap, *global_colormap; /* Open output image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickCoreSignature); assert(image != (Image *) NULL); assert(image->signature == MagickCoreSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickCoreSignature); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Allocate colormap. */ global_colormap=(unsigned char *) AcquireQuantumMemory(768UL, sizeof(*global_colormap)); colormap=(unsigned char *) AcquireQuantumMemory(768UL,sizeof(*colormap)); if ((global_colormap == (unsigned char *) NULL) || (colormap == (unsigned char *) NULL)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (i=0; i < 768; i++) colormap[i]=(unsigned char) 0; /* Write GIF header. */ write_info=CloneImageInfo(image_info); if (LocaleCompare(write_info->magick,"GIF87") != 0) (void) WriteBlob(image,6,(unsigned char *) "GIF89a"); else { (void) WriteBlob(image,6,(unsigned char *) "GIF87a"); write_info->adjoin=MagickFalse; } /* Determine image bounding box. */ page.width=image->columns; if (image->page.width > page.width) page.width=image->page.width; page.height=image->rows; if (image->page.height > page.height) page.height=image->page.height; page.x=image->page.x; page.y=image->page.y; (void) WriteBlobLSBShort(image,(unsigned short) page.width); (void) WriteBlobLSBShort(image,(unsigned short) page.height); /* Write images to file. */ if ((write_info->adjoin != MagickFalse) && (GetNextImageInList(image) != (Image *) NULL)) write_info->interlace=NoInterlace; scene=0; one=1; do { (void) TransformImageColorspace(image,sRGBColorspace,exception); opacity=(-1); if (IsImageOpaque(image,exception) != MagickFalse) { if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteType,exception); } else { double alpha, beta; /* Identify transparent colormap index. */ if ((image->storage_class == DirectClass) || (image->colors > 256)) (void) SetImageType(image,PaletteBilevelAlphaType,exception); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].alpha != OpaqueAlpha) { if (opacity < 0) { opacity=i; continue; } alpha=fabs(image->colormap[i].alpha-TransparentAlpha); beta=fabs(image->colormap[opacity].alpha-TransparentAlpha); if (alpha < beta) opacity=i; } if (opacity == -1) { (void) SetImageType(image,PaletteBilevelAlphaType,exception); for (i=0; i < (ssize_t) image->colors; i++) if (image->colormap[i].alpha != OpaqueAlpha) { if (opacity < 0) { opacity=i; continue; } alpha=fabs(image->colormap[i].alpha-TransparentAlpha); beta=fabs(image->colormap[opacity].alpha-TransparentAlpha); if (alpha < beta) opacity=i; } } if (opacity >= 0) { image->colormap[opacity].red=image->transparent_color.red; image->colormap[opacity].green=image->transparent_color.green; image->colormap[opacity].blue=image->transparent_color.blue; } } if ((image->storage_class == DirectClass) || (image->colors > 256)) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); for (bits_per_pixel=1; bits_per_pixel < 8; bits_per_pixel++) if ((one << bits_per_pixel) >= image->colors) break; q=colormap; for (i=0; i < (ssize_t) image->colors; i++) { *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].red)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].green)); *q++=ScaleQuantumToChar(ClampToQuantum(image->colormap[i].blue)); } for ( ; i < (ssize_t) (one << bits_per_pixel); i++) { *q++=(unsigned char) 0x0; *q++=(unsigned char) 0x0; *q++=(unsigned char) 0x0; } if ((GetPreviousImageInList(image) == (Image *) NULL) || (write_info->adjoin == MagickFalse)) { /* Write global colormap. */ c=0x80; c|=(8-1) << 4; /* color resolution */ c|=(bits_per_pixel-1); /* size of global colormap */ (void) WriteBlobByte(image,(unsigned char) c); for (j=0; j < (ssize_t) image->colors; j++) if (IsPixelInfoEquivalent(&image->background_color,image->colormap+j)) break; (void) WriteBlobByte(image,(unsigned char) (j == (ssize_t) image->colors ? 0 : j)); /* background color */ (void) WriteBlobByte(image,(unsigned char) 0x00); /* reserved */ length=(size_t) (3*(one << bits_per_pixel)); (void) WriteBlob(image,length,colormap); for (j=0; j < 768; j++) global_colormap[j]=colormap[j]; } if (LocaleCompare(write_info->magick,"GIF87") != 0) { const char *value; /* Write graphics control extension. */ (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xf9); (void) WriteBlobByte(image,(unsigned char) 0x04); c=image->dispose << 2; if (opacity >= 0) c|=0x01; (void) WriteBlobByte(image,(unsigned char) c); delay=(size_t) (100*image->delay/MagickMax((size_t) image->ticks_per_second,1)); (void) WriteBlobLSBShort(image,(unsigned short) delay); (void) WriteBlobByte(image,(unsigned char) (opacity >= 0 ? opacity : 0)); (void) WriteBlobByte(image,(unsigned char) 0x00); value=GetImageProperty(image,"comment",exception); if ((LocaleCompare(write_info->magick,"GIF87") != 0) && (value != (const char *) NULL)) { register const char *p; size_t count; /* Write comment extension. */ (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xfe); for (p=value; *p != '\0'; ) { count=MagickMin(strlen(p),255); (void) WriteBlobByte(image,(unsigned char) count); for (i=0; i < (ssize_t) count; i++) (void) WriteBlobByte(image,(unsigned char) *p++); } (void) WriteBlobByte(image,(unsigned char) 0x00); } if ((GetPreviousImageInList(image) == (Image *) NULL) && (GetNextImageInList(image) != (Image *) NULL) && (image->iterations != 1)) { /* Write Netscape Loop extension. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","NETSCAPE2.0"); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); (void) WriteBlob(image,11,(unsigned char *) "NETSCAPE2.0"); (void) WriteBlobByte(image,(unsigned char) 0x03); (void) WriteBlobByte(image,(unsigned char) 0x01); (void) WriteBlobLSBShort(image,(unsigned short) image->iterations); (void) WriteBlobByte(image,(unsigned char) 0x00); } if ((image->gamma != 1.0f/2.2f)) { char attributes[MagickPathExtent]; ssize_t count; /* Write ImageMagick extension. */ (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","ImageMagick"); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); (void) WriteBlob(image,11,(unsigned char *) "ImageMagick"); count=FormatLocaleString(attributes,MagickPathExtent,"gamma=%g", image->gamma); (void) WriteBlobByte(image,(unsigned char) count); (void) WriteBlob(image,(size_t) count,(unsigned char *) attributes); (void) WriteBlobByte(image,(unsigned char) 0x00); } ResetImageProfileIterator(image); for ( ; ; ) { char *name; const StringInfo *profile; name=GetNextImageProfile(image); if (name == (const char *) NULL) break; profile=GetImageProfile(image,name); if (profile != (StringInfo *) NULL) { if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0) || (LocaleCompare(name,"IPTC") == 0) || (LocaleCompare(name,"8BIM") == 0) || (LocaleNCompare(name,"gif:",4) == 0)) { ssize_t offset; unsigned char *datum; datum=GetStringInfoDatum(profile); length=GetStringInfoLength(profile); (void) WriteBlobByte(image,(unsigned char) 0x21); (void) WriteBlobByte(image,(unsigned char) 0xff); (void) WriteBlobByte(image,(unsigned char) 0x0b); if ((LocaleCompare(name,"ICC") == 0) || (LocaleCompare(name,"ICM") == 0)) { /* Write ICC extension. */ (void) WriteBlob(image,11,(unsigned char *) "ICCRGBG1012"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","ICCRGBG1012"); } else if ((LocaleCompare(name,"IPTC") == 0)) { /* Write IPTC extension. */ (void) WriteBlob(image,11,(unsigned char *) "MGKIPTC0000"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","MGKIPTC0000"); } else if ((LocaleCompare(name,"8BIM") == 0)) { /* Write 8BIM extension. */ (void) WriteBlob(image,11,(unsigned char *) "MGK8BIM0000"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s","MGK8BIM0000"); } else { char extension[MagickPathExtent]; /* Write generic extension. */ (void) CopyMagickString(extension,name+4, sizeof(extension)); (void) WriteBlob(image,11,(unsigned char *) extension); (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Writing GIF Extension %s",name); } offset=0; while ((ssize_t) length > offset) { size_t block_length; if ((length-offset) < 255) block_length=length-offset; else block_length=255; (void) WriteBlobByte(image,(unsigned char) block_length); (void) WriteBlob(image,(size_t) block_length,datum+offset); offset+=(ssize_t) block_length; } (void) WriteBlobByte(image,(unsigned char) 0x00); } } } } (void) WriteBlobByte(image,','); /* image separator */ /* Write the image header. */ page.x=image->page.x; page.y=image->page.y; if ((image->page.width != 0) && (image->page.height != 0)) page=image->page; (void) WriteBlobLSBShort(image,(unsigned short) (page.x < 0 ? 0 : page.x)); (void) WriteBlobLSBShort(image,(unsigned short) (page.y < 0 ? 0 : page.y)); (void) WriteBlobLSBShort(image,(unsigned short) image->columns); (void) WriteBlobLSBShort(image,(unsigned short) image->rows); c=0x00; if (write_info->interlace != NoInterlace) c|=0x40; /* pixel data is interlaced */ for (j=0; j < (ssize_t) (3*image->colors); j++) if (colormap[j] != global_colormap[j]) break; if (j == (ssize_t) (3*image->colors)) (void) WriteBlobByte(image,(unsigned char) c); else { c|=0x80; c|=(bits_per_pixel-1); /* size of local colormap */ (void) WriteBlobByte(image,(unsigned char) c); length=(size_t) (3*(one << bits_per_pixel)); (void) WriteBlob(image,length,colormap); } /* Write the image data. */ c=(int) MagickMax(bits_per_pixel,2); (void) WriteBlobByte(image,(unsigned char) c); status=EncodeImage(write_info,image,(size_t) MagickMax(bits_per_pixel,2)+1, exception); if (status == MagickFalse) { global_colormap=(unsigned char *) RelinquishMagickMemory( global_colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); write_info=DestroyImageInfo(write_info); ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); } (void) WriteBlobByte(image,(unsigned char) 0x00); if (GetNextImageInList(image) == (Image *) NULL) break; image=SyncNextImageInList(image); scene++; status=SetImageProgress(image,SaveImagesTag,scene, GetImageListLength(image)); if (status == MagickFalse) break; } while (write_info->adjoin != MagickFalse); (void) WriteBlobByte(image,';'); /* terminator */ global_colormap=(unsigned char *) RelinquishMagickMemory(global_colormap); colormap=(unsigned char *) RelinquishMagickMemory(colormap); write_info=DestroyImageInfo(write_info); (void) CloseBlob(image); return(MagickTrue); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2853_0
crossvul-cpp_data_good_5609_0
/* * ioctl32.c: Conversion between 32bit and 64bit native ioctls. * * Copyright (C) 1997-2000 Jakub Jelinek (jakub@redhat.com) * Copyright (C) 1998 Eddie C. Dost (ecd@skynet.be) * Copyright (C) 2001,2002 Andi Kleen, SuSE Labs * Copyright (C) 2003 Pavel Machek (pavel@ucw.cz) * * These routines maintain argument size conversion between 32bit and 64bit * ioctls. */ #include <linux/joystick.h> #include <linux/types.h> #include <linux/compat.h> #include <linux/kernel.h> #include <linux/capability.h> #include <linux/compiler.h> #include <linux/sched.h> #include <linux/smp.h> #include <linux/ioctl.h> #include <linux/if.h> #include <linux/if_bridge.h> #include <linux/raid/md_u.h> #include <linux/kd.h> #include <linux/route.h> #include <linux/in6.h> #include <linux/ipv6_route.h> #include <linux/skbuff.h> #include <linux/netlink.h> #include <linux/vt.h> #include <linux/falloc.h> #include <linux/fs.h> #include <linux/file.h> #include <linux/ppp_defs.h> #include <linux/ppp-ioctl.h> #include <linux/if_pppox.h> #include <linux/mtio.h> #include <linux/auto_fs.h> #include <linux/auto_fs4.h> #include <linux/tty.h> #include <linux/vt_kern.h> #include <linux/fb.h> #include <linux/videodev2.h> #include <linux/netdevice.h> #include <linux/raw.h> #include <linux/blkdev.h> #include <linux/elevator.h> #include <linux/rtc.h> #include <linux/pci.h> #include <linux/serial.h> #include <linux/if_tun.h> #include <linux/ctype.h> #include <linux/syscalls.h> #include <linux/i2c.h> #include <linux/i2c-dev.h> #include <linux/atalk.h> #include <linux/gfp.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci.h> #include <net/bluetooth/rfcomm.h> #include <linux/capi.h> #include <linux/gigaset_dev.h> #ifdef CONFIG_BLOCK #include <linux/loop.h> #include <linux/cdrom.h> #include <linux/fd.h> #include <scsi/scsi.h> #include <scsi/scsi_ioctl.h> #include <scsi/sg.h> #endif #include <asm/uaccess.h> #include <linux/ethtool.h> #include <linux/mii.h> #include <linux/if_bonding.h> #include <linux/watchdog.h> #include <linux/soundcard.h> #include <linux/lp.h> #include <linux/ppdev.h> #include <linux/atm.h> #include <linux/atmarp.h> #include <linux/atmclip.h> #include <linux/atmdev.h> #include <linux/atmioc.h> #include <linux/atmlec.h> #include <linux/atmmpc.h> #include <linux/atmsvc.h> #include <linux/atm_tcp.h> #include <linux/sonet.h> #include <linux/atm_suni.h> #include <linux/usb.h> #include <linux/usbdevice_fs.h> #include <linux/nbd.h> #include <linux/random.h> #include <linux/filter.h> #include <linux/hiddev.h> #define __DVB_CORE__ #include <linux/dvb/audio.h> #include <linux/dvb/dmx.h> #include <linux/dvb/frontend.h> #include <linux/dvb/video.h> #include <linux/sort.h> #ifdef CONFIG_SPARC #include <asm/fbio.h> #endif static int w_long(unsigned int fd, unsigned int cmd, compat_ulong_t __user *argp) { mm_segment_t old_fs = get_fs(); int err; unsigned long val; set_fs (KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long)&val); set_fs (old_fs); if (!err && put_user(val, argp)) return -EFAULT; return err; } struct compat_video_event { int32_t type; compat_time_t timestamp; union { video_size_t size; unsigned int frame_rate; } u; }; static int do_video_get_event(unsigned int fd, unsigned int cmd, struct compat_video_event __user *up) { struct video_event kevent; mm_segment_t old_fs = get_fs(); int err; set_fs(KERNEL_DS); err = sys_ioctl(fd, cmd, (unsigned long) &kevent); set_fs(old_fs); if (!err) { err = put_user(kevent.type, &up->type); err |= put_user(kevent.timestamp, &up->timestamp); err |= put_user(kevent.u.size.w, &up->u.size.w); err |= put_user(kevent.u.size.h, &up->u.size.h); err |= put_user(kevent.u.size.aspect_ratio, &up->u.size.aspect_ratio); if (err) err = -EFAULT; } return err; } struct compat_video_still_picture { compat_uptr_t iFrame; int32_t size; }; static int do_video_stillpicture(unsigned int fd, unsigned int cmd, struct compat_video_still_picture __user *up) { struct video_still_picture __user *up_native; compat_uptr_t fp; int32_t size; int err; err = get_user(fp, &up->iFrame); err |= get_user(size, &up->size); if (err) return -EFAULT; up_native = compat_alloc_user_space(sizeof(struct video_still_picture)); err = put_user(compat_ptr(fp), &up_native->iFrame); err |= put_user(size, &up_native->size); if (err) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) up_native); return err; } struct compat_video_spu_palette { int length; compat_uptr_t palette; }; static int do_video_set_spu_palette(unsigned int fd, unsigned int cmd, struct compat_video_spu_palette __user *up) { struct video_spu_palette __user *up_native; compat_uptr_t palp; int length, err; err = get_user(palp, &up->palette); err |= get_user(length, &up->length); if (err) return -EFAULT; up_native = compat_alloc_user_space(sizeof(struct video_spu_palette)); err = put_user(compat_ptr(palp), &up_native->palette); err |= put_user(length, &up_native->length); if (err) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) up_native); return err; } #ifdef CONFIG_BLOCK typedef struct sg_io_hdr32 { compat_int_t interface_id; /* [i] 'S' for SCSI generic (required) */ compat_int_t dxfer_direction; /* [i] data transfer direction */ unsigned char cmd_len; /* [i] SCSI command length ( <= 16 bytes) */ unsigned char mx_sb_len; /* [i] max length to write to sbp */ unsigned short iovec_count; /* [i] 0 implies no scatter gather */ compat_uint_t dxfer_len; /* [i] byte count of data transfer */ compat_uint_t dxferp; /* [i], [*io] points to data transfer memory or scatter gather list */ compat_uptr_t cmdp; /* [i], [*i] points to command to perform */ compat_uptr_t sbp; /* [i], [*o] points to sense_buffer memory */ compat_uint_t timeout; /* [i] MAX_UINT->no timeout (unit: millisec) */ compat_uint_t flags; /* [i] 0 -> default, see SG_FLAG... */ compat_int_t pack_id; /* [i->o] unused internally (normally) */ compat_uptr_t usr_ptr; /* [i->o] unused internally */ unsigned char status; /* [o] scsi status */ unsigned char masked_status; /* [o] shifted, masked scsi status */ unsigned char msg_status; /* [o] messaging level data (optional) */ unsigned char sb_len_wr; /* [o] byte count actually written to sbp */ unsigned short host_status; /* [o] errors from host adapter */ unsigned short driver_status; /* [o] errors from software driver */ compat_int_t resid; /* [o] dxfer_len - actual_transferred */ compat_uint_t duration; /* [o] time taken by cmd (unit: millisec) */ compat_uint_t info; /* [o] auxiliary information */ } sg_io_hdr32_t; /* 64 bytes long (on sparc32) */ typedef struct sg_iovec32 { compat_uint_t iov_base; compat_uint_t iov_len; } sg_iovec32_t; static int sg_build_iovec(sg_io_hdr_t __user *sgio, void __user *dxferp, u16 iovec_count) { sg_iovec_t __user *iov = (sg_iovec_t __user *) (sgio + 1); sg_iovec32_t __user *iov32 = dxferp; int i; for (i = 0; i < iovec_count; i++) { u32 base, len; if (get_user(base, &iov32[i].iov_base) || get_user(len, &iov32[i].iov_len) || put_user(compat_ptr(base), &iov[i].iov_base) || put_user(len, &iov[i].iov_len)) return -EFAULT; } if (put_user(iov, &sgio->dxferp)) return -EFAULT; return 0; } static int sg_ioctl_trans(unsigned int fd, unsigned int cmd, sg_io_hdr32_t __user *sgio32) { sg_io_hdr_t __user *sgio; u16 iovec_count; u32 data; void __user *dxferp; int err; int interface_id; if (get_user(interface_id, &sgio32->interface_id)) return -EFAULT; if (interface_id != 'S') return sys_ioctl(fd, cmd, (unsigned long)sgio32); if (get_user(iovec_count, &sgio32->iovec_count)) return -EFAULT; { void __user *top = compat_alloc_user_space(0); void __user *new = compat_alloc_user_space(sizeof(sg_io_hdr_t) + (iovec_count * sizeof(sg_iovec_t))); if (new > top) return -EINVAL; sgio = new; } /* Ok, now construct. */ if (copy_in_user(&sgio->interface_id, &sgio32->interface_id, (2 * sizeof(int)) + (2 * sizeof(unsigned char)) + (1 * sizeof(unsigned short)) + (1 * sizeof(unsigned int)))) return -EFAULT; if (get_user(data, &sgio32->dxferp)) return -EFAULT; dxferp = compat_ptr(data); if (iovec_count) { if (sg_build_iovec(sgio, dxferp, iovec_count)) return -EFAULT; } else { if (put_user(dxferp, &sgio->dxferp)) return -EFAULT; } { unsigned char __user *cmdp; unsigned char __user *sbp; if (get_user(data, &sgio32->cmdp)) return -EFAULT; cmdp = compat_ptr(data); if (get_user(data, &sgio32->sbp)) return -EFAULT; sbp = compat_ptr(data); if (put_user(cmdp, &sgio->cmdp) || put_user(sbp, &sgio->sbp)) return -EFAULT; } if (copy_in_user(&sgio->timeout, &sgio32->timeout, 3 * sizeof(int))) return -EFAULT; if (get_user(data, &sgio32->usr_ptr)) return -EFAULT; if (put_user(compat_ptr(data), &sgio->usr_ptr)) return -EFAULT; err = sys_ioctl(fd, cmd, (unsigned long) sgio); if (err >= 0) { void __user *datap; if (copy_in_user(&sgio32->pack_id, &sgio->pack_id, sizeof(int)) || get_user(datap, &sgio->usr_ptr) || put_user((u32)(unsigned long)datap, &sgio32->usr_ptr) || copy_in_user(&sgio32->status, &sgio->status, (4 * sizeof(unsigned char)) + (2 * sizeof(unsigned short)) + (3 * sizeof(int)))) err = -EFAULT; } return err; } struct compat_sg_req_info { /* used by SG_GET_REQUEST_TABLE ioctl() */ char req_state; char orphan; char sg_io_owned; char problem; int pack_id; compat_uptr_t usr_ptr; unsigned int duration; int unused; }; static int sg_grt_trans(unsigned int fd, unsigned int cmd, struct compat_sg_req_info __user *o) { int err, i; sg_req_info_t __user *r; r = compat_alloc_user_space(sizeof(sg_req_info_t)*SG_MAX_QUEUE); err = sys_ioctl(fd,cmd,(unsigned long)r); if (err < 0) return err; for (i = 0; i < SG_MAX_QUEUE; i++) { void __user *ptr; int d; if (copy_in_user(o + i, r + i, offsetof(sg_req_info_t, usr_ptr)) || get_user(ptr, &r[i].usr_ptr) || get_user(d, &r[i].duration) || put_user((u32)(unsigned long)(ptr), &o[i].usr_ptr) || put_user(d, &o[i].duration)) return -EFAULT; } return err; } #endif /* CONFIG_BLOCK */ struct sock_fprog32 { unsigned short len; compat_caddr_t filter; }; #define PPPIOCSPASS32 _IOW('t', 71, struct sock_fprog32) #define PPPIOCSACTIVE32 _IOW('t', 70, struct sock_fprog32) static int ppp_sock_fprog_ioctl_trans(unsigned int fd, unsigned int cmd, struct sock_fprog32 __user *u_fprog32) { struct sock_fprog __user *u_fprog64 = compat_alloc_user_space(sizeof(struct sock_fprog)); void __user *fptr64; u32 fptr32; u16 flen; if (get_user(flen, &u_fprog32->len) || get_user(fptr32, &u_fprog32->filter)) return -EFAULT; fptr64 = compat_ptr(fptr32); if (put_user(flen, &u_fprog64->len) || put_user(fptr64, &u_fprog64->filter)) return -EFAULT; if (cmd == PPPIOCSPASS32) cmd = PPPIOCSPASS; else cmd = PPPIOCSACTIVE; return sys_ioctl(fd, cmd, (unsigned long) u_fprog64); } struct ppp_option_data32 { compat_caddr_t ptr; u32 length; compat_int_t transmit; }; #define PPPIOCSCOMPRESS32 _IOW('t', 77, struct ppp_option_data32) struct ppp_idle32 { compat_time_t xmit_idle; compat_time_t recv_idle; }; #define PPPIOCGIDLE32 _IOR('t', 63, struct ppp_idle32) static int ppp_gidle(unsigned int fd, unsigned int cmd, struct ppp_idle32 __user *idle32) { struct ppp_idle __user *idle; __kernel_time_t xmit, recv; int err; idle = compat_alloc_user_space(sizeof(*idle)); err = sys_ioctl(fd, PPPIOCGIDLE, (unsigned long) idle); if (!err) { if (get_user(xmit, &idle->xmit_idle) || get_user(recv, &idle->recv_idle) || put_user(xmit, &idle32->xmit_idle) || put_user(recv, &idle32->recv_idle)) err = -EFAULT; } return err; } static int ppp_scompress(unsigned int fd, unsigned int cmd, struct ppp_option_data32 __user *odata32) { struct ppp_option_data __user *odata; __u32 data; void __user *datap; odata = compat_alloc_user_space(sizeof(*odata)); if (get_user(data, &odata32->ptr)) return -EFAULT; datap = compat_ptr(data); if (put_user(datap, &odata->ptr)) return -EFAULT; if (copy_in_user(&odata->length, &odata32->length, sizeof(__u32) + sizeof(int))) return -EFAULT; return sys_ioctl(fd, PPPIOCSCOMPRESS, (unsigned long) odata); } #ifdef CONFIG_BLOCK struct mtget32 { compat_long_t mt_type; compat_long_t mt_resid; compat_long_t mt_dsreg; compat_long_t mt_gstat; compat_long_t mt_erreg; compat_daddr_t mt_fileno; compat_daddr_t mt_blkno; }; #define MTIOCGET32 _IOR('m', 2, struct mtget32) struct mtpos32 { compat_long_t mt_blkno; }; #define MTIOCPOS32 _IOR('m', 3, struct mtpos32) static int mt_ioctl_trans(unsigned int fd, unsigned int cmd, void __user *argp) { mm_segment_t old_fs = get_fs(); struct mtget get; struct mtget32 __user *umget32; struct mtpos pos; struct mtpos32 __user *upos32; unsigned long kcmd; void *karg; int err = 0; switch(cmd) { case MTIOCPOS32: kcmd = MTIOCPOS; karg = &pos; break; default: /* MTIOCGET32 */ kcmd = MTIOCGET; karg = &get; break; } set_fs (KERNEL_DS); err = sys_ioctl (fd, kcmd, (unsigned long)karg); set_fs (old_fs); if (err) return err; switch (cmd) { case MTIOCPOS32: upos32 = argp; err = __put_user(pos.mt_blkno, &upos32->mt_blkno); break; case MTIOCGET32: umget32 = argp; err = __put_user(get.mt_type, &umget32->mt_type); err |= __put_user(get.mt_resid, &umget32->mt_resid); err |= __put_user(get.mt_dsreg, &umget32->mt_dsreg); err |= __put_user(get.mt_gstat, &umget32->mt_gstat); err |= __put_user(get.mt_erreg, &umget32->mt_erreg); err |= __put_user(get.mt_fileno, &umget32->mt_fileno); err |= __put_user(get.mt_blkno, &umget32->mt_blkno); break; } return err ? -EFAULT: 0; } #endif /* CONFIG_BLOCK */ /* Bluetooth ioctls */ #define HCIUARTSETPROTO _IOW('U', 200, int) #define HCIUARTGETPROTO _IOR('U', 201, int) #define HCIUARTGETDEVICE _IOR('U', 202, int) #define HCIUARTSETFLAGS _IOW('U', 203, int) #define HCIUARTGETFLAGS _IOR('U', 204, int) #define BNEPCONNADD _IOW('B', 200, int) #define BNEPCONNDEL _IOW('B', 201, int) #define BNEPGETCONNLIST _IOR('B', 210, int) #define BNEPGETCONNINFO _IOR('B', 211, int) #define CMTPCONNADD _IOW('C', 200, int) #define CMTPCONNDEL _IOW('C', 201, int) #define CMTPGETCONNLIST _IOR('C', 210, int) #define CMTPGETCONNINFO _IOR('C', 211, int) #define HIDPCONNADD _IOW('H', 200, int) #define HIDPCONNDEL _IOW('H', 201, int) #define HIDPGETCONNLIST _IOR('H', 210, int) #define HIDPGETCONNINFO _IOR('H', 211, int) struct serial_struct32 { compat_int_t type; compat_int_t line; compat_uint_t port; compat_int_t irq; compat_int_t flags; compat_int_t xmit_fifo_size; compat_int_t custom_divisor; compat_int_t baud_base; unsigned short close_delay; char io_type; char reserved_char[1]; compat_int_t hub6; unsigned short closing_wait; /* time to wait before closing */ unsigned short closing_wait2; /* no longer used... */ compat_uint_t iomem_base; unsigned short iomem_reg_shift; unsigned int port_high; /* compat_ulong_t iomap_base FIXME */ compat_int_t reserved[1]; }; static int serial_struct_ioctl(unsigned fd, unsigned cmd, struct serial_struct32 __user *ss32) { typedef struct serial_struct SS; typedef struct serial_struct32 SS32; int err; struct serial_struct ss; mm_segment_t oldseg = get_fs(); __u32 udata; unsigned int base; if (cmd == TIOCSSERIAL) { if (!access_ok(VERIFY_READ, ss32, sizeof(SS32))) return -EFAULT; if (__copy_from_user(&ss, ss32, offsetof(SS32, iomem_base))) return -EFAULT; if (__get_user(udata, &ss32->iomem_base)) return -EFAULT; ss.iomem_base = compat_ptr(udata); if (__get_user(ss.iomem_reg_shift, &ss32->iomem_reg_shift) || __get_user(ss.port_high, &ss32->port_high)) return -EFAULT; ss.iomap_base = 0UL; } set_fs(KERNEL_DS); err = sys_ioctl(fd,cmd,(unsigned long)(&ss)); set_fs(oldseg); if (cmd == TIOCGSERIAL && err >= 0) { if (!access_ok(VERIFY_WRITE, ss32, sizeof(SS32))) return -EFAULT; if (__copy_to_user(ss32,&ss,offsetof(SS32,iomem_base))) return -EFAULT; base = (unsigned long)ss.iomem_base >> 32 ? 0xffffffff : (unsigned)(unsigned long)ss.iomem_base; if (__put_user(base, &ss32->iomem_base) || __put_user(ss.iomem_reg_shift, &ss32->iomem_reg_shift) || __put_user(ss.port_high, &ss32->port_high)) return -EFAULT; } return err; } /* * I2C layer ioctls */ struct i2c_msg32 { u16 addr; u16 flags; u16 len; compat_caddr_t buf; }; struct i2c_rdwr_ioctl_data32 { compat_caddr_t msgs; /* struct i2c_msg __user *msgs */ u32 nmsgs; }; struct i2c_smbus_ioctl_data32 { u8 read_write; u8 command; u32 size; compat_caddr_t data; /* union i2c_smbus_data *data */ }; struct i2c_rdwr_aligned { struct i2c_rdwr_ioctl_data cmd; struct i2c_msg msgs[0]; }; static int do_i2c_rdwr_ioctl(unsigned int fd, unsigned int cmd, struct i2c_rdwr_ioctl_data32 __user *udata) { struct i2c_rdwr_aligned __user *tdata; struct i2c_msg __user *tmsgs; struct i2c_msg32 __user *umsgs; compat_caddr_t datap; int nmsgs, i; if (get_user(nmsgs, &udata->nmsgs)) return -EFAULT; if (nmsgs > I2C_RDRW_IOCTL_MAX_MSGS) return -EINVAL; if (get_user(datap, &udata->msgs)) return -EFAULT; umsgs = compat_ptr(datap); tdata = compat_alloc_user_space(sizeof(*tdata) + nmsgs * sizeof(struct i2c_msg)); tmsgs = &tdata->msgs[0]; if (put_user(nmsgs, &tdata->cmd.nmsgs) || put_user(tmsgs, &tdata->cmd.msgs)) return -EFAULT; for (i = 0; i < nmsgs; i++) { if (copy_in_user(&tmsgs[i].addr, &umsgs[i].addr, 3*sizeof(u16))) return -EFAULT; if (get_user(datap, &umsgs[i].buf) || put_user(compat_ptr(datap), &tmsgs[i].buf)) return -EFAULT; } return sys_ioctl(fd, cmd, (unsigned long)tdata); } static int do_i2c_smbus_ioctl(unsigned int fd, unsigned int cmd, struct i2c_smbus_ioctl_data32 __user *udata) { struct i2c_smbus_ioctl_data __user *tdata; compat_caddr_t datap; tdata = compat_alloc_user_space(sizeof(*tdata)); if (tdata == NULL) return -ENOMEM; if (!access_ok(VERIFY_WRITE, tdata, sizeof(*tdata))) return -EFAULT; if (!access_ok(VERIFY_READ, udata, sizeof(*udata))) return -EFAULT; if (__copy_in_user(&tdata->read_write, &udata->read_write, 2 * sizeof(u8))) return -EFAULT; if (__copy_in_user(&tdata->size, &udata->size, 2 * sizeof(u32))) return -EFAULT; if (__get_user(datap, &udata->data) || __put_user(compat_ptr(datap), &tdata->data)) return -EFAULT; return sys_ioctl(fd, cmd, (unsigned long)tdata); } #define RTC_IRQP_READ32 _IOR('p', 0x0b, compat_ulong_t) #define RTC_IRQP_SET32 _IOW('p', 0x0c, compat_ulong_t) #define RTC_EPOCH_READ32 _IOR('p', 0x0d, compat_ulong_t) #define RTC_EPOCH_SET32 _IOW('p', 0x0e, compat_ulong_t) static int rtc_ioctl(unsigned fd, unsigned cmd, void __user *argp) { mm_segment_t oldfs = get_fs(); compat_ulong_t val32; unsigned long kval; int ret; switch (cmd) { case RTC_IRQP_READ32: case RTC_EPOCH_READ32: set_fs(KERNEL_DS); ret = sys_ioctl(fd, (cmd == RTC_IRQP_READ32) ? RTC_IRQP_READ : RTC_EPOCH_READ, (unsigned long)&kval); set_fs(oldfs); if (ret) return ret; val32 = kval; return put_user(val32, (unsigned int __user *)argp); case RTC_IRQP_SET32: return sys_ioctl(fd, RTC_IRQP_SET, (unsigned long)argp); case RTC_EPOCH_SET32: return sys_ioctl(fd, RTC_EPOCH_SET, (unsigned long)argp); } return -ENOIOCTLCMD; } /* on ia32 l_start is on a 32-bit boundary */ #if defined(CONFIG_IA64) || defined(CONFIG_X86_64) struct space_resv_32 { __s16 l_type; __s16 l_whence; __s64 l_start __attribute__((packed)); /* len == 0 means until end of file */ __s64 l_len __attribute__((packed)); __s32 l_sysid; __u32 l_pid; __s32 l_pad[4]; /* reserve area */ }; #define FS_IOC_RESVSP_32 _IOW ('X', 40, struct space_resv_32) #define FS_IOC_RESVSP64_32 _IOW ('X', 42, struct space_resv_32) /* just account for different alignment */ static int compat_ioctl_preallocate(struct file *file, struct space_resv_32 __user *p32) { struct space_resv __user *p = compat_alloc_user_space(sizeof(*p)); if (copy_in_user(&p->l_type, &p32->l_type, sizeof(s16)) || copy_in_user(&p->l_whence, &p32->l_whence, sizeof(s16)) || copy_in_user(&p->l_start, &p32->l_start, sizeof(s64)) || copy_in_user(&p->l_len, &p32->l_len, sizeof(s64)) || copy_in_user(&p->l_sysid, &p32->l_sysid, sizeof(s32)) || copy_in_user(&p->l_pid, &p32->l_pid, sizeof(u32)) || copy_in_user(&p->l_pad, &p32->l_pad, 4*sizeof(u32))) return -EFAULT; return ioctl_preallocate(file, p); } #endif /* * simple reversible transform to make our table more evenly * distributed after sorting. */ #define XFORM(i) (((i) ^ ((i) << 27) ^ ((i) << 17)) & 0xffffffff) #define COMPATIBLE_IOCTL(cmd) XFORM(cmd), /* ioctl should not be warned about even if it's not implemented. Valid reasons to use this: - It is implemented with ->compat_ioctl on some device, but programs call it on others too. - The ioctl is not implemented in the native kernel, but programs call it commonly anyways. Most other reasons are not valid. */ #define IGNORE_IOCTL(cmd) COMPATIBLE_IOCTL(cmd) static unsigned int ioctl_pointer[] = { /* compatible ioctls first */ COMPATIBLE_IOCTL(0x4B50) /* KDGHWCLK - not in the kernel, but don't complain */ COMPATIBLE_IOCTL(0x4B51) /* KDSHWCLK - not in the kernel, but don't complain */ /* Big T */ COMPATIBLE_IOCTL(TCGETA) COMPATIBLE_IOCTL(TCSETA) COMPATIBLE_IOCTL(TCSETAW) COMPATIBLE_IOCTL(TCSETAF) COMPATIBLE_IOCTL(TCSBRK) COMPATIBLE_IOCTL(TCXONC) COMPATIBLE_IOCTL(TCFLSH) COMPATIBLE_IOCTL(TCGETS) COMPATIBLE_IOCTL(TCSETS) COMPATIBLE_IOCTL(TCSETSW) COMPATIBLE_IOCTL(TCSETSF) COMPATIBLE_IOCTL(TIOCLINUX) COMPATIBLE_IOCTL(TIOCSBRK) COMPATIBLE_IOCTL(TIOCGDEV) COMPATIBLE_IOCTL(TIOCCBRK) COMPATIBLE_IOCTL(TIOCGSID) COMPATIBLE_IOCTL(TIOCGICOUNT) /* Little t */ COMPATIBLE_IOCTL(TIOCGETD) COMPATIBLE_IOCTL(TIOCSETD) COMPATIBLE_IOCTL(TIOCEXCL) COMPATIBLE_IOCTL(TIOCNXCL) COMPATIBLE_IOCTL(TIOCCONS) COMPATIBLE_IOCTL(TIOCGSOFTCAR) COMPATIBLE_IOCTL(TIOCSSOFTCAR) COMPATIBLE_IOCTL(TIOCSWINSZ) COMPATIBLE_IOCTL(TIOCGWINSZ) COMPATIBLE_IOCTL(TIOCMGET) COMPATIBLE_IOCTL(TIOCMBIC) COMPATIBLE_IOCTL(TIOCMBIS) COMPATIBLE_IOCTL(TIOCMSET) COMPATIBLE_IOCTL(TIOCPKT) COMPATIBLE_IOCTL(TIOCNOTTY) COMPATIBLE_IOCTL(TIOCSTI) COMPATIBLE_IOCTL(TIOCOUTQ) COMPATIBLE_IOCTL(TIOCSPGRP) COMPATIBLE_IOCTL(TIOCGPGRP) COMPATIBLE_IOCTL(TIOCGPTN) COMPATIBLE_IOCTL(TIOCSPTLCK) COMPATIBLE_IOCTL(TIOCSERGETLSR) COMPATIBLE_IOCTL(TIOCSIG) #ifdef TIOCSRS485 COMPATIBLE_IOCTL(TIOCSRS485) #endif #ifdef TIOCGRS485 COMPATIBLE_IOCTL(TIOCGRS485) #endif #ifdef TCGETS2 COMPATIBLE_IOCTL(TCGETS2) COMPATIBLE_IOCTL(TCSETS2) COMPATIBLE_IOCTL(TCSETSW2) COMPATIBLE_IOCTL(TCSETSF2) #endif /* Little f */ COMPATIBLE_IOCTL(FIOCLEX) COMPATIBLE_IOCTL(FIONCLEX) COMPATIBLE_IOCTL(FIOASYNC) COMPATIBLE_IOCTL(FIONBIO) COMPATIBLE_IOCTL(FIONREAD) /* This is also TIOCINQ */ COMPATIBLE_IOCTL(FS_IOC_FIEMAP) /* 0x00 */ COMPATIBLE_IOCTL(FIBMAP) COMPATIBLE_IOCTL(FIGETBSZ) /* 'X' - originally XFS but some now in the VFS */ COMPATIBLE_IOCTL(FIFREEZE) COMPATIBLE_IOCTL(FITHAW) COMPATIBLE_IOCTL(KDGETKEYCODE) COMPATIBLE_IOCTL(KDSETKEYCODE) COMPATIBLE_IOCTL(KDGKBTYPE) COMPATIBLE_IOCTL(KDGETMODE) COMPATIBLE_IOCTL(KDGKBMODE) COMPATIBLE_IOCTL(KDGKBMETA) COMPATIBLE_IOCTL(KDGKBENT) COMPATIBLE_IOCTL(KDSKBENT) COMPATIBLE_IOCTL(KDGKBSENT) COMPATIBLE_IOCTL(KDSKBSENT) COMPATIBLE_IOCTL(KDGKBDIACR) COMPATIBLE_IOCTL(KDSKBDIACR) COMPATIBLE_IOCTL(KDGKBDIACRUC) COMPATIBLE_IOCTL(KDSKBDIACRUC) COMPATIBLE_IOCTL(KDKBDREP) COMPATIBLE_IOCTL(KDGKBLED) COMPATIBLE_IOCTL(KDGETLED) #ifdef CONFIG_BLOCK /* Big S */ COMPATIBLE_IOCTL(SCSI_IOCTL_GET_IDLUN) COMPATIBLE_IOCTL(SCSI_IOCTL_DOORLOCK) COMPATIBLE_IOCTL(SCSI_IOCTL_DOORUNLOCK) COMPATIBLE_IOCTL(SCSI_IOCTL_TEST_UNIT_READY) COMPATIBLE_IOCTL(SCSI_IOCTL_GET_BUS_NUMBER) COMPATIBLE_IOCTL(SCSI_IOCTL_SEND_COMMAND) COMPATIBLE_IOCTL(SCSI_IOCTL_PROBE_HOST) COMPATIBLE_IOCTL(SCSI_IOCTL_GET_PCI) #endif /* Big V (don't complain on serial console) */ IGNORE_IOCTL(VT_OPENQRY) IGNORE_IOCTL(VT_GETMODE) /* Little p (/dev/rtc, /dev/envctrl, etc.) */ COMPATIBLE_IOCTL(RTC_AIE_ON) COMPATIBLE_IOCTL(RTC_AIE_OFF) COMPATIBLE_IOCTL(RTC_UIE_ON) COMPATIBLE_IOCTL(RTC_UIE_OFF) COMPATIBLE_IOCTL(RTC_PIE_ON) COMPATIBLE_IOCTL(RTC_PIE_OFF) COMPATIBLE_IOCTL(RTC_WIE_ON) COMPATIBLE_IOCTL(RTC_WIE_OFF) COMPATIBLE_IOCTL(RTC_ALM_SET) COMPATIBLE_IOCTL(RTC_ALM_READ) COMPATIBLE_IOCTL(RTC_RD_TIME) COMPATIBLE_IOCTL(RTC_SET_TIME) COMPATIBLE_IOCTL(RTC_WKALM_SET) COMPATIBLE_IOCTL(RTC_WKALM_RD) /* * These two are only for the sbus rtc driver, but * hwclock tries them on every rtc device first when * running on sparc. On other architectures the entries * are useless but harmless. */ COMPATIBLE_IOCTL(_IOR('p', 20, int[7])) /* RTCGET */ COMPATIBLE_IOCTL(_IOW('p', 21, int[7])) /* RTCSET */ /* Little m */ COMPATIBLE_IOCTL(MTIOCTOP) /* Socket level stuff */ COMPATIBLE_IOCTL(FIOQSIZE) #ifdef CONFIG_BLOCK /* loop */ IGNORE_IOCTL(LOOP_CLR_FD) /* md calls this on random blockdevs */ IGNORE_IOCTL(RAID_VERSION) /* qemu/qemu-img might call these two on plain files for probing */ IGNORE_IOCTL(CDROM_DRIVE_STATUS) IGNORE_IOCTL(FDGETPRM32) /* SG stuff */ COMPATIBLE_IOCTL(SG_SET_TIMEOUT) COMPATIBLE_IOCTL(SG_GET_TIMEOUT) COMPATIBLE_IOCTL(SG_EMULATED_HOST) COMPATIBLE_IOCTL(SG_GET_TRANSFORM) COMPATIBLE_IOCTL(SG_SET_RESERVED_SIZE) COMPATIBLE_IOCTL(SG_GET_RESERVED_SIZE) COMPATIBLE_IOCTL(SG_GET_SCSI_ID) COMPATIBLE_IOCTL(SG_SET_FORCE_LOW_DMA) COMPATIBLE_IOCTL(SG_GET_LOW_DMA) COMPATIBLE_IOCTL(SG_SET_FORCE_PACK_ID) COMPATIBLE_IOCTL(SG_GET_PACK_ID) COMPATIBLE_IOCTL(SG_GET_NUM_WAITING) COMPATIBLE_IOCTL(SG_SET_DEBUG) COMPATIBLE_IOCTL(SG_GET_SG_TABLESIZE) COMPATIBLE_IOCTL(SG_GET_COMMAND_Q) COMPATIBLE_IOCTL(SG_SET_COMMAND_Q) COMPATIBLE_IOCTL(SG_GET_VERSION_NUM) COMPATIBLE_IOCTL(SG_NEXT_CMD_LEN) COMPATIBLE_IOCTL(SG_SCSI_RESET) COMPATIBLE_IOCTL(SG_GET_REQUEST_TABLE) COMPATIBLE_IOCTL(SG_SET_KEEP_ORPHAN) COMPATIBLE_IOCTL(SG_GET_KEEP_ORPHAN) #endif /* PPP stuff */ COMPATIBLE_IOCTL(PPPIOCGFLAGS) COMPATIBLE_IOCTL(PPPIOCSFLAGS) COMPATIBLE_IOCTL(PPPIOCGASYNCMAP) COMPATIBLE_IOCTL(PPPIOCSASYNCMAP) COMPATIBLE_IOCTL(PPPIOCGUNIT) COMPATIBLE_IOCTL(PPPIOCGRASYNCMAP) COMPATIBLE_IOCTL(PPPIOCSRASYNCMAP) COMPATIBLE_IOCTL(PPPIOCGMRU) COMPATIBLE_IOCTL(PPPIOCSMRU) COMPATIBLE_IOCTL(PPPIOCSMAXCID) COMPATIBLE_IOCTL(PPPIOCGXASYNCMAP) COMPATIBLE_IOCTL(PPPIOCSXASYNCMAP) COMPATIBLE_IOCTL(PPPIOCXFERUNIT) /* PPPIOCSCOMPRESS is translated */ COMPATIBLE_IOCTL(PPPIOCGNPMODE) COMPATIBLE_IOCTL(PPPIOCSNPMODE) COMPATIBLE_IOCTL(PPPIOCGDEBUG) COMPATIBLE_IOCTL(PPPIOCSDEBUG) /* PPPIOCSPASS is translated */ /* PPPIOCSACTIVE is translated */ /* PPPIOCGIDLE is translated */ COMPATIBLE_IOCTL(PPPIOCNEWUNIT) COMPATIBLE_IOCTL(PPPIOCATTACH) COMPATIBLE_IOCTL(PPPIOCDETACH) COMPATIBLE_IOCTL(PPPIOCSMRRU) COMPATIBLE_IOCTL(PPPIOCCONNECT) COMPATIBLE_IOCTL(PPPIOCDISCONN) COMPATIBLE_IOCTL(PPPIOCATTCHAN) COMPATIBLE_IOCTL(PPPIOCGCHAN) COMPATIBLE_IOCTL(PPPIOCGL2TPSTATS) /* PPPOX */ COMPATIBLE_IOCTL(PPPOEIOCSFWD) COMPATIBLE_IOCTL(PPPOEIOCDFWD) /* ppdev */ COMPATIBLE_IOCTL(PPSETMODE) COMPATIBLE_IOCTL(PPRSTATUS) COMPATIBLE_IOCTL(PPRCONTROL) COMPATIBLE_IOCTL(PPWCONTROL) COMPATIBLE_IOCTL(PPFCONTROL) COMPATIBLE_IOCTL(PPRDATA) COMPATIBLE_IOCTL(PPWDATA) COMPATIBLE_IOCTL(PPCLAIM) COMPATIBLE_IOCTL(PPRELEASE) COMPATIBLE_IOCTL(PPYIELD) COMPATIBLE_IOCTL(PPEXCL) COMPATIBLE_IOCTL(PPDATADIR) COMPATIBLE_IOCTL(PPNEGOT) COMPATIBLE_IOCTL(PPWCTLONIRQ) COMPATIBLE_IOCTL(PPCLRIRQ) COMPATIBLE_IOCTL(PPSETPHASE) COMPATIBLE_IOCTL(PPGETMODES) COMPATIBLE_IOCTL(PPGETMODE) COMPATIBLE_IOCTL(PPGETPHASE) COMPATIBLE_IOCTL(PPGETFLAGS) COMPATIBLE_IOCTL(PPSETFLAGS) /* Big A */ /* sparc only */ /* Big Q for sound/OSS */ COMPATIBLE_IOCTL(SNDCTL_SEQ_RESET) COMPATIBLE_IOCTL(SNDCTL_SEQ_SYNC) COMPATIBLE_IOCTL(SNDCTL_SYNTH_INFO) COMPATIBLE_IOCTL(SNDCTL_SEQ_CTRLRATE) COMPATIBLE_IOCTL(SNDCTL_SEQ_GETOUTCOUNT) COMPATIBLE_IOCTL(SNDCTL_SEQ_GETINCOUNT) COMPATIBLE_IOCTL(SNDCTL_SEQ_PERCMODE) COMPATIBLE_IOCTL(SNDCTL_FM_LOAD_INSTR) COMPATIBLE_IOCTL(SNDCTL_SEQ_TESTMIDI) COMPATIBLE_IOCTL(SNDCTL_SEQ_RESETSAMPLES) COMPATIBLE_IOCTL(SNDCTL_SEQ_NRSYNTHS) COMPATIBLE_IOCTL(SNDCTL_SEQ_NRMIDIS) COMPATIBLE_IOCTL(SNDCTL_MIDI_INFO) COMPATIBLE_IOCTL(SNDCTL_SEQ_THRESHOLD) COMPATIBLE_IOCTL(SNDCTL_SYNTH_MEMAVL) COMPATIBLE_IOCTL(SNDCTL_FM_4OP_ENABLE) COMPATIBLE_IOCTL(SNDCTL_SEQ_PANIC) COMPATIBLE_IOCTL(SNDCTL_SEQ_OUTOFBAND) COMPATIBLE_IOCTL(SNDCTL_SEQ_GETTIME) COMPATIBLE_IOCTL(SNDCTL_SYNTH_ID) COMPATIBLE_IOCTL(SNDCTL_SYNTH_CONTROL) COMPATIBLE_IOCTL(SNDCTL_SYNTH_REMOVESAMPLE) /* Big T for sound/OSS */ COMPATIBLE_IOCTL(SNDCTL_TMR_TIMEBASE) COMPATIBLE_IOCTL(SNDCTL_TMR_START) COMPATIBLE_IOCTL(SNDCTL_TMR_STOP) COMPATIBLE_IOCTL(SNDCTL_TMR_CONTINUE) COMPATIBLE_IOCTL(SNDCTL_TMR_TEMPO) COMPATIBLE_IOCTL(SNDCTL_TMR_SOURCE) COMPATIBLE_IOCTL(SNDCTL_TMR_METRONOME) COMPATIBLE_IOCTL(SNDCTL_TMR_SELECT) /* Little m for sound/OSS */ COMPATIBLE_IOCTL(SNDCTL_MIDI_PRETIME) COMPATIBLE_IOCTL(SNDCTL_MIDI_MPUMODE) COMPATIBLE_IOCTL(SNDCTL_MIDI_MPUCMD) /* Big P for sound/OSS */ COMPATIBLE_IOCTL(SNDCTL_DSP_RESET) COMPATIBLE_IOCTL(SNDCTL_DSP_SYNC) COMPATIBLE_IOCTL(SNDCTL_DSP_SPEED) COMPATIBLE_IOCTL(SNDCTL_DSP_STEREO) COMPATIBLE_IOCTL(SNDCTL_DSP_GETBLKSIZE) COMPATIBLE_IOCTL(SNDCTL_DSP_CHANNELS) COMPATIBLE_IOCTL(SOUND_PCM_WRITE_FILTER) COMPATIBLE_IOCTL(SNDCTL_DSP_POST) COMPATIBLE_IOCTL(SNDCTL_DSP_SUBDIVIDE) COMPATIBLE_IOCTL(SNDCTL_DSP_SETFRAGMENT) COMPATIBLE_IOCTL(SNDCTL_DSP_GETFMTS) COMPATIBLE_IOCTL(SNDCTL_DSP_SETFMT) COMPATIBLE_IOCTL(SNDCTL_DSP_GETOSPACE) COMPATIBLE_IOCTL(SNDCTL_DSP_GETISPACE) COMPATIBLE_IOCTL(SNDCTL_DSP_NONBLOCK) COMPATIBLE_IOCTL(SNDCTL_DSP_GETCAPS) COMPATIBLE_IOCTL(SNDCTL_DSP_GETTRIGGER) COMPATIBLE_IOCTL(SNDCTL_DSP_SETTRIGGER) COMPATIBLE_IOCTL(SNDCTL_DSP_GETIPTR) COMPATIBLE_IOCTL(SNDCTL_DSP_GETOPTR) /* SNDCTL_DSP_MAPINBUF, XXX needs translation */ /* SNDCTL_DSP_MAPOUTBUF, XXX needs translation */ COMPATIBLE_IOCTL(SNDCTL_DSP_SETSYNCRO) COMPATIBLE_IOCTL(SNDCTL_DSP_SETDUPLEX) COMPATIBLE_IOCTL(SNDCTL_DSP_GETODELAY) COMPATIBLE_IOCTL(SNDCTL_DSP_PROFILE) COMPATIBLE_IOCTL(SOUND_PCM_READ_RATE) COMPATIBLE_IOCTL(SOUND_PCM_READ_CHANNELS) COMPATIBLE_IOCTL(SOUND_PCM_READ_BITS) COMPATIBLE_IOCTL(SOUND_PCM_READ_FILTER) /* Big C for sound/OSS */ COMPATIBLE_IOCTL(SNDCTL_COPR_RESET) COMPATIBLE_IOCTL(SNDCTL_COPR_LOAD) COMPATIBLE_IOCTL(SNDCTL_COPR_RDATA) COMPATIBLE_IOCTL(SNDCTL_COPR_RCODE) COMPATIBLE_IOCTL(SNDCTL_COPR_WDATA) COMPATIBLE_IOCTL(SNDCTL_COPR_WCODE) COMPATIBLE_IOCTL(SNDCTL_COPR_RUN) COMPATIBLE_IOCTL(SNDCTL_COPR_HALT) COMPATIBLE_IOCTL(SNDCTL_COPR_SENDMSG) COMPATIBLE_IOCTL(SNDCTL_COPR_RCVMSG) /* Big M for sound/OSS */ COMPATIBLE_IOCTL(SOUND_MIXER_READ_VOLUME) COMPATIBLE_IOCTL(SOUND_MIXER_READ_BASS) COMPATIBLE_IOCTL(SOUND_MIXER_READ_TREBLE) COMPATIBLE_IOCTL(SOUND_MIXER_READ_SYNTH) COMPATIBLE_IOCTL(SOUND_MIXER_READ_PCM) COMPATIBLE_IOCTL(SOUND_MIXER_READ_SPEAKER) COMPATIBLE_IOCTL(SOUND_MIXER_READ_LINE) COMPATIBLE_IOCTL(SOUND_MIXER_READ_MIC) COMPATIBLE_IOCTL(SOUND_MIXER_READ_CD) COMPATIBLE_IOCTL(SOUND_MIXER_READ_IMIX) COMPATIBLE_IOCTL(SOUND_MIXER_READ_ALTPCM) COMPATIBLE_IOCTL(SOUND_MIXER_READ_RECLEV) COMPATIBLE_IOCTL(SOUND_MIXER_READ_IGAIN) COMPATIBLE_IOCTL(SOUND_MIXER_READ_OGAIN) COMPATIBLE_IOCTL(SOUND_MIXER_READ_LINE1) COMPATIBLE_IOCTL(SOUND_MIXER_READ_LINE2) COMPATIBLE_IOCTL(SOUND_MIXER_READ_LINE3) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_DIGITAL1)) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_DIGITAL2)) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_DIGITAL3)) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_PHONEIN)) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_PHONEOUT)) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_VIDEO)) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_RADIO)) COMPATIBLE_IOCTL(MIXER_READ(SOUND_MIXER_MONITOR)) COMPATIBLE_IOCTL(SOUND_MIXER_READ_MUTE) /* SOUND_MIXER_READ_ENHANCE, same value as READ_MUTE */ /* SOUND_MIXER_READ_LOUD, same value as READ_MUTE */ COMPATIBLE_IOCTL(SOUND_MIXER_READ_RECSRC) COMPATIBLE_IOCTL(SOUND_MIXER_READ_DEVMASK) COMPATIBLE_IOCTL(SOUND_MIXER_READ_RECMASK) COMPATIBLE_IOCTL(SOUND_MIXER_READ_STEREODEVS) COMPATIBLE_IOCTL(SOUND_MIXER_READ_CAPS) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_VOLUME) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_BASS) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_TREBLE) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_SYNTH) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_PCM) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_SPEAKER) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_LINE) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_MIC) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_CD) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_IMIX) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_ALTPCM) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_RECLEV) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_IGAIN) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_OGAIN) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_LINE1) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_LINE2) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_LINE3) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_DIGITAL1)) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_DIGITAL2)) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_DIGITAL3)) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_PHONEIN)) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_PHONEOUT)) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_VIDEO)) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_RADIO)) COMPATIBLE_IOCTL(MIXER_WRITE(SOUND_MIXER_MONITOR)) COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_MUTE) /* SOUND_MIXER_WRITE_ENHANCE, same value as WRITE_MUTE */ /* SOUND_MIXER_WRITE_LOUD, same value as WRITE_MUTE */ COMPATIBLE_IOCTL(SOUND_MIXER_WRITE_RECSRC) COMPATIBLE_IOCTL(SOUND_MIXER_INFO) COMPATIBLE_IOCTL(SOUND_OLD_MIXER_INFO) COMPATIBLE_IOCTL(SOUND_MIXER_ACCESS) COMPATIBLE_IOCTL(SOUND_MIXER_AGC) COMPATIBLE_IOCTL(SOUND_MIXER_3DSE) COMPATIBLE_IOCTL(SOUND_MIXER_PRIVATE1) COMPATIBLE_IOCTL(SOUND_MIXER_PRIVATE2) COMPATIBLE_IOCTL(SOUND_MIXER_PRIVATE3) COMPATIBLE_IOCTL(SOUND_MIXER_PRIVATE4) COMPATIBLE_IOCTL(SOUND_MIXER_PRIVATE5) COMPATIBLE_IOCTL(SOUND_MIXER_GETLEVELS) COMPATIBLE_IOCTL(SOUND_MIXER_SETLEVELS) COMPATIBLE_IOCTL(OSS_GETVERSION) /* Raw devices */ COMPATIBLE_IOCTL(RAW_SETBIND) COMPATIBLE_IOCTL(RAW_GETBIND) /* Watchdog */ COMPATIBLE_IOCTL(WDIOC_GETSUPPORT) COMPATIBLE_IOCTL(WDIOC_GETSTATUS) COMPATIBLE_IOCTL(WDIOC_GETBOOTSTATUS) COMPATIBLE_IOCTL(WDIOC_GETTEMP) COMPATIBLE_IOCTL(WDIOC_SETOPTIONS) COMPATIBLE_IOCTL(WDIOC_KEEPALIVE) COMPATIBLE_IOCTL(WDIOC_SETTIMEOUT) COMPATIBLE_IOCTL(WDIOC_GETTIMEOUT) /* Big R */ COMPATIBLE_IOCTL(RNDGETENTCNT) COMPATIBLE_IOCTL(RNDADDTOENTCNT) COMPATIBLE_IOCTL(RNDGETPOOL) COMPATIBLE_IOCTL(RNDADDENTROPY) COMPATIBLE_IOCTL(RNDZAPENTCNT) COMPATIBLE_IOCTL(RNDCLEARPOOL) /* Bluetooth */ COMPATIBLE_IOCTL(HCIDEVUP) COMPATIBLE_IOCTL(HCIDEVDOWN) COMPATIBLE_IOCTL(HCIDEVRESET) COMPATIBLE_IOCTL(HCIDEVRESTAT) COMPATIBLE_IOCTL(HCIGETDEVLIST) COMPATIBLE_IOCTL(HCIGETDEVINFO) COMPATIBLE_IOCTL(HCIGETCONNLIST) COMPATIBLE_IOCTL(HCIGETCONNINFO) COMPATIBLE_IOCTL(HCIGETAUTHINFO) COMPATIBLE_IOCTL(HCISETRAW) COMPATIBLE_IOCTL(HCISETSCAN) COMPATIBLE_IOCTL(HCISETAUTH) COMPATIBLE_IOCTL(HCISETENCRYPT) COMPATIBLE_IOCTL(HCISETPTYPE) COMPATIBLE_IOCTL(HCISETLINKPOL) COMPATIBLE_IOCTL(HCISETLINKMODE) COMPATIBLE_IOCTL(HCISETACLMTU) COMPATIBLE_IOCTL(HCISETSCOMTU) COMPATIBLE_IOCTL(HCIBLOCKADDR) COMPATIBLE_IOCTL(HCIUNBLOCKADDR) COMPATIBLE_IOCTL(HCIINQUIRY) COMPATIBLE_IOCTL(HCIUARTSETPROTO) COMPATIBLE_IOCTL(HCIUARTGETPROTO) COMPATIBLE_IOCTL(RFCOMMCREATEDEV) COMPATIBLE_IOCTL(RFCOMMRELEASEDEV) COMPATIBLE_IOCTL(RFCOMMGETDEVLIST) COMPATIBLE_IOCTL(RFCOMMGETDEVINFO) COMPATIBLE_IOCTL(RFCOMMSTEALDLC) COMPATIBLE_IOCTL(BNEPCONNADD) COMPATIBLE_IOCTL(BNEPCONNDEL) COMPATIBLE_IOCTL(BNEPGETCONNLIST) COMPATIBLE_IOCTL(BNEPGETCONNINFO) COMPATIBLE_IOCTL(CMTPCONNADD) COMPATIBLE_IOCTL(CMTPCONNDEL) COMPATIBLE_IOCTL(CMTPGETCONNLIST) COMPATIBLE_IOCTL(CMTPGETCONNINFO) COMPATIBLE_IOCTL(HIDPCONNADD) COMPATIBLE_IOCTL(HIDPCONNDEL) COMPATIBLE_IOCTL(HIDPGETCONNLIST) COMPATIBLE_IOCTL(HIDPGETCONNINFO) /* CAPI */ COMPATIBLE_IOCTL(CAPI_REGISTER) COMPATIBLE_IOCTL(CAPI_GET_MANUFACTURER) COMPATIBLE_IOCTL(CAPI_GET_VERSION) COMPATIBLE_IOCTL(CAPI_GET_SERIAL) COMPATIBLE_IOCTL(CAPI_GET_PROFILE) COMPATIBLE_IOCTL(CAPI_MANUFACTURER_CMD) COMPATIBLE_IOCTL(CAPI_GET_ERRCODE) COMPATIBLE_IOCTL(CAPI_INSTALLED) COMPATIBLE_IOCTL(CAPI_GET_FLAGS) COMPATIBLE_IOCTL(CAPI_SET_FLAGS) COMPATIBLE_IOCTL(CAPI_CLR_FLAGS) COMPATIBLE_IOCTL(CAPI_NCCI_OPENCOUNT) COMPATIBLE_IOCTL(CAPI_NCCI_GETUNIT) /* Siemens Gigaset */ COMPATIBLE_IOCTL(GIGASET_REDIR) COMPATIBLE_IOCTL(GIGASET_CONFIG) COMPATIBLE_IOCTL(GIGASET_BRKCHARS) COMPATIBLE_IOCTL(GIGASET_VERSION) /* Misc. */ COMPATIBLE_IOCTL(0x41545900) /* ATYIO_CLKR */ COMPATIBLE_IOCTL(0x41545901) /* ATYIO_CLKW */ COMPATIBLE_IOCTL(PCIIOC_CONTROLLER) COMPATIBLE_IOCTL(PCIIOC_MMAP_IS_IO) COMPATIBLE_IOCTL(PCIIOC_MMAP_IS_MEM) COMPATIBLE_IOCTL(PCIIOC_WRITE_COMBINE) /* NBD */ COMPATIBLE_IOCTL(NBD_DO_IT) COMPATIBLE_IOCTL(NBD_CLEAR_SOCK) COMPATIBLE_IOCTL(NBD_CLEAR_QUE) COMPATIBLE_IOCTL(NBD_PRINT_DEBUG) COMPATIBLE_IOCTL(NBD_DISCONNECT) /* i2c */ COMPATIBLE_IOCTL(I2C_SLAVE) COMPATIBLE_IOCTL(I2C_SLAVE_FORCE) COMPATIBLE_IOCTL(I2C_TENBIT) COMPATIBLE_IOCTL(I2C_PEC) COMPATIBLE_IOCTL(I2C_RETRIES) COMPATIBLE_IOCTL(I2C_TIMEOUT) /* hiddev */ COMPATIBLE_IOCTL(HIDIOCGVERSION) COMPATIBLE_IOCTL(HIDIOCAPPLICATION) COMPATIBLE_IOCTL(HIDIOCGDEVINFO) COMPATIBLE_IOCTL(HIDIOCGSTRING) COMPATIBLE_IOCTL(HIDIOCINITREPORT) COMPATIBLE_IOCTL(HIDIOCGREPORT) COMPATIBLE_IOCTL(HIDIOCSREPORT) COMPATIBLE_IOCTL(HIDIOCGREPORTINFO) COMPATIBLE_IOCTL(HIDIOCGFIELDINFO) COMPATIBLE_IOCTL(HIDIOCGUSAGE) COMPATIBLE_IOCTL(HIDIOCSUSAGE) COMPATIBLE_IOCTL(HIDIOCGUCODE) COMPATIBLE_IOCTL(HIDIOCGFLAG) COMPATIBLE_IOCTL(HIDIOCSFLAG) COMPATIBLE_IOCTL(HIDIOCGCOLLECTIONINDEX) COMPATIBLE_IOCTL(HIDIOCGCOLLECTIONINFO) /* dvb */ COMPATIBLE_IOCTL(AUDIO_STOP) COMPATIBLE_IOCTL(AUDIO_PLAY) COMPATIBLE_IOCTL(AUDIO_PAUSE) COMPATIBLE_IOCTL(AUDIO_CONTINUE) COMPATIBLE_IOCTL(AUDIO_SELECT_SOURCE) COMPATIBLE_IOCTL(AUDIO_SET_MUTE) COMPATIBLE_IOCTL(AUDIO_SET_AV_SYNC) COMPATIBLE_IOCTL(AUDIO_SET_BYPASS_MODE) COMPATIBLE_IOCTL(AUDIO_CHANNEL_SELECT) COMPATIBLE_IOCTL(AUDIO_GET_STATUS) COMPATIBLE_IOCTL(AUDIO_GET_CAPABILITIES) COMPATIBLE_IOCTL(AUDIO_CLEAR_BUFFER) COMPATIBLE_IOCTL(AUDIO_SET_ID) COMPATIBLE_IOCTL(AUDIO_SET_MIXER) COMPATIBLE_IOCTL(AUDIO_SET_STREAMTYPE) COMPATIBLE_IOCTL(AUDIO_SET_EXT_ID) COMPATIBLE_IOCTL(AUDIO_SET_ATTRIBUTES) COMPATIBLE_IOCTL(AUDIO_SET_KARAOKE) COMPATIBLE_IOCTL(DMX_START) COMPATIBLE_IOCTL(DMX_STOP) COMPATIBLE_IOCTL(DMX_SET_FILTER) COMPATIBLE_IOCTL(DMX_SET_PES_FILTER) COMPATIBLE_IOCTL(DMX_SET_BUFFER_SIZE) COMPATIBLE_IOCTL(DMX_GET_PES_PIDS) COMPATIBLE_IOCTL(DMX_GET_CAPS) COMPATIBLE_IOCTL(DMX_SET_SOURCE) COMPATIBLE_IOCTL(DMX_GET_STC) COMPATIBLE_IOCTL(FE_GET_INFO) COMPATIBLE_IOCTL(FE_DISEQC_RESET_OVERLOAD) COMPATIBLE_IOCTL(FE_DISEQC_SEND_MASTER_CMD) COMPATIBLE_IOCTL(FE_DISEQC_RECV_SLAVE_REPLY) COMPATIBLE_IOCTL(FE_DISEQC_SEND_BURST) COMPATIBLE_IOCTL(FE_SET_TONE) COMPATIBLE_IOCTL(FE_SET_VOLTAGE) COMPATIBLE_IOCTL(FE_ENABLE_HIGH_LNB_VOLTAGE) COMPATIBLE_IOCTL(FE_READ_STATUS) COMPATIBLE_IOCTL(FE_READ_BER) COMPATIBLE_IOCTL(FE_READ_SIGNAL_STRENGTH) COMPATIBLE_IOCTL(FE_READ_SNR) COMPATIBLE_IOCTL(FE_READ_UNCORRECTED_BLOCKS) COMPATIBLE_IOCTL(FE_SET_FRONTEND) COMPATIBLE_IOCTL(FE_GET_FRONTEND) COMPATIBLE_IOCTL(FE_GET_EVENT) COMPATIBLE_IOCTL(FE_DISHNETWORK_SEND_LEGACY_CMD) COMPATIBLE_IOCTL(VIDEO_STOP) COMPATIBLE_IOCTL(VIDEO_PLAY) COMPATIBLE_IOCTL(VIDEO_FREEZE) COMPATIBLE_IOCTL(VIDEO_CONTINUE) COMPATIBLE_IOCTL(VIDEO_SELECT_SOURCE) COMPATIBLE_IOCTL(VIDEO_SET_BLANK) COMPATIBLE_IOCTL(VIDEO_GET_STATUS) COMPATIBLE_IOCTL(VIDEO_SET_DISPLAY_FORMAT) COMPATIBLE_IOCTL(VIDEO_FAST_FORWARD) COMPATIBLE_IOCTL(VIDEO_SLOWMOTION) COMPATIBLE_IOCTL(VIDEO_GET_CAPABILITIES) COMPATIBLE_IOCTL(VIDEO_CLEAR_BUFFER) COMPATIBLE_IOCTL(VIDEO_SET_ID) COMPATIBLE_IOCTL(VIDEO_SET_STREAMTYPE) COMPATIBLE_IOCTL(VIDEO_SET_FORMAT) COMPATIBLE_IOCTL(VIDEO_SET_SYSTEM) COMPATIBLE_IOCTL(VIDEO_SET_HIGHLIGHT) COMPATIBLE_IOCTL(VIDEO_SET_SPU) COMPATIBLE_IOCTL(VIDEO_GET_NAVI) COMPATIBLE_IOCTL(VIDEO_SET_ATTRIBUTES) COMPATIBLE_IOCTL(VIDEO_GET_SIZE) COMPATIBLE_IOCTL(VIDEO_GET_FRAME_RATE) /* joystick */ COMPATIBLE_IOCTL(JSIOCGVERSION) COMPATIBLE_IOCTL(JSIOCGAXES) COMPATIBLE_IOCTL(JSIOCGBUTTONS) COMPATIBLE_IOCTL(JSIOCGNAME(0)) #ifdef TIOCGLTC COMPATIBLE_IOCTL(TIOCGLTC) COMPATIBLE_IOCTL(TIOCSLTC) #endif #ifdef TIOCSTART /* * For these two we have definitions in ioctls.h and/or termios.h on * some architectures but no actual implemention. Some applications * like bash call them if they are defined in the headers, so we provide * entries here to avoid syslog message spew. */ COMPATIBLE_IOCTL(TIOCSTART) COMPATIBLE_IOCTL(TIOCSTOP) #endif /* fat 'r' ioctls. These are handled by fat with ->compat_ioctl, but we don't want warnings on other file systems. So declare them as compatible here. */ #define VFAT_IOCTL_READDIR_BOTH32 _IOR('r', 1, struct compat_dirent[2]) #define VFAT_IOCTL_READDIR_SHORT32 _IOR('r', 2, struct compat_dirent[2]) IGNORE_IOCTL(VFAT_IOCTL_READDIR_BOTH32) IGNORE_IOCTL(VFAT_IOCTL_READDIR_SHORT32) #ifdef CONFIG_SPARC /* Sparc framebuffers, handled in sbusfb_compat_ioctl() */ IGNORE_IOCTL(FBIOGTYPE) IGNORE_IOCTL(FBIOSATTR) IGNORE_IOCTL(FBIOGATTR) IGNORE_IOCTL(FBIOSVIDEO) IGNORE_IOCTL(FBIOGVIDEO) IGNORE_IOCTL(FBIOSCURPOS) IGNORE_IOCTL(FBIOGCURPOS) IGNORE_IOCTL(FBIOGCURMAX) IGNORE_IOCTL(FBIOPUTCMAP32) IGNORE_IOCTL(FBIOGETCMAP32) IGNORE_IOCTL(FBIOSCURSOR32) IGNORE_IOCTL(FBIOGCURSOR32) #endif }; /* * Convert common ioctl arguments based on their command number * * Please do not add any code in here. Instead, implement * a compat_ioctl operation in the place that handleѕ the * ioctl for the native case. */ static long do_ioctl_trans(int fd, unsigned int cmd, unsigned long arg, struct file *file) { void __user *argp = compat_ptr(arg); switch (cmd) { case PPPIOCGIDLE32: return ppp_gidle(fd, cmd, argp); case PPPIOCSCOMPRESS32: return ppp_scompress(fd, cmd, argp); case PPPIOCSPASS32: case PPPIOCSACTIVE32: return ppp_sock_fprog_ioctl_trans(fd, cmd, argp); #ifdef CONFIG_BLOCK case SG_IO: return sg_ioctl_trans(fd, cmd, argp); case SG_GET_REQUEST_TABLE: return sg_grt_trans(fd, cmd, argp); case MTIOCGET32: case MTIOCPOS32: return mt_ioctl_trans(fd, cmd, argp); #endif /* Serial */ case TIOCGSERIAL: case TIOCSSERIAL: return serial_struct_ioctl(fd, cmd, argp); /* i2c */ case I2C_FUNCS: return w_long(fd, cmd, argp); case I2C_RDWR: return do_i2c_rdwr_ioctl(fd, cmd, argp); case I2C_SMBUS: return do_i2c_smbus_ioctl(fd, cmd, argp); /* Not implemented in the native kernel */ case RTC_IRQP_READ32: case RTC_IRQP_SET32: case RTC_EPOCH_READ32: case RTC_EPOCH_SET32: return rtc_ioctl(fd, cmd, argp); /* dvb */ case VIDEO_GET_EVENT: return do_video_get_event(fd, cmd, argp); case VIDEO_STILLPICTURE: return do_video_stillpicture(fd, cmd, argp); case VIDEO_SET_SPU_PALETTE: return do_video_set_spu_palette(fd, cmd, argp); } /* * These take an integer instead of a pointer as 'arg', * so we must not do a compat_ptr() translation. */ switch (cmd) { /* Big T */ case TCSBRKP: case TIOCMIWAIT: case TIOCSCTTY: /* RAID */ case HOT_REMOVE_DISK: case HOT_ADD_DISK: case SET_DISK_FAULTY: case SET_BITMAP_FILE: /* Big K */ case KDSIGACCEPT: case KIOCSOUND: case KDMKTONE: case KDSETMODE: case KDSKBMODE: case KDSKBMETA: case KDSKBLED: case KDSETLED: /* NBD */ case NBD_SET_SOCK: case NBD_SET_BLKSIZE: case NBD_SET_SIZE: case NBD_SET_SIZE_BLOCKS: return do_vfs_ioctl(file, fd, cmd, arg); } return -ENOIOCTLCMD; } static int compat_ioctl_check_table(unsigned int xcmd) { int i; const int max = ARRAY_SIZE(ioctl_pointer) - 1; BUILD_BUG_ON(max >= (1 << 16)); /* guess initial offset into table, assuming a normalized distribution */ i = ((xcmd >> 16) * max) >> 16; /* do linear search up first, until greater or equal */ while (ioctl_pointer[i] < xcmd && i < max) i++; /* then do linear search down */ while (ioctl_pointer[i] > xcmd && i > 0) i--; return ioctl_pointer[i] == xcmd; } asmlinkage long compat_sys_ioctl(unsigned int fd, unsigned int cmd, unsigned long arg) { struct fd f = fdget(fd); int error = -EBADF; if (!f.file) goto out; /* RED-PEN how should LSM module know it's handling 32bit? */ error = security_file_ioctl(f.file, cmd, arg); if (error) goto out_fput; /* * To allow the compat_ioctl handlers to be self contained * we need to check the common ioctls here first. * Just handle them with the standard handlers below. */ switch (cmd) { case FIOCLEX: case FIONCLEX: case FIONBIO: case FIOASYNC: case FIOQSIZE: break; #if defined(CONFIG_IA64) || defined(CONFIG_X86_64) case FS_IOC_RESVSP_32: case FS_IOC_RESVSP64_32: error = compat_ioctl_preallocate(f.file, compat_ptr(arg)); goto out_fput; #else case FS_IOC_RESVSP: case FS_IOC_RESVSP64: error = ioctl_preallocate(f.file, compat_ptr(arg)); goto out_fput; #endif case FIBMAP: case FIGETBSZ: case FIONREAD: if (S_ISREG(f.file->f_path.dentry->d_inode->i_mode)) break; /*FALL THROUGH*/ default: if (f.file->f_op && f.file->f_op->compat_ioctl) { error = f.file->f_op->compat_ioctl(f.file, cmd, arg); if (error != -ENOIOCTLCMD) goto out_fput; } if (!f.file->f_op || !f.file->f_op->unlocked_ioctl) goto do_ioctl; break; } if (compat_ioctl_check_table(XFORM(cmd))) goto found_handler; error = do_ioctl_trans(fd, cmd, arg, f.file); if (error == -ENOIOCTLCMD) error = -ENOTTY; goto out_fput; found_handler: arg = (unsigned long)compat_ptr(arg); do_ioctl: error = do_vfs_ioctl(f.file, fd, cmd, arg); out_fput: fdput(f); out: return error; } static int __init init_sys32_ioctl_cmp(const void *p, const void *q) { unsigned int a, b; a = *(unsigned int *)p; b = *(unsigned int *)q; if (a > b) return 1; if (a < b) return -1; return 0; } static int __init init_sys32_ioctl(void) { sort(ioctl_pointer, ARRAY_SIZE(ioctl_pointer), sizeof(*ioctl_pointer), init_sys32_ioctl_cmp, NULL); return 0; } __initcall(init_sys32_ioctl);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5609_0
crossvul-cpp_data_bad_2490_3
/* Copyright (c) 2001 Matej Pfajfar. * Copyright (c) 2001-2004, Roger Dingledine. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. * Copyright (c) 2007-2016, The Tor Project, Inc. */ /* See LICENSE for licensing information */ /** * \file nodelist.c * * \brief Structures and functions for tracking what we know about the routers * on the Tor network, and correlating information from networkstatus, * routerinfo, and microdescs. * * The key structure here is node_t: that's the canonical way to refer * to a Tor relay that we might want to build a circuit through. Every * node_t has either a routerinfo_t, or a routerstatus_t from the current * networkstatus consensus. If it has a routerstatus_t, it will also * need to have a microdesc_t before you can use it for circuits. * * The nodelist_t is a global singleton that maps identities to node_t * objects. Access them with the node_get_*() functions. The nodelist_t * is maintained by calls throughout the codebase * * Generally, other code should not have to reach inside a node_t to * see what information it has. Instead, you should call one of the * many accessor functions that works on a generic node_t. If there * isn't one that does what you need, it's better to make such a function, * and then use it. * * For historical reasons, some of the functions that select a node_t * from the list of all usable node_t objects are in the routerlist.c * module, since they originally selected a routerinfo_t. (TODO: They * should move!) * * (TODO: Perhaps someday we should abstract the remaining ways of * talking about a relay to also be node_t instances. Those would be * routerstatus_t as used for directory requests, and dir_server_t as * used for authorities and fallback directories.) */ #include "or.h" #include "address.h" #include "config.h" #include "control.h" #include "dirserv.h" #include "entrynodes.h" #include "geoip.h" #include "main.h" #include "microdesc.h" #include "networkstatus.h" #include "nodelist.h" #include "policies.h" #include "protover.h" #include "rendservice.h" #include "router.h" #include "routerlist.h" #include "routerset.h" #include "torcert.h" #include <string.h> static void nodelist_drop_node(node_t *node, int remove_from_ht); static void node_free(node_t *node); /** count_usable_descriptors counts descriptors with these flag(s) */ typedef enum { /* All descriptors regardless of flags */ USABLE_DESCRIPTOR_ALL = 0, /* Only descriptors with the Exit flag */ USABLE_DESCRIPTOR_EXIT_ONLY = 1 } usable_descriptor_t; static void count_usable_descriptors(int *num_present, int *num_usable, smartlist_t *descs_out, const networkstatus_t *consensus, const or_options_t *options, time_t now, routerset_t *in_set, usable_descriptor_t exit_only); static void update_router_have_minimum_dir_info(void); static double get_frac_paths_needed_for_circs(const or_options_t *options, const networkstatus_t *ns); /** A nodelist_t holds a node_t object for every router we're "willing to use * for something". Specifically, it should hold a node_t for every node that * is currently in the routerlist, or currently in the consensus we're using. */ typedef struct nodelist_t { /* A list of all the nodes. */ smartlist_t *nodes; /* Hash table to map from node ID digest to node. */ HT_HEAD(nodelist_map, node_t) nodes_by_id; } nodelist_t; static inline unsigned int node_id_hash(const node_t *node) { return (unsigned) siphash24g(node->identity, DIGEST_LEN); } static inline unsigned int node_id_eq(const node_t *node1, const node_t *node2) { return tor_memeq(node1->identity, node2->identity, DIGEST_LEN); } HT_PROTOTYPE(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq) HT_GENERATE2(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq, 0.6, tor_reallocarray_, tor_free_) /** The global nodelist. */ static nodelist_t *the_nodelist=NULL; /** Create an empty nodelist if we haven't done so already. */ static void init_nodelist(void) { if (PREDICT_UNLIKELY(the_nodelist == NULL)) { the_nodelist = tor_malloc_zero(sizeof(nodelist_t)); HT_INIT(nodelist_map, &the_nodelist->nodes_by_id); the_nodelist->nodes = smartlist_new(); } } /** As node_get_by_id, but returns a non-const pointer */ node_t * node_get_mutable_by_id(const char *identity_digest) { node_t search, *node; if (PREDICT_UNLIKELY(the_nodelist == NULL)) return NULL; memcpy(&search.identity, identity_digest, DIGEST_LEN); node = HT_FIND(nodelist_map, &the_nodelist->nodes_by_id, &search); return node; } /** Return the node_t whose identity is <b>identity_digest</b>, or NULL * if no such node exists. */ MOCK_IMPL(const node_t *, node_get_by_id,(const char *identity_digest)) { return node_get_mutable_by_id(identity_digest); } /** Internal: return the node_t whose identity_digest is * <b>identity_digest</b>. If none exists, create a new one, add it to the * nodelist, and return it. * * Requires that the nodelist be initialized. */ static node_t * node_get_or_create(const char *identity_digest) { node_t *node; if ((node = node_get_mutable_by_id(identity_digest))) return node; node = tor_malloc_zero(sizeof(node_t)); memcpy(node->identity, identity_digest, DIGEST_LEN); HT_INSERT(nodelist_map, &the_nodelist->nodes_by_id, node); smartlist_add(the_nodelist->nodes, node); node->nodelist_idx = smartlist_len(the_nodelist->nodes) - 1; node->country = -1; return node; } /** Called when a node's address changes. */ static void node_addrs_changed(node_t *node) { node->last_reachable = node->last_reachable6 = 0; node->country = -1; } /** Add <b>ri</b> to an appropriate node in the nodelist. If we replace an * old routerinfo, and <b>ri_old_out</b> is not NULL, set *<b>ri_old_out</b> * to the previous routerinfo. */ node_t * nodelist_set_routerinfo(routerinfo_t *ri, routerinfo_t **ri_old_out) { node_t *node; const char *id_digest; int had_router = 0; tor_assert(ri); init_nodelist(); id_digest = ri->cache_info.identity_digest; node = node_get_or_create(id_digest); if (node->ri) { if (!routers_have_same_or_addrs(node->ri, ri)) { node_addrs_changed(node); } had_router = 1; if (ri_old_out) *ri_old_out = node->ri; } else { if (ri_old_out) *ri_old_out = NULL; } node->ri = ri; if (node->country == -1) node_set_country(node); if (authdir_mode(get_options()) && !had_router) { const char *discard=NULL; uint32_t status = dirserv_router_get_status(ri, &discard, LOG_INFO); dirserv_set_node_flags_from_authoritative_status(node, status); } return node; } /** Set the appropriate node_t to use <b>md</b> as its microdescriptor. * * Called when a new microdesc has arrived and the usable consensus flavor * is "microdesc". **/ node_t * nodelist_add_microdesc(microdesc_t *md) { networkstatus_t *ns = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC); const routerstatus_t *rs; node_t *node; if (ns == NULL) return NULL; init_nodelist(); /* Microdescriptors don't carry an identity digest, so we need to figure * it out by looking up the routerstatus. */ rs = router_get_consensus_status_by_descriptor_digest(ns, md->digest); if (rs == NULL) return NULL; node = node_get_mutable_by_id(rs->identity_digest); if (node) { if (node->md) node->md->held_by_nodes--; node->md = md; md->held_by_nodes++; } return node; } /** Tell the nodelist that the current usable consensus is <b>ns</b>. * This makes the nodelist change all of the routerstatus entries for * the nodes, drop nodes that no longer have enough info to get used, * and grab microdescriptors into nodes as appropriate. */ void nodelist_set_consensus(networkstatus_t *ns) { const or_options_t *options = get_options(); int authdir = authdir_mode_v3(options); init_nodelist(); if (ns->flavor == FLAV_MICRODESC) (void) get_microdesc_cache(); /* Make sure it exists first. */ SMARTLIST_FOREACH(the_nodelist->nodes, node_t *, node, node->rs = NULL); SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) { node_t *node = node_get_or_create(rs->identity_digest); node->rs = rs; if (ns->flavor == FLAV_MICRODESC) { if (node->md == NULL || tor_memneq(node->md->digest,rs->descriptor_digest,DIGEST256_LEN)) { if (node->md) node->md->held_by_nodes--; node->md = microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest); if (node->md) node->md->held_by_nodes++; } } node_set_country(node); /* If we're not an authdir, believe others. */ if (!authdir) { node->is_valid = rs->is_valid; node->is_running = rs->is_flagged_running; node->is_fast = rs->is_fast; node->is_stable = rs->is_stable; node->is_possible_guard = rs->is_possible_guard; node->is_exit = rs->is_exit; node->is_bad_exit = rs->is_bad_exit; node->is_hs_dir = rs->is_hs_dir; node->ipv6_preferred = 0; if (fascist_firewall_prefer_ipv6_orport(options) && (tor_addr_is_null(&rs->ipv6_addr) == 0 || (node->md && tor_addr_is_null(&node->md->ipv6_addr) == 0))) node->ipv6_preferred = 1; } } SMARTLIST_FOREACH_END(rs); nodelist_purge(); if (! authdir) { SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { /* We have no routerstatus for this router. Clear flags so we can skip * it, maybe.*/ if (!node->rs) { tor_assert(node->ri); /* if it had only an md, or nothing, purge * would have removed it. */ if (node->ri->purpose == ROUTER_PURPOSE_GENERAL) { /* Clear all flags. */ node->is_valid = node->is_running = node->is_hs_dir = node->is_fast = node->is_stable = node->is_possible_guard = node->is_exit = node->is_bad_exit = node->ipv6_preferred = 0; } } } SMARTLIST_FOREACH_END(node); } } /** Helper: return true iff a node has a usable amount of information*/ static inline int node_is_usable(const node_t *node) { return (node->rs) || (node->ri); } /** Tell the nodelist that <b>md</b> is no longer a microdescriptor for the * node with <b>identity_digest</b>. */ void nodelist_remove_microdesc(const char *identity_digest, microdesc_t *md) { node_t *node = node_get_mutable_by_id(identity_digest); if (node && node->md == md) { node->md = NULL; md->held_by_nodes--; } } /** Tell the nodelist that <b>ri</b> is no longer in the routerlist. */ void nodelist_remove_routerinfo(routerinfo_t *ri) { node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest); if (node && node->ri == ri) { node->ri = NULL; if (! node_is_usable(node)) { nodelist_drop_node(node, 1); node_free(node); } } } /** Remove <b>node</b> from the nodelist. (Asserts that it was there to begin * with.) */ static void nodelist_drop_node(node_t *node, int remove_from_ht) { node_t *tmp; int idx; if (remove_from_ht) { tmp = HT_REMOVE(nodelist_map, &the_nodelist->nodes_by_id, node); tor_assert(tmp == node); } idx = node->nodelist_idx; tor_assert(idx >= 0); tor_assert(node == smartlist_get(the_nodelist->nodes, idx)); smartlist_del(the_nodelist->nodes, idx); if (idx < smartlist_len(the_nodelist->nodes)) { tmp = smartlist_get(the_nodelist->nodes, idx); tmp->nodelist_idx = idx; } node->nodelist_idx = -1; } /** Return a newly allocated smartlist of the nodes that have <b>md</b> as * their microdescriptor. */ smartlist_t * nodelist_find_nodes_with_microdesc(const microdesc_t *md) { smartlist_t *result = smartlist_new(); if (the_nodelist == NULL) return result; SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { if (node->md == md) { smartlist_add(result, node); } } SMARTLIST_FOREACH_END(node); return result; } /** Release storage held by <b>node</b> */ static void node_free(node_t *node) { if (!node) return; if (node->md) node->md->held_by_nodes--; tor_assert(node->nodelist_idx == -1); tor_free(node); } /** Remove all entries from the nodelist that don't have enough info to be * usable for anything. */ void nodelist_purge(void) { node_t **iter; if (PREDICT_UNLIKELY(the_nodelist == NULL)) return; /* Remove the non-usable nodes. */ for (iter = HT_START(nodelist_map, &the_nodelist->nodes_by_id); iter; ) { node_t *node = *iter; if (node->md && !node->rs) { /* An md is only useful if there is an rs. */ node->md->held_by_nodes--; node->md = NULL; } if (node_is_usable(node)) { iter = HT_NEXT(nodelist_map, &the_nodelist->nodes_by_id, iter); } else { iter = HT_NEXT_RMV(nodelist_map, &the_nodelist->nodes_by_id, iter); nodelist_drop_node(node, 0); node_free(node); } } nodelist_assert_ok(); } /** Release all storage held by the nodelist. */ void nodelist_free_all(void) { if (PREDICT_UNLIKELY(the_nodelist == NULL)) return; HT_CLEAR(nodelist_map, &the_nodelist->nodes_by_id); SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { node->nodelist_idx = -1; node_free(node); } SMARTLIST_FOREACH_END(node); smartlist_free(the_nodelist->nodes); tor_free(the_nodelist); } /** Check that the nodelist is internally consistent, and consistent with * the directory info it's derived from. */ void nodelist_assert_ok(void) { routerlist_t *rl = router_get_routerlist(); networkstatus_t *ns = networkstatus_get_latest_consensus(); digestmap_t *dm; if (!the_nodelist) return; dm = digestmap_new(); /* every routerinfo in rl->routers should be in the nodelist. */ if (rl) { SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) { const node_t *node = node_get_by_id(ri->cache_info.identity_digest); tor_assert(node && node->ri == ri); tor_assert(fast_memeq(ri->cache_info.identity_digest, node->identity, DIGEST_LEN)); tor_assert(! digestmap_get(dm, node->identity)); digestmap_set(dm, node->identity, (void*)node); } SMARTLIST_FOREACH_END(ri); } /* every routerstatus in ns should be in the nodelist */ if (ns) { SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) { const node_t *node = node_get_by_id(rs->identity_digest); tor_assert(node && node->rs == rs); tor_assert(fast_memeq(rs->identity_digest, node->identity, DIGEST_LEN)); digestmap_set(dm, node->identity, (void*)node); if (ns->flavor == FLAV_MICRODESC) { /* If it's a microdesc consensus, every entry that has a * microdescriptor should be in the nodelist. */ microdesc_t *md = microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest); tor_assert(md == node->md); if (md) tor_assert(md->held_by_nodes >= 1); } } SMARTLIST_FOREACH_END(rs); } /* The nodelist should have no other entries, and its entries should be * well-formed. */ SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { tor_assert(digestmap_get(dm, node->identity) != NULL); tor_assert(node_sl_idx == node->nodelist_idx); } SMARTLIST_FOREACH_END(node); tor_assert((long)smartlist_len(the_nodelist->nodes) == (long)HT_SIZE(&the_nodelist->nodes_by_id)); digestmap_free(dm, NULL); } /** Return a list of a node_t * for every node we know about. The caller * MUST NOT modify the list. (You can set and clear flags in the nodes if * you must, but you must not add or remove nodes.) */ MOCK_IMPL(smartlist_t *, nodelist_get_list,(void)) { init_nodelist(); return the_nodelist->nodes; } /** Given a hex-encoded nickname of the format DIGEST, $DIGEST, $DIGEST=name, * or $DIGEST~name, return the node with the matching identity digest and * nickname (if any). Return NULL if no such node exists, or if <b>hex_id</b> * is not well-formed. */ const node_t * node_get_by_hex_id(const char *hex_id) { char digest_buf[DIGEST_LEN]; char nn_buf[MAX_NICKNAME_LEN+1]; char nn_char='\0'; if (hex_digest_nickname_decode(hex_id, digest_buf, &nn_char, nn_buf)==0) { const node_t *node = node_get_by_id(digest_buf); if (!node) return NULL; if (nn_char) { const char *real_name = node_get_nickname(node); if (!real_name || strcasecmp(real_name, nn_buf)) return NULL; if (nn_char == '=') { const char *named_id = networkstatus_get_router_digest_by_nickname(nn_buf); if (!named_id || tor_memneq(named_id, digest_buf, DIGEST_LEN)) return NULL; } } return node; } return NULL; } /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return * the corresponding node_t, or NULL if none exists. Warn the user if * <b>warn_if_unnamed</b> is set, and they have specified a router by * nickname, but the Named flag isn't set for that router. */ MOCK_IMPL(const node_t *, node_get_by_nickname,(const char *nickname, int warn_if_unnamed)) { if (!the_nodelist) return NULL; /* Handle these cases: DIGEST, $DIGEST, $DIGEST=name, $DIGEST~name. */ { const node_t *node; if ((node = node_get_by_hex_id(nickname)) != NULL) return node; } if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) return NULL; /* Okay, so if we get here, the nickname is just a nickname. Is there * a binding for it in the consensus? */ { const char *named_id = networkstatus_get_router_digest_by_nickname(nickname); if (named_id) return node_get_by_id(named_id); } /* Is it marked as owned-by-someone-else? */ if (networkstatus_nickname_is_unnamed(nickname)) { log_info(LD_GENERAL, "The name %s is listed as Unnamed: there is some " "router that holds it, but not one listed in the current " "consensus.", escaped(nickname)); return NULL; } /* Okay, so the name is not canonical for anybody. */ { smartlist_t *matches = smartlist_new(); const node_t *choice = NULL; SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { if (!strcasecmp(node_get_nickname(node), nickname)) smartlist_add(matches, node); } SMARTLIST_FOREACH_END(node); if (smartlist_len(matches)>1 && warn_if_unnamed) { int any_unwarned = 0; SMARTLIST_FOREACH_BEGIN(matches, node_t *, node) { if (!node->name_lookup_warned) { node->name_lookup_warned = 1; any_unwarned = 1; } } SMARTLIST_FOREACH_END(node); if (any_unwarned) { log_warn(LD_CONFIG, "There are multiple matches for the name %s, " "but none is listed as Named in the directory consensus. " "Choosing one arbitrarily.", nickname); } } else if (smartlist_len(matches)==1 && warn_if_unnamed) { char fp[HEX_DIGEST_LEN+1]; node_t *node = smartlist_get(matches, 0); if (! node->name_lookup_warned) { base16_encode(fp, sizeof(fp), node->identity, DIGEST_LEN); log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the directory " "authorities do not have any key registered for this " "nickname -- so it could be used by any server, not just " "the one you meant. " "To make sure you get the same server in the future, refer " "to it by key, as \"$%s\".", nickname, fp); node->name_lookup_warned = 1; } } if (smartlist_len(matches)) choice = smartlist_get(matches, 0); smartlist_free(matches); return choice; } } /** Return the Ed25519 identity key for the provided node, or NULL if it * doesn't have one. */ const ed25519_public_key_t * node_get_ed25519_id(const node_t *node) { if (node->ri) { if (node->ri->cache_info.signing_key_cert) { const ed25519_public_key_t *pk = &node->ri->cache_info.signing_key_cert->signing_key; if (BUG(ed25519_public_key_is_zero(pk))) goto try_the_md; return pk; } } try_the_md: if (node->md) { if (node->md->ed25519_identity_pkey) { return node->md->ed25519_identity_pkey; } } return NULL; } /** Return true iff this node's Ed25519 identity matches <b>id</b>. * (An absent Ed25519 identity matches NULL or zero.) */ int node_ed25519_id_matches(const node_t *node, const ed25519_public_key_t *id) { const ed25519_public_key_t *node_id = node_get_ed25519_id(node); if (node_id == NULL || ed25519_public_key_is_zero(node_id)) { return id == NULL || ed25519_public_key_is_zero(id); } else { return id && ed25519_pubkey_eq(node_id, id); } } /** Return true iff <b>node</b> supports authenticating itself * by ed25519 ID during the link handshake in a way that we can understand * when we probe it. */ int node_supports_ed25519_link_authentication(const node_t *node) { /* XXXX Oh hm. What if some day in the future there are link handshake * versions that aren't 3 but which are ed25519 */ if (! node_get_ed25519_id(node)) return 0; if (node->ri) { const char *protos = node->ri->protocol_list; if (protos == NULL) return 0; return protocol_list_supports_protocol(protos, PRT_LINKAUTH, 3); } if (node->rs) { return node->rs->supports_ed25519_link_handshake; } tor_assert_nonfatal_unreached_once(); return 0; } /** Return the RSA ID key's SHA1 digest for the provided node. */ const uint8_t * node_get_rsa_id_digest(const node_t *node) { tor_assert(node); return (const uint8_t*)node->identity; } /** Return the nickname of <b>node</b>, or NULL if we can't find one. */ const char * node_get_nickname(const node_t *node) { tor_assert(node); if (node->rs) return node->rs->nickname; else if (node->ri) return node->ri->nickname; else return NULL; } /** Return true iff the nickname of <b>node</b> is canonical, based on the * latest consensus. */ int node_is_named(const node_t *node) { const char *named_id; const char *nickname = node_get_nickname(node); if (!nickname) return 0; named_id = networkstatus_get_router_digest_by_nickname(nickname); if (!named_id) return 0; return tor_memeq(named_id, node->identity, DIGEST_LEN); } /** Return true iff <b>node</b> appears to be a directory authority or * directory cache */ int node_is_dir(const node_t *node) { if (node->rs) { routerstatus_t * rs = node->rs; /* This is true if supports_tunnelled_dir_requests is true which * indicates that we support directory request tunnelled or through the * DirPort. */ return rs->is_v2_dir; } else if (node->ri) { routerinfo_t * ri = node->ri; /* Both tunnelled request is supported or DirPort is set. */ return ri->supports_tunnelled_dir_requests; } else { return 0; } } /** Return true iff <b>node</b> has either kind of usable descriptor -- that * is, a routerdescriptor or a microdescriptor. */ int node_has_descriptor(const node_t *node) { return (node->ri || (node->rs && node->md)); } /** Return the router_purpose of <b>node</b>. */ int node_get_purpose(const node_t *node) { if (node->ri) return node->ri->purpose; else return ROUTER_PURPOSE_GENERAL; } /** Compute the verbose ("extended") nickname of <b>node</b> and store it * into the MAX_VERBOSE_NICKNAME_LEN+1 character buffer at * <b>verbose_name_out</b> */ void node_get_verbose_nickname(const node_t *node, char *verbose_name_out) { const char *nickname = node_get_nickname(node); int is_named = node_is_named(node); verbose_name_out[0] = '$'; base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, node->identity, DIGEST_LEN); if (!nickname) return; verbose_name_out[1+HEX_DIGEST_LEN] = is_named ? '=' : '~'; strlcpy(verbose_name_out+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1); } /** Compute the verbose ("extended") nickname of node with * given <b>id_digest</b> and store it into the MAX_VERBOSE_NICKNAME_LEN+1 * character buffer at <b>verbose_name_out</b> * * If node_get_by_id() returns NULL, base 16 encoding of * <b>id_digest</b> is returned instead. */ void node_get_verbose_nickname_by_id(const char *id_digest, char *verbose_name_out) { const node_t *node = node_get_by_id(id_digest); if (!node) { verbose_name_out[0] = '$'; base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN); } else { node_get_verbose_nickname(node, verbose_name_out); } } /** Return true iff it seems that <b>node</b> allows circuits to exit * through it directlry from the client. */ int node_allows_single_hop_exits(const node_t *node) { if (node && node->ri) return node->ri->allow_single_hop_exits; else return 0; } /** Return true iff it seems that <b>node</b> has an exit policy that doesn't * actually permit anything to exit, or we don't know its exit policy */ int node_exit_policy_rejects_all(const node_t *node) { if (node->rejects_all) return 1; if (node->ri) return node->ri->policy_is_reject_star; else if (node->md) return node->md->exit_policy == NULL || short_policy_is_reject_star(node->md->exit_policy); else return 1; } /** Return true iff the exit policy for <b>node</b> is such that we can treat * rejecting an address of type <b>family</b> unexpectedly as a sign of that * node's failure. */ int node_exit_policy_is_exact(const node_t *node, sa_family_t family) { if (family == AF_UNSPEC) { return 1; /* Rejecting an address but not telling us what address * is a bad sign. */ } else if (family == AF_INET) { return node->ri != NULL; } else if (family == AF_INET6) { return 0; } tor_fragile_assert(); return 1; } /* Check if the "addr" and port_field fields from r are a valid non-listening * address/port. If so, set valid to true and add a newly allocated * tor_addr_port_t containing "addr" and port_field to sl. * "addr" is an IPv4 host-order address and port_field is a uint16_t. * r is typically a routerinfo_t or routerstatus_t. */ #define SL_ADD_NEW_IPV4_AP(r, port_field, sl, valid) \ STMT_BEGIN \ if (tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \ valid = 1; \ tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \ tor_addr_from_ipv4h(&ap->addr, (r)->addr); \ ap->port = (r)->port_field; \ smartlist_add((sl), ap); \ } \ STMT_END /* Check if the "addr" and port_field fields from r are a valid non-listening * address/port. If so, set valid to true and add a newly allocated * tor_addr_port_t containing "addr" and port_field to sl. * "addr" is a tor_addr_t and port_field is a uint16_t. * r is typically a routerinfo_t or routerstatus_t. */ #define SL_ADD_NEW_IPV6_AP(r, port_field, sl, valid) \ STMT_BEGIN \ if (tor_addr_port_is_valid(&(r)->ipv6_addr, (r)->port_field, 0)) { \ valid = 1; \ tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \ tor_addr_copy(&ap->addr, &(r)->ipv6_addr); \ ap->port = (r)->port_field; \ smartlist_add((sl), ap); \ } \ STMT_END /** Return list of tor_addr_port_t with all OR ports (in the sense IP * addr + TCP port) for <b>node</b>. Caller must free all elements * using tor_free() and free the list using smartlist_free(). * * XXX this is potentially a memory fragmentation hog -- if on * critical path consider the option of having the caller allocate the * memory */ smartlist_t * node_get_all_orports(const node_t *node) { smartlist_t *sl = smartlist_new(); int valid = 0; /* Find a valid IPv4 address and port */ if (node->ri != NULL) { SL_ADD_NEW_IPV4_AP(node->ri, or_port, sl, valid); } /* If we didn't find a valid address/port in the ri, try the rs */ if (!valid && node->rs != NULL) { SL_ADD_NEW_IPV4_AP(node->rs, or_port, sl, valid); } /* Find a valid IPv6 address and port */ valid = 0; if (node->ri != NULL) { SL_ADD_NEW_IPV6_AP(node->ri, ipv6_orport, sl, valid); } if (!valid && node->rs != NULL) { SL_ADD_NEW_IPV6_AP(node->rs, ipv6_orport, sl, valid); } if (!valid && node->md != NULL) { SL_ADD_NEW_IPV6_AP(node->md, ipv6_orport, sl, valid); } return sl; } #undef SL_ADD_NEW_IPV4_AP #undef SL_ADD_NEW_IPV6_AP /** Wrapper around node_get_prim_orport for backward compatibility. */ void node_get_addr(const node_t *node, tor_addr_t *addr_out) { tor_addr_port_t ap; node_get_prim_orport(node, &ap); tor_addr_copy(addr_out, &ap.addr); } /** Return the host-order IPv4 address for <b>node</b>, or 0 if it doesn't * seem to have one. */ uint32_t node_get_prim_addr_ipv4h(const node_t *node) { /* Don't check the ORPort or DirPort, as this function isn't port-specific, * and the node might have a valid IPv4 address, yet have a zero * ORPort or DirPort. */ if (node->ri && tor_addr_is_valid_ipv4h(node->ri->addr, 0)) { return node->ri->addr; } else if (node->rs && tor_addr_is_valid_ipv4h(node->rs->addr, 0)) { return node->rs->addr; } return 0; } /** Copy a string representation of an IP address for <b>node</b> into * the <b>len</b>-byte buffer at <b>buf</b>. */ void node_get_address_string(const node_t *node, char *buf, size_t len) { uint32_t ipv4_addr = node_get_prim_addr_ipv4h(node); if (tor_addr_is_valid_ipv4h(ipv4_addr, 0)) { tor_addr_t addr; tor_addr_from_ipv4h(&addr, ipv4_addr); tor_addr_to_str(buf, &addr, len, 0); } else if (len > 0) { buf[0] = '\0'; } } /** Return <b>node</b>'s declared uptime, or -1 if it doesn't seem to have * one. */ long node_get_declared_uptime(const node_t *node) { if (node->ri) return node->ri->uptime; else return -1; } /** Return <b>node</b>'s platform string, or NULL if we don't know it. */ const char * node_get_platform(const node_t *node) { /* If we wanted, we could record the version in the routerstatus_t, since * the consensus lists it. We don't, though, so this function just won't * work with microdescriptors. */ if (node->ri) return node->ri->platform; else return NULL; } /** Return <b>node</b>'s time of publication, or 0 if we don't have one. */ time_t node_get_published_on(const node_t *node) { if (node->ri) return node->ri->cache_info.published_on; else return 0; } /** Return true iff <b>node</b> is one representing this router. */ int node_is_me(const node_t *node) { return router_digest_is_me(node->identity); } /** Return <b>node</b> declared family (as a list of names), or NULL if * the node didn't declare a family. */ const smartlist_t * node_get_declared_family(const node_t *node) { if (node->ri && node->ri->declared_family) return node->ri->declared_family; else if (node->md && node->md->family) return node->md->family; else return NULL; } /* Does this node have a valid IPv6 address? * Prefer node_has_ipv6_orport() or node_has_ipv6_dirport() for * checking specific ports. */ int node_has_ipv6_addr(const node_t *node) { /* Don't check the ORPort or DirPort, as this function isn't port-specific, * and the node might have a valid IPv6 address, yet have a zero * ORPort or DirPort. */ if (node->ri && tor_addr_is_valid(&node->ri->ipv6_addr, 0)) return 1; if (node->rs && tor_addr_is_valid(&node->rs->ipv6_addr, 0)) return 1; if (node->md && tor_addr_is_valid(&node->md->ipv6_addr, 0)) return 1; return 0; } /* Does this node have a valid IPv6 ORPort? */ int node_has_ipv6_orport(const node_t *node) { tor_addr_port_t ipv6_orport; node_get_pref_ipv6_orport(node, &ipv6_orport); return tor_addr_port_is_valid_ap(&ipv6_orport, 0); } /* Does this node have a valid IPv6 DirPort? */ int node_has_ipv6_dirport(const node_t *node) { tor_addr_port_t ipv6_dirport; node_get_pref_ipv6_dirport(node, &ipv6_dirport); return tor_addr_port_is_valid_ap(&ipv6_dirport, 0); } /** Return 1 if we prefer the IPv6 address and OR TCP port of * <b>node</b>, else 0. * * We prefer the IPv6 address if the router has an IPv6 address, * and we can use IPv6 addresses, and: * i) the node_t says that it prefers IPv6 * or * ii) the router has no IPv4 OR address. * * If you don't have a node, consider looking it up. * If there is no node, use fascist_firewall_prefer_ipv6_orport(). */ int node_ipv6_or_preferred(const node_t *node) { const or_options_t *options = get_options(); tor_addr_port_t ipv4_addr; node_assert_ok(node); /* XX/teor - node->ipv6_preferred is set from * fascist_firewall_prefer_ipv6_orport() each time the consensus is loaded. */ if (!fascist_firewall_use_ipv6(options)) { return 0; } else if (node->ipv6_preferred || node_get_prim_orport(node, &ipv4_addr)) { return node_has_ipv6_orport(node); } return 0; } #define RETURN_IPV4_AP(r, port_field, ap_out) \ STMT_BEGIN \ if (r && tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \ tor_addr_from_ipv4h(&(ap_out)->addr, (r)->addr); \ (ap_out)->port = (r)->port_field; \ return 0; \ } \ STMT_END /** Copy the primary (IPv4) OR port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. Return 0 if a valid address and * port was copied, else return non-zero.*/ int node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. */ RETURN_IPV4_AP(node->ri, or_port, ap_out); RETURN_IPV4_AP(node->rs, or_port, ap_out); /* Microdescriptors only have an IPv6 address */ return -1; } /** Copy the preferred OR port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out) { tor_assert(ap_out); if (node_ipv6_or_preferred(node)) { node_get_pref_ipv6_orport(node, ap_out); } else { /* the primary ORPort is always on IPv4 */ node_get_prim_orport(node, ap_out); } } /** Copy the preferred IPv6 OR port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. * Prefer rs over md for consistency with the fascist_firewall_* functions. * Check if the address or port are valid, and try another alternative * if they are not. */ if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr, node->ri->ipv6_orport, 0)) { tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr); ap_out->port = node->ri->ipv6_orport; } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr, node->rs->ipv6_orport, 0)) { tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr); ap_out->port = node->rs->ipv6_orport; } else if (node->md && tor_addr_port_is_valid(&node->md->ipv6_addr, node->md->ipv6_orport, 0)) { tor_addr_copy(&ap_out->addr, &node->md->ipv6_addr); ap_out->port = node->md->ipv6_orport; } else { tor_addr_make_null(&ap_out->addr, AF_INET6); ap_out->port = 0; } } /** Return 1 if we prefer the IPv6 address and Dir TCP port of * <b>node</b>, else 0. * * We prefer the IPv6 address if the router has an IPv6 address, * and we can use IPv6 addresses, and: * i) the router has no IPv4 Dir address. * or * ii) our preference is for IPv6 Dir addresses. * * If there is no node, use fascist_firewall_prefer_ipv6_dirport(). */ int node_ipv6_dir_preferred(const node_t *node) { const or_options_t *options = get_options(); tor_addr_port_t ipv4_addr; node_assert_ok(node); /* node->ipv6_preferred is set from fascist_firewall_prefer_ipv6_orport(), * so we can't use it to determine DirPort IPv6 preference. * This means that bridge clients will use IPv4 DirPorts by default. */ if (!fascist_firewall_use_ipv6(options)) { return 0; } else if (node_get_prim_dirport(node, &ipv4_addr) || fascist_firewall_prefer_ipv6_dirport(get_options())) { return node_has_ipv6_dirport(node); } return 0; } /** Copy the primary (IPv4) Dir port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. Return 0 if a valid address and * port was copied, else return non-zero.*/ int node_get_prim_dirport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. */ RETURN_IPV4_AP(node->ri, dir_port, ap_out); RETURN_IPV4_AP(node->rs, dir_port, ap_out); /* Microdescriptors only have an IPv6 address */ return -1; } #undef RETURN_IPV4_AP /** Copy the preferred Dir port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_dirport(const node_t *node, tor_addr_port_t *ap_out) { tor_assert(ap_out); if (node_ipv6_dir_preferred(node)) { node_get_pref_ipv6_dirport(node, ap_out); } else { /* the primary DirPort is always on IPv4 */ node_get_prim_dirport(node, ap_out); } } /** Copy the preferred IPv6 Dir port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_ipv6_dirport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. * Prefer rs over md for consistency with the fascist_firewall_* functions. * Check if the address or port are valid, and try another alternative * if they are not. */ /* Assume IPv4 and IPv6 dirports are the same */ if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr, node->ri->dir_port, 0)) { tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr); ap_out->port = node->ri->dir_port; } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr, node->rs->dir_port, 0)) { tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr); ap_out->port = node->rs->dir_port; } else { tor_addr_make_null(&ap_out->addr, AF_INET6); ap_out->port = 0; } } /** Return true iff <b>md</b> has a curve25519 onion key. * Use node_has_curve25519_onion_key() instead of calling this directly. */ static int microdesc_has_curve25519_onion_key(const microdesc_t *md) { if (!md) { return 0; } if (!md->onion_curve25519_pkey) { return 0; } if (tor_mem_is_zero((const char*)md->onion_curve25519_pkey->public_key, CURVE25519_PUBKEY_LEN)) { return 0; } return 1; } /** Return true iff <b>node</b> has a curve25519 onion key. */ int node_has_curve25519_onion_key(const node_t *node) { if (!node) return 0; if (node->ri) return routerinfo_has_curve25519_onion_key(node->ri); else if (node->md) return microdesc_has_curve25519_onion_key(node->md); else return 0; } /** Refresh the country code of <b>ri</b>. This function MUST be called on * each router when the GeoIP database is reloaded, and on all new routers. */ void node_set_country(node_t *node) { tor_addr_t addr = TOR_ADDR_NULL; /* XXXXipv6 */ if (node->rs) tor_addr_from_ipv4h(&addr, node->rs->addr); else if (node->ri) tor_addr_from_ipv4h(&addr, node->ri->addr); node->country = geoip_get_country_by_addr(&addr); } /** Set the country code of all routers in the routerlist. */ void nodelist_refresh_countries(void) { smartlist_t *nodes = nodelist_get_list(); SMARTLIST_FOREACH(nodes, node_t *, node, node_set_country(node)); } /** Return true iff router1 and router2 have similar enough network addresses * that we should treat them as being in the same family */ static inline int addrs_in_same_network_family(const tor_addr_t *a1, const tor_addr_t *a2) { return 0 == tor_addr_compare_masked(a1, a2, 16, CMP_SEMANTIC); } /** Return true if <b>node</b>'s nickname matches <b>nickname</b> * (case-insensitive), or if <b>node's</b> identity key digest * matches a hexadecimal value stored in <b>nickname</b>. Return * false otherwise. */ static int node_nickname_matches(const node_t *node, const char *nickname) { const char *n = node_get_nickname(node); if (n && nickname[0]!='$' && !strcasecmp(n, nickname)) return 1; return hex_digest_nickname_matches(nickname, node->identity, n, node_is_named(node)); } /** Return true iff <b>node</b> is named by some nickname in <b>lst</b>. */ static inline int node_in_nickname_smartlist(const smartlist_t *lst, const node_t *node) { if (!lst) return 0; SMARTLIST_FOREACH(lst, const char *, name, { if (node_nickname_matches(node, name)) return 1; }); return 0; } /** Return true iff r1 and r2 are in the same family, but not the same * router. */ int nodes_in_same_family(const node_t *node1, const node_t *node2) { const or_options_t *options = get_options(); /* Are they in the same family because of their addresses? */ if (options->EnforceDistinctSubnets) { tor_addr_t a1, a2; node_get_addr(node1, &a1); node_get_addr(node2, &a2); if (addrs_in_same_network_family(&a1, &a2)) return 1; } /* Are they in the same family because the agree they are? */ { const smartlist_t *f1, *f2; f1 = node_get_declared_family(node1); f2 = node_get_declared_family(node2); if (f1 && f2 && node_in_nickname_smartlist(f1, node2) && node_in_nickname_smartlist(f2, node1)) return 1; } /* Are they in the same option because the user says they are? */ if (options->NodeFamilySets) { SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, { if (routerset_contains_node(rs, node1) && routerset_contains_node(rs, node2)) return 1; }); } return 0; } /** * Add all the family of <b>node</b>, including <b>node</b> itself, to * the smartlist <b>sl</b>. * * This is used to make sure we don't pick siblings in a single path, or * pick more than one relay from a family for our entry guard list. * Note that a node may be added to <b>sl</b> more than once if it is * part of <b>node</b>'s family for more than one reason. */ void nodelist_add_node_and_family(smartlist_t *sl, const node_t *node) { const smartlist_t *all_nodes = nodelist_get_list(); const smartlist_t *declared_family; const or_options_t *options = get_options(); tor_assert(node); declared_family = node_get_declared_family(node); /* Let's make sure that we have the node itself, if it's a real node. */ { const node_t *real_node = node_get_by_id(node->identity); if (real_node) smartlist_add(sl, (node_t*)real_node); } /* First, add any nodes with similar network addresses. */ if (options->EnforceDistinctSubnets) { tor_addr_t node_addr; node_get_addr(node, &node_addr); SMARTLIST_FOREACH_BEGIN(all_nodes, const node_t *, node2) { tor_addr_t a; node_get_addr(node2, &a); if (addrs_in_same_network_family(&a, &node_addr)) smartlist_add(sl, (void*)node2); } SMARTLIST_FOREACH_END(node2); } /* Now, add all nodes in the declared_family of this node, if they * also declare this node to be in their family. */ if (declared_family) { /* Add every r such that router declares familyness with node, and node * declares familyhood with router. */ SMARTLIST_FOREACH_BEGIN(declared_family, const char *, name) { const node_t *node2; const smartlist_t *family2; if (!(node2 = node_get_by_nickname(name, 0))) continue; if (!(family2 = node_get_declared_family(node2))) continue; SMARTLIST_FOREACH_BEGIN(family2, const char *, name2) { if (node_nickname_matches(node, name2)) { smartlist_add(sl, (void*)node2); break; } } SMARTLIST_FOREACH_END(name2); } SMARTLIST_FOREACH_END(name); } /* If the user declared any families locally, honor those too. */ if (options->NodeFamilySets) { SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, { if (routerset_contains_node(rs, node)) { routerset_get_all_nodes(sl, rs, NULL, 0); } }); } } /** Find a router that's up, that has this IP address, and * that allows exit to this address:port, or return NULL if there * isn't a good one. * Don't exit enclave to excluded relays -- it wouldn't actually * hurt anything, but this way there are fewer confused users. */ const node_t * router_find_exact_exit_enclave(const char *address, uint16_t port) {/*XXXX MOVE*/ uint32_t addr; struct in_addr in; tor_addr_t a; const or_options_t *options = get_options(); if (!tor_inet_aton(address, &in)) return NULL; /* it's not an IP already */ addr = ntohl(in.s_addr); tor_addr_from_ipv4h(&a, addr); SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, { if (node_get_addr_ipv4h(node) == addr && node->is_running && compare_tor_addr_to_node_policy(&a, port, node) == ADDR_POLICY_ACCEPTED && !routerset_contains_node(options->ExcludeExitNodesUnion_, node)) return node; }); return NULL; } /** Return 1 if <b>router</b> is not suitable for these parameters, else 0. * If <b>need_uptime</b> is non-zero, we require a minimum uptime. * If <b>need_capacity</b> is non-zero, we require a minimum advertised * bandwidth. * If <b>need_guard</b>, we require that the router is a possible entry guard. */ int node_is_unreliable(const node_t *node, int need_uptime, int need_capacity, int need_guard) { if (need_uptime && !node->is_stable) return 1; if (need_capacity && !node->is_fast) return 1; if (need_guard && !node->is_possible_guard) return 1; return 0; } /** Return 1 if all running sufficiently-stable routers we can use will reject * addr:port. Return 0 if any might accept it. */ int router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port, int need_uptime) { addr_policy_result_t r; SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) { if (node->is_running && !node_is_unreliable(node, need_uptime, 0, 0)) { r = compare_tor_addr_to_node_policy(addr, port, node); if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED) return 0; /* this one could be ok. good enough. */ } } SMARTLIST_FOREACH_END(node); return 1; /* all will reject. */ } /** Mark the router with ID <b>digest</b> as running or non-running * in our routerlist. */ void router_set_status(const char *digest, int up) { node_t *node; tor_assert(digest); SMARTLIST_FOREACH(router_get_fallback_dir_servers(), dir_server_t *, d, if (tor_memeq(d->digest, digest, DIGEST_LEN)) d->is_running = up); SMARTLIST_FOREACH(router_get_trusted_dir_servers(), dir_server_t *, d, if (tor_memeq(d->digest, digest, DIGEST_LEN)) d->is_running = up); node = node_get_mutable_by_id(digest); if (node) { #if 0 log_debug(LD_DIR,"Marking router %s as %s.", node_describe(node), up ? "up" : "down"); #endif if (!up && node_is_me(node) && !net_is_disabled()) log_warn(LD_NET, "We just marked ourself as down. Are your external " "addresses reachable?"); if (bool_neq(node->is_running, up)) router_dir_info_changed(); node->is_running = up; } } /** True iff, the last time we checked whether we had enough directory info * to build circuits, the answer was "yes". If there are no exits in the * consensus, we act as if we have 100% of the exit directory info. */ static int have_min_dir_info = 0; /** Does the consensus contain nodes that can exit? */ static consensus_path_type_t have_consensus_path = CONSENSUS_PATH_UNKNOWN; /** True iff enough has changed since the last time we checked whether we had * enough directory info to build circuits that our old answer can no longer * be trusted. */ static int need_to_update_have_min_dir_info = 1; /** String describing what we're missing before we have enough directory * info. */ static char dir_info_status[512] = ""; /** Return true iff we have enough consensus information to * start building circuits. Right now, this means "a consensus that's * less than a day old, and at least 60% of router descriptors (configurable), * weighted by bandwidth. Treat the exit fraction as 100% if there are * no exits in the consensus." * To obtain the final weighted bandwidth, we multiply the * weighted bandwidth fraction for each position (guard, middle, exit). */ int router_have_minimum_dir_info(void) { static int logged_delay=0; const char *delay_fetches_msg = NULL; if (should_delay_dir_fetches(get_options(), &delay_fetches_msg)) { if (!logged_delay) log_notice(LD_DIR, "Delaying directory fetches: %s", delay_fetches_msg); logged_delay=1; strlcpy(dir_info_status, delay_fetches_msg, sizeof(dir_info_status)); return 0; } logged_delay = 0; /* reset it if we get this far */ if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) { update_router_have_minimum_dir_info(); } return have_min_dir_info; } /** Set to CONSENSUS_PATH_EXIT if there is at least one exit node * in the consensus. We update this flag in compute_frac_paths_available if * there is at least one relay that has an Exit flag in the consensus. * Used to avoid building exit circuits when they will almost certainly fail. * Set to CONSENSUS_PATH_INTERNAL if there are no exits in the consensus. * (This situation typically occurs during bootstrap of a test network.) * Set to CONSENSUS_PATH_UNKNOWN if we have never checked, or have * reason to believe our last known value was invalid or has expired. * If we're in a network with TestingDirAuthVoteExit set, * this can cause router_have_consensus_path() to be set to * CONSENSUS_PATH_EXIT, even if there are no nodes with accept exit policies. */ MOCK_IMPL(consensus_path_type_t, router_have_consensus_path, (void)) { return have_consensus_path; } /** Called when our internal view of the directory has changed. This can be * when the authorities change, networkstatuses change, the list of routerdescs * changes, or number of running routers changes. */ void router_dir_info_changed(void) { need_to_update_have_min_dir_info = 1; rend_hsdir_routers_changed(); } /** Return a string describing what we're missing before we have enough * directory info. */ const char * get_dir_info_status_string(void) { return dir_info_status; } /** Iterate over the servers listed in <b>consensus</b>, and count how many of * them seem like ones we'd use (store this in *<b>num_usable</b>), and how * many of <em>those</em> we have descriptors for (store this in * *<b>num_present</b>). * * If <b>in_set</b> is non-NULL, only consider those routers in <b>in_set</b>. * If <b>exit_only</b> is USABLE_DESCRIPTOR_EXIT_ONLY, only consider nodes * with the Exit flag. * If *<b>descs_out</b> is present, add a node_t for each usable descriptor * to it. */ static void count_usable_descriptors(int *num_present, int *num_usable, smartlist_t *descs_out, const networkstatus_t *consensus, const or_options_t *options, time_t now, routerset_t *in_set, usable_descriptor_t exit_only) { const int md = (consensus->flavor == FLAV_MICRODESC); *num_present = 0, *num_usable = 0; SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *, rs) { const node_t *node = node_get_by_id(rs->identity_digest); if (!node) continue; /* This would be a bug: every entry in the consensus is * supposed to have a node. */ if (exit_only == USABLE_DESCRIPTOR_EXIT_ONLY && ! rs->is_exit) continue; if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1)) continue; if (client_would_use_router(rs, now, options)) { const char * const digest = rs->descriptor_digest; int present; ++*num_usable; /* the consensus says we want it. */ if (md) present = NULL != microdesc_cache_lookup_by_digest256(NULL, digest); else present = NULL != router_get_by_descriptor_digest(digest); if (present) { /* we have the descriptor listed in the consensus. */ ++*num_present; } if (descs_out) smartlist_add(descs_out, (node_t*)node); } } SMARTLIST_FOREACH_END(rs); log_debug(LD_DIR, "%d usable, %d present (%s%s).", *num_usable, *num_present, md ? "microdesc" : "desc", exit_only == USABLE_DESCRIPTOR_EXIT_ONLY ? " exits" : "s"); } /** Return an estimate of which fraction of usable paths through the Tor * network we have available for use. Count how many routers seem like ones * we'd use (store this in *<b>num_usable_out</b>), and how many of * <em>those</em> we have descriptors for (store this in * *<b>num_present_out</b>.) * * If **<b>status_out</b> is present, allocate a new string and print the * available percentages of guard, middle, and exit nodes to it, noting * whether there are exits in the consensus. * If there are no exits in the consensus, we treat the exit fraction as 100%, * but set router_have_consensus_path() so that we can only build internal * paths. */ static double compute_frac_paths_available(const networkstatus_t *consensus, const or_options_t *options, time_t now, int *num_present_out, int *num_usable_out, char **status_out) { smartlist_t *guards = smartlist_new(); smartlist_t *mid = smartlist_new(); smartlist_t *exits = smartlist_new(); double f_guard, f_mid, f_exit; double f_path = 0.0; /* Used to determine whether there are any exits in the consensus */ int np = 0; /* Used to determine whether there are any exits with descriptors */ int nu = 0; const int authdir = authdir_mode_v3(options); count_usable_descriptors(num_present_out, num_usable_out, mid, consensus, options, now, NULL, USABLE_DESCRIPTOR_ALL); if (options->EntryNodes) { count_usable_descriptors(&np, &nu, guards, consensus, options, now, options->EntryNodes, USABLE_DESCRIPTOR_ALL); } else { SMARTLIST_FOREACH(mid, const node_t *, node, { if (authdir) { if (node->rs && node->rs->is_possible_guard) smartlist_add(guards, (node_t*)node); } else { if (node->is_possible_guard) smartlist_add(guards, (node_t*)node); } }); } /* All nodes with exit flag * If we're in a network with TestingDirAuthVoteExit set, * this can cause false positives on have_consensus_path, * incorrectly setting it to CONSENSUS_PATH_EXIT. This is * an unavoidable feature of forcing authorities to declare * certain nodes as exits. */ count_usable_descriptors(&np, &nu, exits, consensus, options, now, NULL, USABLE_DESCRIPTOR_EXIT_ONLY); log_debug(LD_NET, "%s: %d present, %d usable", "exits", np, nu); /* We need at least 1 exit present in the consensus to consider * building exit paths */ /* Update our understanding of whether the consensus has exits */ consensus_path_type_t old_have_consensus_path = have_consensus_path; have_consensus_path = ((nu > 0) ? CONSENSUS_PATH_EXIT : CONSENSUS_PATH_INTERNAL); if (have_consensus_path == CONSENSUS_PATH_INTERNAL && old_have_consensus_path != have_consensus_path) { log_notice(LD_NET, "The current consensus has no exit nodes. " "Tor can only build internal paths, " "such as paths to hidden services."); /* However, exit nodes can reachability self-test using this consensus, * join the network, and appear in a later consensus. This will allow * the network to build exit paths, such as paths for world wide web * browsing (as distinct from hidden service web browsing). */ } f_guard = frac_nodes_with_descriptors(guards, WEIGHT_FOR_GUARD); f_mid = frac_nodes_with_descriptors(mid, WEIGHT_FOR_MID); f_exit = frac_nodes_with_descriptors(exits, WEIGHT_FOR_EXIT); log_debug(LD_NET, "f_guard: %.2f, f_mid: %.2f, f_exit: %.2f", f_guard, f_mid, f_exit); smartlist_free(guards); smartlist_free(mid); smartlist_free(exits); if (options->ExitNodes) { double f_myexit, f_myexit_unflagged; smartlist_t *myexits= smartlist_new(); smartlist_t *myexits_unflagged = smartlist_new(); /* All nodes with exit flag in ExitNodes option */ count_usable_descriptors(&np, &nu, myexits, consensus, options, now, options->ExitNodes, USABLE_DESCRIPTOR_EXIT_ONLY); log_debug(LD_NET, "%s: %d present, %d usable", "myexits", np, nu); /* Now compute the nodes in the ExitNodes option where which we don't know * what their exit policy is, or we know it permits something. */ count_usable_descriptors(&np, &nu, myexits_unflagged, consensus, options, now, options->ExitNodes, USABLE_DESCRIPTOR_ALL); log_debug(LD_NET, "%s: %d present, %d usable", "myexits_unflagged (initial)", np, nu); SMARTLIST_FOREACH_BEGIN(myexits_unflagged, const node_t *, node) { if (node_has_descriptor(node) && node_exit_policy_rejects_all(node)) { SMARTLIST_DEL_CURRENT(myexits_unflagged, node); /* this node is not actually an exit */ np--; /* this node is unusable as an exit */ nu--; } } SMARTLIST_FOREACH_END(node); log_debug(LD_NET, "%s: %d present, %d usable", "myexits_unflagged (final)", np, nu); f_myexit= frac_nodes_with_descriptors(myexits,WEIGHT_FOR_EXIT); f_myexit_unflagged= frac_nodes_with_descriptors(myexits_unflagged,WEIGHT_FOR_EXIT); log_debug(LD_NET, "f_exit: %.2f, f_myexit: %.2f, f_myexit_unflagged: %.2f", f_exit, f_myexit, f_myexit_unflagged); /* If our ExitNodes list has eliminated every possible Exit node, and there * were some possible Exit nodes, then instead consider nodes that permit * exiting to some ports. */ if (smartlist_len(myexits) == 0 && smartlist_len(myexits_unflagged)) { f_myexit = f_myexit_unflagged; } smartlist_free(myexits); smartlist_free(myexits_unflagged); /* This is a tricky point here: we don't want to make it easy for a * directory to trickle exits to us until it learns which exits we have * configured, so require that we have a threshold both of total exits * and usable exits. */ if (f_myexit < f_exit) f_exit = f_myexit; } /* if the consensus has no exits, treat the exit fraction as 100% */ if (router_have_consensus_path() != CONSENSUS_PATH_EXIT) { f_exit = 1.0; } f_path = f_guard * f_mid * f_exit; if (status_out) tor_asprintf(status_out, "%d%% of guards bw, " "%d%% of midpoint bw, and " "%d%% of exit bw%s = " "%d%% of path bw", (int)(f_guard*100), (int)(f_mid*100), (int)(f_exit*100), (router_have_consensus_path() == CONSENSUS_PATH_EXIT ? "" : " (no exits in consensus)"), (int)(f_path*100)); return f_path; } /** We just fetched a new set of descriptors. Compute how far through * the "loading descriptors" bootstrapping phase we are, so we can inform * the controller of our progress. */ int count_loading_descriptors_progress(void) { int num_present = 0, num_usable=0; time_t now = time(NULL); const or_options_t *options = get_options(); const networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor()); double paths, fraction; if (!consensus) return 0; /* can't count descriptors if we have no list of them */ paths = compute_frac_paths_available(consensus, options, now, &num_present, &num_usable, NULL); fraction = paths / get_frac_paths_needed_for_circs(options,consensus); if (fraction > 1.0) return 0; /* it's not the number of descriptors holding us back */ return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int) (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 - BOOTSTRAP_STATUS_LOADING_DESCRIPTORS)); } /** Return the fraction of paths needed before we're willing to build * circuits, as configured in <b>options</b>, or in the consensus <b>ns</b>. */ static double get_frac_paths_needed_for_circs(const or_options_t *options, const networkstatus_t *ns) { #define DFLT_PCT_USABLE_NEEDED 60 if (options->PathsNeededToBuildCircuits >= 0.0) { return options->PathsNeededToBuildCircuits; } else { return networkstatus_get_param(ns, "min_paths_for_circs_pct", DFLT_PCT_USABLE_NEEDED, 25, 95)/100.0; } } /** Change the value of have_min_dir_info, setting it true iff we have enough * network and router information to build circuits. Clear the value of * need_to_update_have_min_dir_info. */ static void update_router_have_minimum_dir_info(void) { time_t now = time(NULL); int res; const or_options_t *options = get_options(); const networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor()); int using_md; if (!consensus) { if (!networkstatus_get_latest_consensus()) strlcpy(dir_info_status, "We have no usable consensus.", sizeof(dir_info_status)); else strlcpy(dir_info_status, "We have no recent usable consensus.", sizeof(dir_info_status)); res = 0; goto done; } using_md = consensus->flavor == FLAV_MICRODESC; if (! entry_guards_have_enough_dir_info_to_build_circuits()) { strlcpy(dir_info_status, "We're missing descriptors for some of our " "primary entry guards", sizeof(dir_info_status)); res = 0; goto done; } /* Check fraction of available paths */ { char *status = NULL; int num_present=0, num_usable=0; double paths = compute_frac_paths_available(consensus, options, now, &num_present, &num_usable, &status); if (paths < get_frac_paths_needed_for_circs(options,consensus)) { tor_snprintf(dir_info_status, sizeof(dir_info_status), "We need more %sdescriptors: we have %d/%d, and " "can only build %d%% of likely paths. (We have %s.)", using_md?"micro":"", num_present, num_usable, (int)(paths*100), status); tor_free(status); res = 0; control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0); goto done; } tor_free(status); res = 1; } done: /* If paths have just become available in this update. */ if (res && !have_min_dir_info) { control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO"); if (control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0) == 0) { log_notice(LD_DIR, "We now have enough directory information to build circuits."); } } /* If paths have just become unavailable in this update. */ if (!res && have_min_dir_info) { int quiet = directory_too_idle_to_fetch_descriptors(options, now); tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR, "Our directory information is no longer up-to-date " "enough to build circuits: %s", dir_info_status); /* a) make us log when we next complete a circuit, so we know when Tor * is back up and usable, and b) disable some activities that Tor * should only do while circuits are working, like reachability tests * and fetching bridge descriptors only over circuits. */ note_that_we_maybe_cant_complete_circuits(); have_consensus_path = CONSENSUS_PATH_UNKNOWN; control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO"); } have_min_dir_info = res; need_to_update_have_min_dir_info = 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2490_3
crossvul-cpp_data_good_2426_0
/* * kernel/sched/core.c * * Kernel scheduler and related syscalls * * Copyright (C) 1991-2002 Linus Torvalds * * 1996-12-23 Modified by Dave Grothe to fix bugs in semaphores and * make semaphores SMP safe * 1998-11-19 Implemented schedule_timeout() and related stuff * by Andrea Arcangeli * 2002-01-04 New ultra-scalable O(1) scheduler by Ingo Molnar: * hybrid priority-list and round-robin design with * an array-switch method of distributing timeslices * and per-CPU runqueues. Cleanups and useful suggestions * by Davide Libenzi, preemptible kernel bits by Robert Love. * 2003-09-03 Interactivity tuning by Con Kolivas. * 2004-04-02 Scheduler domains code by Nick Piggin * 2007-04-15 Work begun on replacing all interactivity tuning with a * fair scheduling design by Con Kolivas. * 2007-05-05 Load balancing (smp-nice) and other improvements * by Peter Williams * 2007-05-06 Interactivity improvements to CFS by Mike Galbraith * 2007-07-01 Group scheduling enhancements by Srivatsa Vaddagiri * 2007-11-29 RT balancing improvements by Steven Rostedt, Gregory Haskins, * Thomas Gleixner, Mike Kravetz */ #include <linux/mm.h> #include <linux/module.h> #include <linux/nmi.h> #include <linux/init.h> #include <linux/uaccess.h> #include <linux/highmem.h> #include <asm/mmu_context.h> #include <linux/interrupt.h> #include <linux/capability.h> #include <linux/completion.h> #include <linux/kernel_stat.h> #include <linux/debug_locks.h> #include <linux/perf_event.h> #include <linux/security.h> #include <linux/notifier.h> #include <linux/profile.h> #include <linux/freezer.h> #include <linux/vmalloc.h> #include <linux/blkdev.h> #include <linux/delay.h> #include <linux/pid_namespace.h> #include <linux/smp.h> #include <linux/threads.h> #include <linux/timer.h> #include <linux/rcupdate.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/percpu.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/sysctl.h> #include <linux/syscalls.h> #include <linux/times.h> #include <linux/tsacct_kern.h> #include <linux/kprobes.h> #include <linux/delayacct.h> #include <linux/unistd.h> #include <linux/pagemap.h> #include <linux/hrtimer.h> #include <linux/tick.h> #include <linux/debugfs.h> #include <linux/ctype.h> #include <linux/ftrace.h> #include <linux/slab.h> #include <linux/init_task.h> #include <linux/binfmts.h> #include <linux/context_tracking.h> #include <asm/switch_to.h> #include <asm/tlb.h> #include <asm/irq_regs.h> #include <asm/mutex.h> #ifdef CONFIG_PARAVIRT #include <asm/paravirt.h> #endif #include "sched.h" #include "../workqueue_internal.h" #include "../smpboot.h" #define CREATE_TRACE_POINTS #include <trace/events/sched.h> void start_bandwidth_timer(struct hrtimer *period_timer, ktime_t period) { unsigned long delta; ktime_t soft, hard, now; for (;;) { if (hrtimer_active(period_timer)) break; now = hrtimer_cb_get_time(period_timer); hrtimer_forward(period_timer, now, period); soft = hrtimer_get_softexpires(period_timer); hard = hrtimer_get_expires(period_timer); delta = ktime_to_ns(ktime_sub(hard, soft)); __hrtimer_start_range_ns(period_timer, soft, delta, HRTIMER_MODE_ABS_PINNED, 0); } } DEFINE_MUTEX(sched_domains_mutex); DEFINE_PER_CPU_SHARED_ALIGNED(struct rq, runqueues); static void update_rq_clock_task(struct rq *rq, s64 delta); void update_rq_clock(struct rq *rq) { s64 delta; if (rq->skip_clock_update > 0) return; delta = sched_clock_cpu(cpu_of(rq)) - rq->clock; rq->clock += delta; update_rq_clock_task(rq, delta); } /* * Debugging: various feature bits */ #define SCHED_FEAT(name, enabled) \ (1UL << __SCHED_FEAT_##name) * enabled | const_debug unsigned int sysctl_sched_features = #include "features.h" 0; #undef SCHED_FEAT #ifdef CONFIG_SCHED_DEBUG #define SCHED_FEAT(name, enabled) \ #name , static const char * const sched_feat_names[] = { #include "features.h" }; #undef SCHED_FEAT static int sched_feat_show(struct seq_file *m, void *v) { int i; for (i = 0; i < __SCHED_FEAT_NR; i++) { if (!(sysctl_sched_features & (1UL << i))) seq_puts(m, "NO_"); seq_printf(m, "%s ", sched_feat_names[i]); } seq_puts(m, "\n"); return 0; } #ifdef HAVE_JUMP_LABEL #define jump_label_key__true STATIC_KEY_INIT_TRUE #define jump_label_key__false STATIC_KEY_INIT_FALSE #define SCHED_FEAT(name, enabled) \ jump_label_key__##enabled , struct static_key sched_feat_keys[__SCHED_FEAT_NR] = { #include "features.h" }; #undef SCHED_FEAT static void sched_feat_disable(int i) { if (static_key_enabled(&sched_feat_keys[i])) static_key_slow_dec(&sched_feat_keys[i]); } static void sched_feat_enable(int i) { if (!static_key_enabled(&sched_feat_keys[i])) static_key_slow_inc(&sched_feat_keys[i]); } #else static void sched_feat_disable(int i) { }; static void sched_feat_enable(int i) { }; #endif /* HAVE_JUMP_LABEL */ static int sched_feat_set(char *cmp) { int i; int neg = 0; if (strncmp(cmp, "NO_", 3) == 0) { neg = 1; cmp += 3; } for (i = 0; i < __SCHED_FEAT_NR; i++) { if (strcmp(cmp, sched_feat_names[i]) == 0) { if (neg) { sysctl_sched_features &= ~(1UL << i); sched_feat_disable(i); } else { sysctl_sched_features |= (1UL << i); sched_feat_enable(i); } break; } } return i; } static ssize_t sched_feat_write(struct file *filp, const char __user *ubuf, size_t cnt, loff_t *ppos) { char buf[64]; char *cmp; int i; if (cnt > 63) cnt = 63; if (copy_from_user(&buf, ubuf, cnt)) return -EFAULT; buf[cnt] = 0; cmp = strstrip(buf); i = sched_feat_set(cmp); if (i == __SCHED_FEAT_NR) return -EINVAL; *ppos += cnt; return cnt; } static int sched_feat_open(struct inode *inode, struct file *filp) { return single_open(filp, sched_feat_show, NULL); } static const struct file_operations sched_feat_fops = { .open = sched_feat_open, .write = sched_feat_write, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static __init int sched_init_debug(void) { debugfs_create_file("sched_features", 0644, NULL, NULL, &sched_feat_fops); return 0; } late_initcall(sched_init_debug); #endif /* CONFIG_SCHED_DEBUG */ /* * Number of tasks to iterate in a single balance run. * Limited because this is done with IRQs disabled. */ const_debug unsigned int sysctl_sched_nr_migrate = 32; /* * period over which we average the RT time consumption, measured * in ms. * * default: 1s */ const_debug unsigned int sysctl_sched_time_avg = MSEC_PER_SEC; /* * period over which we measure -rt task cpu usage in us. * default: 1s */ unsigned int sysctl_sched_rt_period = 1000000; __read_mostly int scheduler_running; /* * part of the period that we allow rt tasks to run in us. * default: 0.95s */ int sysctl_sched_rt_runtime = 950000; /* * __task_rq_lock - lock the rq @p resides on. */ static inline struct rq *__task_rq_lock(struct task_struct *p) __acquires(rq->lock) { struct rq *rq; lockdep_assert_held(&p->pi_lock); for (;;) { rq = task_rq(p); raw_spin_lock(&rq->lock); if (likely(rq == task_rq(p))) return rq; raw_spin_unlock(&rq->lock); } } /* * task_rq_lock - lock p->pi_lock and lock the rq @p resides on. */ static struct rq *task_rq_lock(struct task_struct *p, unsigned long *flags) __acquires(p->pi_lock) __acquires(rq->lock) { struct rq *rq; for (;;) { raw_spin_lock_irqsave(&p->pi_lock, *flags); rq = task_rq(p); raw_spin_lock(&rq->lock); if (likely(rq == task_rq(p))) return rq; raw_spin_unlock(&rq->lock); raw_spin_unlock_irqrestore(&p->pi_lock, *flags); } } static void __task_rq_unlock(struct rq *rq) __releases(rq->lock) { raw_spin_unlock(&rq->lock); } static inline void task_rq_unlock(struct rq *rq, struct task_struct *p, unsigned long *flags) __releases(rq->lock) __releases(p->pi_lock) { raw_spin_unlock(&rq->lock); raw_spin_unlock_irqrestore(&p->pi_lock, *flags); } /* * this_rq_lock - lock this runqueue and disable interrupts. */ static struct rq *this_rq_lock(void) __acquires(rq->lock) { struct rq *rq; local_irq_disable(); rq = this_rq(); raw_spin_lock(&rq->lock); return rq; } #ifdef CONFIG_SCHED_HRTICK /* * Use HR-timers to deliver accurate preemption points. */ static void hrtick_clear(struct rq *rq) { if (hrtimer_active(&rq->hrtick_timer)) hrtimer_cancel(&rq->hrtick_timer); } /* * High-resolution timer tick. * Runs from hardirq context with interrupts disabled. */ static enum hrtimer_restart hrtick(struct hrtimer *timer) { struct rq *rq = container_of(timer, struct rq, hrtick_timer); WARN_ON_ONCE(cpu_of(rq) != smp_processor_id()); raw_spin_lock(&rq->lock); update_rq_clock(rq); rq->curr->sched_class->task_tick(rq, rq->curr, 1); raw_spin_unlock(&rq->lock); return HRTIMER_NORESTART; } #ifdef CONFIG_SMP static int __hrtick_restart(struct rq *rq) { struct hrtimer *timer = &rq->hrtick_timer; ktime_t time = hrtimer_get_softexpires(timer); return __hrtimer_start_range_ns(timer, time, 0, HRTIMER_MODE_ABS_PINNED, 0); } /* * called from hardirq (IPI) context */ static void __hrtick_start(void *arg) { struct rq *rq = arg; raw_spin_lock(&rq->lock); __hrtick_restart(rq); rq->hrtick_csd_pending = 0; raw_spin_unlock(&rq->lock); } /* * Called to set the hrtick timer state. * * called with rq->lock held and irqs disabled */ void hrtick_start(struct rq *rq, u64 delay) { struct hrtimer *timer = &rq->hrtick_timer; ktime_t time = ktime_add_ns(timer->base->get_time(), delay); hrtimer_set_expires(timer, time); if (rq == this_rq()) { __hrtick_restart(rq); } else if (!rq->hrtick_csd_pending) { __smp_call_function_single(cpu_of(rq), &rq->hrtick_csd, 0); rq->hrtick_csd_pending = 1; } } static int hotplug_hrtick(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (int)(long)hcpu; switch (action) { case CPU_UP_CANCELED: case CPU_UP_CANCELED_FROZEN: case CPU_DOWN_PREPARE: case CPU_DOWN_PREPARE_FROZEN: case CPU_DEAD: case CPU_DEAD_FROZEN: hrtick_clear(cpu_rq(cpu)); return NOTIFY_OK; } return NOTIFY_DONE; } static __init void init_hrtick(void) { hotcpu_notifier(hotplug_hrtick, 0); } #else /* * Called to set the hrtick timer state. * * called with rq->lock held and irqs disabled */ void hrtick_start(struct rq *rq, u64 delay) { __hrtimer_start_range_ns(&rq->hrtick_timer, ns_to_ktime(delay), 0, HRTIMER_MODE_REL_PINNED, 0); } static inline void init_hrtick(void) { } #endif /* CONFIG_SMP */ static void init_rq_hrtick(struct rq *rq) { #ifdef CONFIG_SMP rq->hrtick_csd_pending = 0; rq->hrtick_csd.flags = 0; rq->hrtick_csd.func = __hrtick_start; rq->hrtick_csd.info = rq; #endif hrtimer_init(&rq->hrtick_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); rq->hrtick_timer.function = hrtick; } #else /* CONFIG_SCHED_HRTICK */ static inline void hrtick_clear(struct rq *rq) { } static inline void init_rq_hrtick(struct rq *rq) { } static inline void init_hrtick(void) { } #endif /* CONFIG_SCHED_HRTICK */ /* * resched_task - mark a task 'to be rescheduled now'. * * On UP this means the setting of the need_resched flag, on SMP it * might also involve a cross-CPU call to trigger the scheduler on * the target CPU. */ void resched_task(struct task_struct *p) { int cpu; lockdep_assert_held(&task_rq(p)->lock); if (test_tsk_need_resched(p)) return; set_tsk_need_resched(p); cpu = task_cpu(p); if (cpu == smp_processor_id()) { set_preempt_need_resched(); return; } /* NEED_RESCHED must be visible before we test polling */ smp_mb(); if (!tsk_is_polling(p)) smp_send_reschedule(cpu); } void resched_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); unsigned long flags; if (!raw_spin_trylock_irqsave(&rq->lock, flags)) return; resched_task(cpu_curr(cpu)); raw_spin_unlock_irqrestore(&rq->lock, flags); } #ifdef CONFIG_SMP #ifdef CONFIG_NO_HZ_COMMON /* * In the semi idle case, use the nearest busy cpu for migrating timers * from an idle cpu. This is good for power-savings. * * We don't do similar optimization for completely idle system, as * selecting an idle cpu will add more delays to the timers than intended * (as that cpu's timer base may not be uptodate wrt jiffies etc). */ int get_nohz_timer_target(void) { int cpu = smp_processor_id(); int i; struct sched_domain *sd; rcu_read_lock(); for_each_domain(cpu, sd) { for_each_cpu(i, sched_domain_span(sd)) { if (!idle_cpu(i)) { cpu = i; goto unlock; } } } unlock: rcu_read_unlock(); return cpu; } /* * When add_timer_on() enqueues a timer into the timer wheel of an * idle CPU then this timer might expire before the next timer event * which is scheduled to wake up that CPU. In case of a completely * idle system the next event might even be infinite time into the * future. wake_up_idle_cpu() ensures that the CPU is woken up and * leaves the inner idle loop so the newly added timer is taken into * account when the CPU goes back to idle and evaluates the timer * wheel for the next timer event. */ static void wake_up_idle_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); if (cpu == smp_processor_id()) return; /* * This is safe, as this function is called with the timer * wheel base lock of (cpu) held. When the CPU is on the way * to idle and has not yet set rq->curr to idle then it will * be serialized on the timer wheel base lock and take the new * timer into account automatically. */ if (rq->curr != rq->idle) return; /* * We can set TIF_RESCHED on the idle task of the other CPU * lockless. The worst case is that the other CPU runs the * idle task through an additional NOOP schedule() */ set_tsk_need_resched(rq->idle); /* NEED_RESCHED must be visible before we test polling */ smp_mb(); if (!tsk_is_polling(rq->idle)) smp_send_reschedule(cpu); } static bool wake_up_full_nohz_cpu(int cpu) { if (tick_nohz_full_cpu(cpu)) { if (cpu != smp_processor_id() || tick_nohz_tick_stopped()) smp_send_reschedule(cpu); return true; } return false; } void wake_up_nohz_cpu(int cpu) { if (!wake_up_full_nohz_cpu(cpu)) wake_up_idle_cpu(cpu); } static inline bool got_nohz_idle_kick(void) { int cpu = smp_processor_id(); if (!test_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu))) return false; if (idle_cpu(cpu) && !need_resched()) return true; /* * We can't run Idle Load Balance on this CPU for this time so we * cancel it and clear NOHZ_BALANCE_KICK */ clear_bit(NOHZ_BALANCE_KICK, nohz_flags(cpu)); return false; } #else /* CONFIG_NO_HZ_COMMON */ static inline bool got_nohz_idle_kick(void) { return false; } #endif /* CONFIG_NO_HZ_COMMON */ #ifdef CONFIG_NO_HZ_FULL bool sched_can_stop_tick(void) { struct rq *rq; rq = this_rq(); /* Make sure rq->nr_running update is visible after the IPI */ smp_rmb(); /* More than one running task need preemption */ if (rq->nr_running > 1) return false; return true; } #endif /* CONFIG_NO_HZ_FULL */ void sched_avg_update(struct rq *rq) { s64 period = sched_avg_period(); while ((s64)(rq_clock(rq) - rq->age_stamp) > period) { /* * Inline assembly required to prevent the compiler * optimising this loop into a divmod call. * See __iter_div_u64_rem() for another example of this. */ asm("" : "+rm" (rq->age_stamp)); rq->age_stamp += period; rq->rt_avg /= 2; } } #endif /* CONFIG_SMP */ #if defined(CONFIG_RT_GROUP_SCHED) || (defined(CONFIG_FAIR_GROUP_SCHED) && \ (defined(CONFIG_SMP) || defined(CONFIG_CFS_BANDWIDTH))) /* * Iterate task_group tree rooted at *from, calling @down when first entering a * node and @up when leaving it for the final time. * * Caller must hold rcu_lock or sufficient equivalent. */ int walk_tg_tree_from(struct task_group *from, tg_visitor down, tg_visitor up, void *data) { struct task_group *parent, *child; int ret; parent = from; down: ret = (*down)(parent, data); if (ret) goto out; list_for_each_entry_rcu(child, &parent->children, siblings) { parent = child; goto down; up: continue; } ret = (*up)(parent, data); if (ret || parent == from) goto out; child = parent; parent = parent->parent; if (parent) goto up; out: return ret; } int tg_nop(struct task_group *tg, void *data) { return 0; } #endif static void set_load_weight(struct task_struct *p) { int prio = p->static_prio - MAX_RT_PRIO; struct load_weight *load = &p->se.load; /* * SCHED_IDLE tasks get minimal weight: */ if (p->policy == SCHED_IDLE) { load->weight = scale_load(WEIGHT_IDLEPRIO); load->inv_weight = WMULT_IDLEPRIO; return; } load->weight = scale_load(prio_to_weight[prio]); load->inv_weight = prio_to_wmult[prio]; } static void enqueue_task(struct rq *rq, struct task_struct *p, int flags) { update_rq_clock(rq); sched_info_queued(rq, p); p->sched_class->enqueue_task(rq, p, flags); } static void dequeue_task(struct rq *rq, struct task_struct *p, int flags) { update_rq_clock(rq); sched_info_dequeued(rq, p); p->sched_class->dequeue_task(rq, p, flags); } void activate_task(struct rq *rq, struct task_struct *p, int flags) { if (task_contributes_to_load(p)) rq->nr_uninterruptible--; enqueue_task(rq, p, flags); } void deactivate_task(struct rq *rq, struct task_struct *p, int flags) { if (task_contributes_to_load(p)) rq->nr_uninterruptible++; dequeue_task(rq, p, flags); } static void update_rq_clock_task(struct rq *rq, s64 delta) { /* * In theory, the compile should just see 0 here, and optimize out the call * to sched_rt_avg_update. But I don't trust it... */ #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) s64 steal = 0, irq_delta = 0; #endif #ifdef CONFIG_IRQ_TIME_ACCOUNTING irq_delta = irq_time_read(cpu_of(rq)) - rq->prev_irq_time; /* * Since irq_time is only updated on {soft,}irq_exit, we might run into * this case when a previous update_rq_clock() happened inside a * {soft,}irq region. * * When this happens, we stop ->clock_task and only update the * prev_irq_time stamp to account for the part that fit, so that a next * update will consume the rest. This ensures ->clock_task is * monotonic. * * It does however cause some slight miss-attribution of {soft,}irq * time, a more accurate solution would be to update the irq_time using * the current rq->clock timestamp, except that would require using * atomic ops. */ if (irq_delta > delta) irq_delta = delta; rq->prev_irq_time += irq_delta; delta -= irq_delta; #endif #ifdef CONFIG_PARAVIRT_TIME_ACCOUNTING if (static_key_false((&paravirt_steal_rq_enabled))) { u64 st; steal = paravirt_steal_clock(cpu_of(rq)); steal -= rq->prev_steal_time_rq; if (unlikely(steal > delta)) steal = delta; st = steal_ticks(steal); steal = st * TICK_NSEC; rq->prev_steal_time_rq += steal; delta -= steal; } #endif rq->clock_task += delta; #if defined(CONFIG_IRQ_TIME_ACCOUNTING) || defined(CONFIG_PARAVIRT_TIME_ACCOUNTING) if ((irq_delta + steal) && sched_feat(NONTASK_POWER)) sched_rt_avg_update(rq, irq_delta + steal); #endif } void sched_set_stop_task(int cpu, struct task_struct *stop) { struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 }; struct task_struct *old_stop = cpu_rq(cpu)->stop; if (stop) { /* * Make it appear like a SCHED_FIFO task, its something * userspace knows about and won't get confused about. * * Also, it will make PI more or less work without too * much confusion -- but then, stop work should not * rely on PI working anyway. */ sched_setscheduler_nocheck(stop, SCHED_FIFO, &param); stop->sched_class = &stop_sched_class; } cpu_rq(cpu)->stop = stop; if (old_stop) { /* * Reset it back to a normal scheduling class so that * it can die in pieces. */ old_stop->sched_class = &rt_sched_class; } } /* * __normal_prio - return the priority that is based on the static prio */ static inline int __normal_prio(struct task_struct *p) { return p->static_prio; } /* * Calculate the expected normal priority: i.e. priority * without taking RT-inheritance into account. Might be * boosted by interactivity modifiers. Changes upon fork, * setprio syscalls, and whenever the interactivity * estimator recalculates. */ static inline int normal_prio(struct task_struct *p) { int prio; if (task_has_dl_policy(p)) prio = MAX_DL_PRIO-1; else if (task_has_rt_policy(p)) prio = MAX_RT_PRIO-1 - p->rt_priority; else prio = __normal_prio(p); return prio; } /* * Calculate the current priority, i.e. the priority * taken into account by the scheduler. This value might * be boosted by RT tasks, or might be boosted by * interactivity modifiers. Will be RT if the task got * RT-boosted. If not then it returns p->normal_prio. */ static int effective_prio(struct task_struct *p) { p->normal_prio = normal_prio(p); /* * If we are RT tasks or we were boosted to RT priority, * keep the priority unchanged. Otherwise, update priority * to the normal priority: */ if (!rt_prio(p->prio)) return p->normal_prio; return p->prio; } /** * task_curr - is this task currently executing on a CPU? * @p: the task in question. * * Return: 1 if the task is currently executing. 0 otherwise. */ inline int task_curr(const struct task_struct *p) { return cpu_curr(task_cpu(p)) == p; } static inline void check_class_changed(struct rq *rq, struct task_struct *p, const struct sched_class *prev_class, int oldprio) { if (prev_class != p->sched_class) { if (prev_class->switched_from) prev_class->switched_from(rq, p); p->sched_class->switched_to(rq, p); } else if (oldprio != p->prio || dl_task(p)) p->sched_class->prio_changed(rq, p, oldprio); } void check_preempt_curr(struct rq *rq, struct task_struct *p, int flags) { const struct sched_class *class; if (p->sched_class == rq->curr->sched_class) { rq->curr->sched_class->check_preempt_curr(rq, p, flags); } else { for_each_class(class) { if (class == rq->curr->sched_class) break; if (class == p->sched_class) { resched_task(rq->curr); break; } } } /* * A queue event has occurred, and we're going to schedule. In * this case, we can save a useless back to back clock update. */ if (rq->curr->on_rq && test_tsk_need_resched(rq->curr)) rq->skip_clock_update = 1; } #ifdef CONFIG_SMP void set_task_cpu(struct task_struct *p, unsigned int new_cpu) { #ifdef CONFIG_SCHED_DEBUG /* * We should never call set_task_cpu() on a blocked task, * ttwu() will sort out the placement. */ WARN_ON_ONCE(p->state != TASK_RUNNING && p->state != TASK_WAKING && !(task_preempt_count(p) & PREEMPT_ACTIVE)); #ifdef CONFIG_LOCKDEP /* * The caller should hold either p->pi_lock or rq->lock, when changing * a task's CPU. ->pi_lock for waking tasks, rq->lock for runnable tasks. * * sched_move_task() holds both and thus holding either pins the cgroup, * see task_group(). * * Furthermore, all task_rq users should acquire both locks, see * task_rq_lock(). */ WARN_ON_ONCE(debug_locks && !(lockdep_is_held(&p->pi_lock) || lockdep_is_held(&task_rq(p)->lock))); #endif #endif trace_sched_migrate_task(p, new_cpu); if (task_cpu(p) != new_cpu) { if (p->sched_class->migrate_task_rq) p->sched_class->migrate_task_rq(p, new_cpu); p->se.nr_migrations++; perf_sw_event(PERF_COUNT_SW_CPU_MIGRATIONS, 1, NULL, 0); } __set_task_cpu(p, new_cpu); } static void __migrate_swap_task(struct task_struct *p, int cpu) { if (p->on_rq) { struct rq *src_rq, *dst_rq; src_rq = task_rq(p); dst_rq = cpu_rq(cpu); deactivate_task(src_rq, p, 0); set_task_cpu(p, cpu); activate_task(dst_rq, p, 0); check_preempt_curr(dst_rq, p, 0); } else { /* * Task isn't running anymore; make it appear like we migrated * it before it went to sleep. This means on wakeup we make the * previous cpu our targer instead of where it really is. */ p->wake_cpu = cpu; } } struct migration_swap_arg { struct task_struct *src_task, *dst_task; int src_cpu, dst_cpu; }; static int migrate_swap_stop(void *data) { struct migration_swap_arg *arg = data; struct rq *src_rq, *dst_rq; int ret = -EAGAIN; src_rq = cpu_rq(arg->src_cpu); dst_rq = cpu_rq(arg->dst_cpu); double_raw_lock(&arg->src_task->pi_lock, &arg->dst_task->pi_lock); double_rq_lock(src_rq, dst_rq); if (task_cpu(arg->dst_task) != arg->dst_cpu) goto unlock; if (task_cpu(arg->src_task) != arg->src_cpu) goto unlock; if (!cpumask_test_cpu(arg->dst_cpu, tsk_cpus_allowed(arg->src_task))) goto unlock; if (!cpumask_test_cpu(arg->src_cpu, tsk_cpus_allowed(arg->dst_task))) goto unlock; __migrate_swap_task(arg->src_task, arg->dst_cpu); __migrate_swap_task(arg->dst_task, arg->src_cpu); ret = 0; unlock: double_rq_unlock(src_rq, dst_rq); raw_spin_unlock(&arg->dst_task->pi_lock); raw_spin_unlock(&arg->src_task->pi_lock); return ret; } /* * Cross migrate two tasks */ int migrate_swap(struct task_struct *cur, struct task_struct *p) { struct migration_swap_arg arg; int ret = -EINVAL; arg = (struct migration_swap_arg){ .src_task = cur, .src_cpu = task_cpu(cur), .dst_task = p, .dst_cpu = task_cpu(p), }; if (arg.src_cpu == arg.dst_cpu) goto out; /* * These three tests are all lockless; this is OK since all of them * will be re-checked with proper locks held further down the line. */ if (!cpu_active(arg.src_cpu) || !cpu_active(arg.dst_cpu)) goto out; if (!cpumask_test_cpu(arg.dst_cpu, tsk_cpus_allowed(arg.src_task))) goto out; if (!cpumask_test_cpu(arg.src_cpu, tsk_cpus_allowed(arg.dst_task))) goto out; trace_sched_swap_numa(cur, arg.src_cpu, p, arg.dst_cpu); ret = stop_two_cpus(arg.dst_cpu, arg.src_cpu, migrate_swap_stop, &arg); out: return ret; } struct migration_arg { struct task_struct *task; int dest_cpu; }; static int migration_cpu_stop(void *data); /* * wait_task_inactive - wait for a thread to unschedule. * * If @match_state is nonzero, it's the @p->state value just checked and * not expected to change. If it changes, i.e. @p might have woken up, * then return zero. When we succeed in waiting for @p to be off its CPU, * we return a positive number (its total switch count). If a second call * a short while later returns the same number, the caller can be sure that * @p has remained unscheduled the whole time. * * The caller must ensure that the task *will* unschedule sometime soon, * else this function might spin for a *long* time. This function can't * be called with interrupts off, or it may introduce deadlock with * smp_call_function() if an IPI is sent by the same process we are * waiting to become inactive. */ unsigned long wait_task_inactive(struct task_struct *p, long match_state) { unsigned long flags; int running, on_rq; unsigned long ncsw; struct rq *rq; for (;;) { /* * We do the initial early heuristics without holding * any task-queue locks at all. We'll only try to get * the runqueue lock when things look like they will * work out! */ rq = task_rq(p); /* * If the task is actively running on another CPU * still, just relax and busy-wait without holding * any locks. * * NOTE! Since we don't hold any locks, it's not * even sure that "rq" stays as the right runqueue! * But we don't care, since "task_running()" will * return false if the runqueue has changed and p * is actually now running somewhere else! */ while (task_running(rq, p)) { if (match_state && unlikely(p->state != match_state)) return 0; cpu_relax(); } /* * Ok, time to look more closely! We need the rq * lock now, to be *sure*. If we're wrong, we'll * just go back and repeat. */ rq = task_rq_lock(p, &flags); trace_sched_wait_task(p); running = task_running(rq, p); on_rq = p->on_rq; ncsw = 0; if (!match_state || p->state == match_state) ncsw = p->nvcsw | LONG_MIN; /* sets MSB */ task_rq_unlock(rq, p, &flags); /* * If it changed from the expected state, bail out now. */ if (unlikely(!ncsw)) break; /* * Was it really running after all now that we * checked with the proper locks actually held? * * Oops. Go back and try again.. */ if (unlikely(running)) { cpu_relax(); continue; } /* * It's not enough that it's not actively running, * it must be off the runqueue _entirely_, and not * preempted! * * So if it was still runnable (but just not actively * running right now), it's preempted, and we should * yield - it could be a while. */ if (unlikely(on_rq)) { ktime_t to = ktime_set(0, NSEC_PER_SEC/HZ); set_current_state(TASK_UNINTERRUPTIBLE); schedule_hrtimeout(&to, HRTIMER_MODE_REL); continue; } /* * Ahh, all good. It wasn't running, and it wasn't * runnable, which means that it will never become * running in the future either. We're all done! */ break; } return ncsw; } /*** * kick_process - kick a running thread to enter/exit the kernel * @p: the to-be-kicked thread * * Cause a process which is running on another CPU to enter * kernel-mode, without any delay. (to get signals handled.) * * NOTE: this function doesn't have to take the runqueue lock, * because all it wants to ensure is that the remote task enters * the kernel. If the IPI races and the task has been migrated * to another CPU then no harm is done and the purpose has been * achieved as well. */ void kick_process(struct task_struct *p) { int cpu; preempt_disable(); cpu = task_cpu(p); if ((cpu != smp_processor_id()) && task_curr(p)) smp_send_reschedule(cpu); preempt_enable(); } EXPORT_SYMBOL_GPL(kick_process); #endif /* CONFIG_SMP */ #ifdef CONFIG_SMP /* * ->cpus_allowed is protected by both rq->lock and p->pi_lock */ static int select_fallback_rq(int cpu, struct task_struct *p) { int nid = cpu_to_node(cpu); const struct cpumask *nodemask = NULL; enum { cpuset, possible, fail } state = cpuset; int dest_cpu; /* * If the node that the cpu is on has been offlined, cpu_to_node() * will return -1. There is no cpu on the node, and we should * select the cpu on the other node. */ if (nid != -1) { nodemask = cpumask_of_node(nid); /* Look for allowed, online CPU in same node. */ for_each_cpu(dest_cpu, nodemask) { if (!cpu_online(dest_cpu)) continue; if (!cpu_active(dest_cpu)) continue; if (cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) return dest_cpu; } } for (;;) { /* Any allowed, online CPU? */ for_each_cpu(dest_cpu, tsk_cpus_allowed(p)) { if (!cpu_online(dest_cpu)) continue; if (!cpu_active(dest_cpu)) continue; goto out; } switch (state) { case cpuset: /* No more Mr. Nice Guy. */ cpuset_cpus_allowed_fallback(p); state = possible; break; case possible: do_set_cpus_allowed(p, cpu_possible_mask); state = fail; break; case fail: BUG(); break; } } out: if (state != cpuset) { /* * Don't tell them about moving exiting tasks or * kernel threads (both mm NULL), since they never * leave kernel. */ if (p->mm && printk_ratelimit()) { printk_sched("process %d (%s) no longer affine to cpu%d\n", task_pid_nr(p), p->comm, cpu); } } return dest_cpu; } /* * The caller (fork, wakeup) owns p->pi_lock, ->cpus_allowed is stable. */ static inline int select_task_rq(struct task_struct *p, int cpu, int sd_flags, int wake_flags) { cpu = p->sched_class->select_task_rq(p, cpu, sd_flags, wake_flags); /* * In order not to call set_task_cpu() on a blocking task we need * to rely on ttwu() to place the task on a valid ->cpus_allowed * cpu. * * Since this is common to all placement strategies, this lives here. * * [ this allows ->select_task() to simply return task_cpu(p) and * not worry about this generic constraint ] */ if (unlikely(!cpumask_test_cpu(cpu, tsk_cpus_allowed(p)) || !cpu_online(cpu))) cpu = select_fallback_rq(task_cpu(p), p); return cpu; } static void update_avg(u64 *avg, u64 sample) { s64 diff = sample - *avg; *avg += diff >> 3; } #endif static void ttwu_stat(struct task_struct *p, int cpu, int wake_flags) { #ifdef CONFIG_SCHEDSTATS struct rq *rq = this_rq(); #ifdef CONFIG_SMP int this_cpu = smp_processor_id(); if (cpu == this_cpu) { schedstat_inc(rq, ttwu_local); schedstat_inc(p, se.statistics.nr_wakeups_local); } else { struct sched_domain *sd; schedstat_inc(p, se.statistics.nr_wakeups_remote); rcu_read_lock(); for_each_domain(this_cpu, sd) { if (cpumask_test_cpu(cpu, sched_domain_span(sd))) { schedstat_inc(sd, ttwu_wake_remote); break; } } rcu_read_unlock(); } if (wake_flags & WF_MIGRATED) schedstat_inc(p, se.statistics.nr_wakeups_migrate); #endif /* CONFIG_SMP */ schedstat_inc(rq, ttwu_count); schedstat_inc(p, se.statistics.nr_wakeups); if (wake_flags & WF_SYNC) schedstat_inc(p, se.statistics.nr_wakeups_sync); #endif /* CONFIG_SCHEDSTATS */ } static void ttwu_activate(struct rq *rq, struct task_struct *p, int en_flags) { activate_task(rq, p, en_flags); p->on_rq = 1; /* if a worker is waking up, notify workqueue */ if (p->flags & PF_WQ_WORKER) wq_worker_waking_up(p, cpu_of(rq)); } /* * Mark the task runnable and perform wakeup-preemption. */ static void ttwu_do_wakeup(struct rq *rq, struct task_struct *p, int wake_flags) { check_preempt_curr(rq, p, wake_flags); trace_sched_wakeup(p, true); p->state = TASK_RUNNING; #ifdef CONFIG_SMP if (p->sched_class->task_woken) p->sched_class->task_woken(rq, p); if (rq->idle_stamp) { u64 delta = rq_clock(rq) - rq->idle_stamp; u64 max = 2*rq->max_idle_balance_cost; update_avg(&rq->avg_idle, delta); if (rq->avg_idle > max) rq->avg_idle = max; rq->idle_stamp = 0; } #endif } static void ttwu_do_activate(struct rq *rq, struct task_struct *p, int wake_flags) { #ifdef CONFIG_SMP if (p->sched_contributes_to_load) rq->nr_uninterruptible--; #endif ttwu_activate(rq, p, ENQUEUE_WAKEUP | ENQUEUE_WAKING); ttwu_do_wakeup(rq, p, wake_flags); } /* * Called in case the task @p isn't fully descheduled from its runqueue, * in this case we must do a remote wakeup. Its a 'light' wakeup though, * since all we need to do is flip p->state to TASK_RUNNING, since * the task is still ->on_rq. */ static int ttwu_remote(struct task_struct *p, int wake_flags) { struct rq *rq; int ret = 0; rq = __task_rq_lock(p); if (p->on_rq) { /* check_preempt_curr() may use rq clock */ update_rq_clock(rq); ttwu_do_wakeup(rq, p, wake_flags); ret = 1; } __task_rq_unlock(rq); return ret; } #ifdef CONFIG_SMP static void sched_ttwu_pending(void) { struct rq *rq = this_rq(); struct llist_node *llist = llist_del_all(&rq->wake_list); struct task_struct *p; raw_spin_lock(&rq->lock); while (llist) { p = llist_entry(llist, struct task_struct, wake_entry); llist = llist_next(llist); ttwu_do_activate(rq, p, 0); } raw_spin_unlock(&rq->lock); } void scheduler_ipi(void) { /* * Fold TIF_NEED_RESCHED into the preempt_count; anybody setting * TIF_NEED_RESCHED remotely (for the first time) will also send * this IPI. */ preempt_fold_need_resched(); if (llist_empty(&this_rq()->wake_list) && !tick_nohz_full_cpu(smp_processor_id()) && !got_nohz_idle_kick()) return; /* * Not all reschedule IPI handlers call irq_enter/irq_exit, since * traditionally all their work was done from the interrupt return * path. Now that we actually do some work, we need to make sure * we do call them. * * Some archs already do call them, luckily irq_enter/exit nest * properly. * * Arguably we should visit all archs and update all handlers, * however a fair share of IPIs are still resched only so this would * somewhat pessimize the simple resched case. */ irq_enter(); tick_nohz_full_check(); sched_ttwu_pending(); /* * Check if someone kicked us for doing the nohz idle load balance. */ if (unlikely(got_nohz_idle_kick())) { this_rq()->idle_balance = 1; raise_softirq_irqoff(SCHED_SOFTIRQ); } irq_exit(); } static void ttwu_queue_remote(struct task_struct *p, int cpu) { if (llist_add(&p->wake_entry, &cpu_rq(cpu)->wake_list)) smp_send_reschedule(cpu); } bool cpus_share_cache(int this_cpu, int that_cpu) { return per_cpu(sd_llc_id, this_cpu) == per_cpu(sd_llc_id, that_cpu); } #endif /* CONFIG_SMP */ static void ttwu_queue(struct task_struct *p, int cpu) { struct rq *rq = cpu_rq(cpu); #if defined(CONFIG_SMP) if (sched_feat(TTWU_QUEUE) && !cpus_share_cache(smp_processor_id(), cpu)) { sched_clock_cpu(cpu); /* sync clocks x-cpu */ ttwu_queue_remote(p, cpu); return; } #endif raw_spin_lock(&rq->lock); ttwu_do_activate(rq, p, 0); raw_spin_unlock(&rq->lock); } /** * try_to_wake_up - wake up a thread * @p: the thread to be awakened * @state: the mask of task states that can be woken * @wake_flags: wake modifier flags (WF_*) * * Put it on the run-queue if it's not already there. The "current" * thread is always on the run-queue (except when the actual * re-schedule is in progress), and as such you're allowed to do * the simpler "current->state = TASK_RUNNING" to mark yourself * runnable without the overhead of this. * * Return: %true if @p was woken up, %false if it was already running. * or @state didn't match @p's state. */ static int try_to_wake_up(struct task_struct *p, unsigned int state, int wake_flags) { unsigned long flags; int cpu, success = 0; /* * If we are going to wake up a thread waiting for CONDITION we * need to ensure that CONDITION=1 done by the caller can not be * reordered with p->state check below. This pairs with mb() in * set_current_state() the waiting thread does. */ smp_mb__before_spinlock(); raw_spin_lock_irqsave(&p->pi_lock, flags); if (!(p->state & state)) goto out; success = 1; /* we're going to change ->state */ cpu = task_cpu(p); if (p->on_rq && ttwu_remote(p, wake_flags)) goto stat; #ifdef CONFIG_SMP /* * If the owning (remote) cpu is still in the middle of schedule() with * this task as prev, wait until its done referencing the task. */ while (p->on_cpu) cpu_relax(); /* * Pairs with the smp_wmb() in finish_lock_switch(). */ smp_rmb(); p->sched_contributes_to_load = !!task_contributes_to_load(p); p->state = TASK_WAKING; if (p->sched_class->task_waking) p->sched_class->task_waking(p); cpu = select_task_rq(p, p->wake_cpu, SD_BALANCE_WAKE, wake_flags); if (task_cpu(p) != cpu) { wake_flags |= WF_MIGRATED; set_task_cpu(p, cpu); } #endif /* CONFIG_SMP */ ttwu_queue(p, cpu); stat: ttwu_stat(p, cpu, wake_flags); out: raw_spin_unlock_irqrestore(&p->pi_lock, flags); return success; } /** * try_to_wake_up_local - try to wake up a local task with rq lock held * @p: the thread to be awakened * * Put @p on the run-queue if it's not already there. The caller must * ensure that this_rq() is locked, @p is bound to this_rq() and not * the current task. */ static void try_to_wake_up_local(struct task_struct *p) { struct rq *rq = task_rq(p); if (WARN_ON_ONCE(rq != this_rq()) || WARN_ON_ONCE(p == current)) return; lockdep_assert_held(&rq->lock); if (!raw_spin_trylock(&p->pi_lock)) { raw_spin_unlock(&rq->lock); raw_spin_lock(&p->pi_lock); raw_spin_lock(&rq->lock); } if (!(p->state & TASK_NORMAL)) goto out; if (!p->on_rq) ttwu_activate(rq, p, ENQUEUE_WAKEUP); ttwu_do_wakeup(rq, p, 0); ttwu_stat(p, smp_processor_id(), 0); out: raw_spin_unlock(&p->pi_lock); } /** * wake_up_process - Wake up a specific process * @p: The process to be woken up. * * Attempt to wake up the nominated process and move it to the set of runnable * processes. * * Return: 1 if the process was woken up, 0 if it was already running. * * It may be assumed that this function implies a write memory barrier before * changing the task state if and only if any tasks are woken up. */ int wake_up_process(struct task_struct *p) { WARN_ON(task_is_stopped_or_traced(p)); return try_to_wake_up(p, TASK_NORMAL, 0); } EXPORT_SYMBOL(wake_up_process); int wake_up_state(struct task_struct *p, unsigned int state) { return try_to_wake_up(p, state, 0); } /* * Perform scheduler related setup for a newly forked process p. * p is forked by current. * * __sched_fork() is basic setup used by init_idle() too: */ static void __sched_fork(unsigned long clone_flags, struct task_struct *p) { p->on_rq = 0; p->se.on_rq = 0; p->se.exec_start = 0; p->se.sum_exec_runtime = 0; p->se.prev_sum_exec_runtime = 0; p->se.nr_migrations = 0; p->se.vruntime = 0; INIT_LIST_HEAD(&p->se.group_node); #ifdef CONFIG_SCHEDSTATS memset(&p->se.statistics, 0, sizeof(p->se.statistics)); #endif RB_CLEAR_NODE(&p->dl.rb_node); hrtimer_init(&p->dl.dl_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL); p->dl.dl_runtime = p->dl.runtime = 0; p->dl.dl_deadline = p->dl.deadline = 0; p->dl.dl_period = 0; p->dl.flags = 0; INIT_LIST_HEAD(&p->rt.run_list); #ifdef CONFIG_PREEMPT_NOTIFIERS INIT_HLIST_HEAD(&p->preempt_notifiers); #endif #ifdef CONFIG_NUMA_BALANCING if (p->mm && atomic_read(&p->mm->mm_users) == 1) { p->mm->numa_next_scan = jiffies + msecs_to_jiffies(sysctl_numa_balancing_scan_delay); p->mm->numa_scan_seq = 0; } if (clone_flags & CLONE_VM) p->numa_preferred_nid = current->numa_preferred_nid; else p->numa_preferred_nid = -1; p->node_stamp = 0ULL; p->numa_scan_seq = p->mm ? p->mm->numa_scan_seq : 0; p->numa_scan_period = sysctl_numa_balancing_scan_delay; p->numa_work.next = &p->numa_work; p->numa_faults = NULL; p->numa_faults_buffer = NULL; INIT_LIST_HEAD(&p->numa_entry); p->numa_group = NULL; #endif /* CONFIG_NUMA_BALANCING */ } #ifdef CONFIG_NUMA_BALANCING #ifdef CONFIG_SCHED_DEBUG void set_numabalancing_state(bool enabled) { if (enabled) sched_feat_set("NUMA"); else sched_feat_set("NO_NUMA"); } #else __read_mostly bool numabalancing_enabled; void set_numabalancing_state(bool enabled) { numabalancing_enabled = enabled; } #endif /* CONFIG_SCHED_DEBUG */ #ifdef CONFIG_PROC_SYSCTL int sysctl_numa_balancing(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct ctl_table t; int err; int state = numabalancing_enabled; if (write && !capable(CAP_SYS_ADMIN)) return -EPERM; t = *table; t.data = &state; err = proc_dointvec_minmax(&t, write, buffer, lenp, ppos); if (err < 0) return err; if (write) set_numabalancing_state(state); return err; } #endif #endif /* * fork()/clone()-time setup: */ int sched_fork(unsigned long clone_flags, struct task_struct *p) { unsigned long flags; int cpu = get_cpu(); __sched_fork(clone_flags, p); /* * We mark the process as running here. This guarantees that * nobody will actually run it, and a signal or other external * event cannot wake it up and insert it on the runqueue either. */ p->state = TASK_RUNNING; /* * Make sure we do not leak PI boosting priority to the child. */ p->prio = current->normal_prio; /* * Revert to default priority/policy on fork if requested. */ if (unlikely(p->sched_reset_on_fork)) { if (task_has_dl_policy(p) || task_has_rt_policy(p)) { p->policy = SCHED_NORMAL; p->static_prio = NICE_TO_PRIO(0); p->rt_priority = 0; } else if (PRIO_TO_NICE(p->static_prio) < 0) p->static_prio = NICE_TO_PRIO(0); p->prio = p->normal_prio = __normal_prio(p); set_load_weight(p); /* * We don't need the reset flag anymore after the fork. It has * fulfilled its duty: */ p->sched_reset_on_fork = 0; } if (dl_prio(p->prio)) { put_cpu(); return -EAGAIN; } else if (rt_prio(p->prio)) { p->sched_class = &rt_sched_class; } else { p->sched_class = &fair_sched_class; } if (p->sched_class->task_fork) p->sched_class->task_fork(p); /* * The child is not yet in the pid-hash so no cgroup attach races, * and the cgroup is pinned to this child due to cgroup_fork() * is ran before sched_fork(). * * Silence PROVE_RCU. */ raw_spin_lock_irqsave(&p->pi_lock, flags); set_task_cpu(p, cpu); raw_spin_unlock_irqrestore(&p->pi_lock, flags); #if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT) if (likely(sched_info_on())) memset(&p->sched_info, 0, sizeof(p->sched_info)); #endif #if defined(CONFIG_SMP) p->on_cpu = 0; #endif init_task_preempt_count(p); #ifdef CONFIG_SMP plist_node_init(&p->pushable_tasks, MAX_PRIO); RB_CLEAR_NODE(&p->pushable_dl_tasks); #endif put_cpu(); return 0; } unsigned long to_ratio(u64 period, u64 runtime) { if (runtime == RUNTIME_INF) return 1ULL << 20; /* * Doing this here saves a lot of checks in all * the calling paths, and returning zero seems * safe for them anyway. */ if (period == 0) return 0; return div64_u64(runtime << 20, period); } #ifdef CONFIG_SMP inline struct dl_bw *dl_bw_of(int i) { return &cpu_rq(i)->rd->dl_bw; } static inline int dl_bw_cpus(int i) { struct root_domain *rd = cpu_rq(i)->rd; int cpus = 0; for_each_cpu_and(i, rd->span, cpu_active_mask) cpus++; return cpus; } #else inline struct dl_bw *dl_bw_of(int i) { return &cpu_rq(i)->dl.dl_bw; } static inline int dl_bw_cpus(int i) { return 1; } #endif static inline void __dl_clear(struct dl_bw *dl_b, u64 tsk_bw) { dl_b->total_bw -= tsk_bw; } static inline void __dl_add(struct dl_bw *dl_b, u64 tsk_bw) { dl_b->total_bw += tsk_bw; } static inline bool __dl_overflow(struct dl_bw *dl_b, int cpus, u64 old_bw, u64 new_bw) { return dl_b->bw != -1 && dl_b->bw * cpus < dl_b->total_bw - old_bw + new_bw; } /* * We must be sure that accepting a new task (or allowing changing the * parameters of an existing one) is consistent with the bandwidth * constraints. If yes, this function also accordingly updates the currently * allocated bandwidth to reflect the new situation. * * This function is called while holding p's rq->lock. */ static int dl_overflow(struct task_struct *p, int policy, const struct sched_attr *attr) { struct dl_bw *dl_b = dl_bw_of(task_cpu(p)); u64 period = attr->sched_period ?: attr->sched_deadline; u64 runtime = attr->sched_runtime; u64 new_bw = dl_policy(policy) ? to_ratio(period, runtime) : 0; int cpus, err = -1; if (new_bw == p->dl.dl_bw) return 0; /* * Either if a task, enters, leave, or stays -deadline but changes * its parameters, we may need to update accordingly the total * allocated bandwidth of the container. */ raw_spin_lock(&dl_b->lock); cpus = dl_bw_cpus(task_cpu(p)); if (dl_policy(policy) && !task_has_dl_policy(p) && !__dl_overflow(dl_b, cpus, 0, new_bw)) { __dl_add(dl_b, new_bw); err = 0; } else if (dl_policy(policy) && task_has_dl_policy(p) && !__dl_overflow(dl_b, cpus, p->dl.dl_bw, new_bw)) { __dl_clear(dl_b, p->dl.dl_bw); __dl_add(dl_b, new_bw); err = 0; } else if (!dl_policy(policy) && task_has_dl_policy(p)) { __dl_clear(dl_b, p->dl.dl_bw); err = 0; } raw_spin_unlock(&dl_b->lock); return err; } extern void init_dl_bw(struct dl_bw *dl_b); /* * wake_up_new_task - wake up a newly created task for the first time. * * This function will do some initial scheduler statistics housekeeping * that must be done for every newly created context, then puts the task * on the runqueue and wakes it. */ void wake_up_new_task(struct task_struct *p) { unsigned long flags; struct rq *rq; raw_spin_lock_irqsave(&p->pi_lock, flags); #ifdef CONFIG_SMP /* * Fork balancing, do it here and not earlier because: * - cpus_allowed can change in the fork path * - any previously selected cpu might disappear through hotplug */ set_task_cpu(p, select_task_rq(p, task_cpu(p), SD_BALANCE_FORK, 0)); #endif /* Initialize new task's runnable average */ init_task_runnable_average(p); rq = __task_rq_lock(p); activate_task(rq, p, 0); p->on_rq = 1; trace_sched_wakeup_new(p, true); check_preempt_curr(rq, p, WF_FORK); #ifdef CONFIG_SMP if (p->sched_class->task_woken) p->sched_class->task_woken(rq, p); #endif task_rq_unlock(rq, p, &flags); } #ifdef CONFIG_PREEMPT_NOTIFIERS /** * preempt_notifier_register - tell me when current is being preempted & rescheduled * @notifier: notifier struct to register */ void preempt_notifier_register(struct preempt_notifier *notifier) { hlist_add_head(&notifier->link, &current->preempt_notifiers); } EXPORT_SYMBOL_GPL(preempt_notifier_register); /** * preempt_notifier_unregister - no longer interested in preemption notifications * @notifier: notifier struct to unregister * * This is safe to call from within a preemption notifier. */ void preempt_notifier_unregister(struct preempt_notifier *notifier) { hlist_del(&notifier->link); } EXPORT_SYMBOL_GPL(preempt_notifier_unregister); static void fire_sched_in_preempt_notifiers(struct task_struct *curr) { struct preempt_notifier *notifier; hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) notifier->ops->sched_in(notifier, raw_smp_processor_id()); } static void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { struct preempt_notifier *notifier; hlist_for_each_entry(notifier, &curr->preempt_notifiers, link) notifier->ops->sched_out(notifier, next); } #else /* !CONFIG_PREEMPT_NOTIFIERS */ static void fire_sched_in_preempt_notifiers(struct task_struct *curr) { } static void fire_sched_out_preempt_notifiers(struct task_struct *curr, struct task_struct *next) { } #endif /* CONFIG_PREEMPT_NOTIFIERS */ /** * prepare_task_switch - prepare to switch tasks * @rq: the runqueue preparing to switch * @prev: the current task that is being switched out * @next: the task we are going to switch to. * * This is called with the rq lock held and interrupts off. It must * be paired with a subsequent finish_task_switch after the context * switch. * * prepare_task_switch sets up locking and calls architecture specific * hooks. */ static inline void prepare_task_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next) { trace_sched_switch(prev, next); sched_info_switch(rq, prev, next); perf_event_task_sched_out(prev, next); fire_sched_out_preempt_notifiers(prev, next); prepare_lock_switch(rq, next); prepare_arch_switch(next); } /** * finish_task_switch - clean up after a task-switch * @rq: runqueue associated with task-switch * @prev: the thread we just switched away from. * * finish_task_switch must be called after the context switch, paired * with a prepare_task_switch call before the context switch. * finish_task_switch will reconcile locking set up by prepare_task_switch, * and do any other architecture-specific cleanup actions. * * Note that we may have delayed dropping an mm in context_switch(). If * so, we finish that here outside of the runqueue lock. (Doing it * with the lock held can cause deadlocks; see schedule() for * details.) */ static void finish_task_switch(struct rq *rq, struct task_struct *prev) __releases(rq->lock) { struct mm_struct *mm = rq->prev_mm; long prev_state; rq->prev_mm = NULL; /* * A task struct has one reference for the use as "current". * If a task dies, then it sets TASK_DEAD in tsk->state and calls * schedule one last time. The schedule call will never return, and * the scheduled task must drop that reference. * The test for TASK_DEAD must occur while the runqueue locks are * still held, otherwise prev could be scheduled on another cpu, die * there before we look at prev->state, and then the reference would * be dropped twice. * Manfred Spraul <manfred@colorfullife.com> */ prev_state = prev->state; vtime_task_switch(prev); finish_arch_switch(prev); perf_event_task_sched_in(prev, current); finish_lock_switch(rq, prev); finish_arch_post_lock_switch(); fire_sched_in_preempt_notifiers(current); if (mm) mmdrop(mm); if (unlikely(prev_state == TASK_DEAD)) { task_numa_free(prev); if (prev->sched_class->task_dead) prev->sched_class->task_dead(prev); /* * Remove function-return probe instances associated with this * task and put them back on the free list. */ kprobe_flush_task(prev); put_task_struct(prev); } tick_nohz_task_switch(current); } #ifdef CONFIG_SMP /* assumes rq->lock is held */ static inline void pre_schedule(struct rq *rq, struct task_struct *prev) { if (prev->sched_class->pre_schedule) prev->sched_class->pre_schedule(rq, prev); } /* rq->lock is NOT held, but preemption is disabled */ static inline void post_schedule(struct rq *rq) { if (rq->post_schedule) { unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); if (rq->curr->sched_class->post_schedule) rq->curr->sched_class->post_schedule(rq); raw_spin_unlock_irqrestore(&rq->lock, flags); rq->post_schedule = 0; } } #else static inline void pre_schedule(struct rq *rq, struct task_struct *p) { } static inline void post_schedule(struct rq *rq) { } #endif /** * schedule_tail - first thing a freshly forked thread must call. * @prev: the thread we just switched away from. */ asmlinkage void schedule_tail(struct task_struct *prev) __releases(rq->lock) { struct rq *rq = this_rq(); finish_task_switch(rq, prev); /* * FIXME: do we need to worry about rq being invalidated by the * task_switch? */ post_schedule(rq); #ifdef __ARCH_WANT_UNLOCKED_CTXSW /* In this case, finish_task_switch does not reenable preemption */ preempt_enable(); #endif if (current->set_child_tid) put_user(task_pid_vnr(current), current->set_child_tid); } /* * context_switch - switch to the new MM and the new * thread's register state. */ static inline void context_switch(struct rq *rq, struct task_struct *prev, struct task_struct *next) { struct mm_struct *mm, *oldmm; prepare_task_switch(rq, prev, next); mm = next->mm; oldmm = prev->active_mm; /* * For paravirt, this is coupled with an exit in switch_to to * combine the page table reload and the switch backend into * one hypercall. */ arch_start_context_switch(prev); if (!mm) { next->active_mm = oldmm; atomic_inc(&oldmm->mm_count); enter_lazy_tlb(oldmm, next); } else switch_mm(oldmm, mm, next); if (!prev->mm) { prev->active_mm = NULL; rq->prev_mm = oldmm; } /* * Since the runqueue lock will be released by the next * task (which is an invalid locking op but in the case * of the scheduler it's an obvious special-case), so we * do an early lockdep release here: */ #ifndef __ARCH_WANT_UNLOCKED_CTXSW spin_release(&rq->lock.dep_map, 1, _THIS_IP_); #endif context_tracking_task_switch(prev, next); /* Here we just switch the register state and the stack. */ switch_to(prev, next, prev); barrier(); /* * this_rq must be evaluated again because prev may have moved * CPUs since it called schedule(), thus the 'rq' on its stack * frame will be invalid. */ finish_task_switch(this_rq(), prev); } /* * nr_running and nr_context_switches: * * externally visible scheduler statistics: current number of runnable * threads, total number of context switches performed since bootup. */ unsigned long nr_running(void) { unsigned long i, sum = 0; for_each_online_cpu(i) sum += cpu_rq(i)->nr_running; return sum; } unsigned long long nr_context_switches(void) { int i; unsigned long long sum = 0; for_each_possible_cpu(i) sum += cpu_rq(i)->nr_switches; return sum; } unsigned long nr_iowait(void) { unsigned long i, sum = 0; for_each_possible_cpu(i) sum += atomic_read(&cpu_rq(i)->nr_iowait); return sum; } unsigned long nr_iowait_cpu(int cpu) { struct rq *this = cpu_rq(cpu); return atomic_read(&this->nr_iowait); } #ifdef CONFIG_SMP /* * sched_exec - execve() is a valuable balancing opportunity, because at * this point the task has the smallest effective memory and cache footprint. */ void sched_exec(void) { struct task_struct *p = current; unsigned long flags; int dest_cpu; raw_spin_lock_irqsave(&p->pi_lock, flags); dest_cpu = p->sched_class->select_task_rq(p, task_cpu(p), SD_BALANCE_EXEC, 0); if (dest_cpu == smp_processor_id()) goto unlock; if (likely(cpu_active(dest_cpu))) { struct migration_arg arg = { p, dest_cpu }; raw_spin_unlock_irqrestore(&p->pi_lock, flags); stop_one_cpu(task_cpu(p), migration_cpu_stop, &arg); return; } unlock: raw_spin_unlock_irqrestore(&p->pi_lock, flags); } #endif DEFINE_PER_CPU(struct kernel_stat, kstat); DEFINE_PER_CPU(struct kernel_cpustat, kernel_cpustat); EXPORT_PER_CPU_SYMBOL(kstat); EXPORT_PER_CPU_SYMBOL(kernel_cpustat); /* * Return any ns on the sched_clock that have not yet been accounted in * @p in case that task is currently running. * * Called with task_rq_lock() held on @rq. */ static u64 do_task_delta_exec(struct task_struct *p, struct rq *rq) { u64 ns = 0; if (task_current(rq, p)) { update_rq_clock(rq); ns = rq_clock_task(rq) - p->se.exec_start; if ((s64)ns < 0) ns = 0; } return ns; } unsigned long long task_delta_exec(struct task_struct *p) { unsigned long flags; struct rq *rq; u64 ns = 0; rq = task_rq_lock(p, &flags); ns = do_task_delta_exec(p, rq); task_rq_unlock(rq, p, &flags); return ns; } /* * Return accounted runtime for the task. * In case the task is currently running, return the runtime plus current's * pending runtime that have not been accounted yet. */ unsigned long long task_sched_runtime(struct task_struct *p) { unsigned long flags; struct rq *rq; u64 ns = 0; #if defined(CONFIG_64BIT) && defined(CONFIG_SMP) /* * 64-bit doesn't need locks to atomically read a 64bit value. * So we have a optimization chance when the task's delta_exec is 0. * Reading ->on_cpu is racy, but this is ok. * * If we race with it leaving cpu, we'll take a lock. So we're correct. * If we race with it entering cpu, unaccounted time is 0. This is * indistinguishable from the read occurring a few cycles earlier. */ if (!p->on_cpu) return p->se.sum_exec_runtime; #endif rq = task_rq_lock(p, &flags); ns = p->se.sum_exec_runtime + do_task_delta_exec(p, rq); task_rq_unlock(rq, p, &flags); return ns; } /* * This function gets called by the timer code, with HZ frequency. * We call it with interrupts disabled. */ void scheduler_tick(void) { int cpu = smp_processor_id(); struct rq *rq = cpu_rq(cpu); struct task_struct *curr = rq->curr; sched_clock_tick(); raw_spin_lock(&rq->lock); update_rq_clock(rq); curr->sched_class->task_tick(rq, curr, 0); update_cpu_load_active(rq); raw_spin_unlock(&rq->lock); perf_event_task_tick(); #ifdef CONFIG_SMP rq->idle_balance = idle_cpu(cpu); trigger_load_balance(rq); #endif rq_last_tick_reset(rq); } #ifdef CONFIG_NO_HZ_FULL /** * scheduler_tick_max_deferment * * Keep at least one tick per second when a single * active task is running because the scheduler doesn't * yet completely support full dynticks environment. * * This makes sure that uptime, CFS vruntime, load * balancing, etc... continue to move forward, even * with a very low granularity. * * Return: Maximum deferment in nanoseconds. */ u64 scheduler_tick_max_deferment(void) { struct rq *rq = this_rq(); unsigned long next, now = ACCESS_ONCE(jiffies); next = rq->last_sched_tick + HZ; if (time_before_eq(next, now)) return 0; return jiffies_to_nsecs(next - now); } #endif notrace unsigned long get_parent_ip(unsigned long addr) { if (in_lock_functions(addr)) { addr = CALLER_ADDR2; if (in_lock_functions(addr)) addr = CALLER_ADDR3; } return addr; } #if defined(CONFIG_PREEMPT) && (defined(CONFIG_DEBUG_PREEMPT) || \ defined(CONFIG_PREEMPT_TRACER)) void __kprobes preempt_count_add(int val) { #ifdef CONFIG_DEBUG_PREEMPT /* * Underflow? */ if (DEBUG_LOCKS_WARN_ON((preempt_count() < 0))) return; #endif __preempt_count_add(val); #ifdef CONFIG_DEBUG_PREEMPT /* * Spinlock count overflowing soon? */ DEBUG_LOCKS_WARN_ON((preempt_count() & PREEMPT_MASK) >= PREEMPT_MASK - 10); #endif if (preempt_count() == val) trace_preempt_off(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1)); } EXPORT_SYMBOL(preempt_count_add); void __kprobes preempt_count_sub(int val) { #ifdef CONFIG_DEBUG_PREEMPT /* * Underflow? */ if (DEBUG_LOCKS_WARN_ON(val > preempt_count())) return; /* * Is the spinlock portion underflowing? */ if (DEBUG_LOCKS_WARN_ON((val < PREEMPT_MASK) && !(preempt_count() & PREEMPT_MASK))) return; #endif if (preempt_count() == val) trace_preempt_on(CALLER_ADDR0, get_parent_ip(CALLER_ADDR1)); __preempt_count_sub(val); } EXPORT_SYMBOL(preempt_count_sub); #endif /* * Print scheduling while atomic bug: */ static noinline void __schedule_bug(struct task_struct *prev) { if (oops_in_progress) return; printk(KERN_ERR "BUG: scheduling while atomic: %s/%d/0x%08x\n", prev->comm, prev->pid, preempt_count()); debug_show_held_locks(prev); print_modules(); if (irqs_disabled()) print_irqtrace_events(prev); dump_stack(); add_taint(TAINT_WARN, LOCKDEP_STILL_OK); } /* * Various schedule()-time debugging checks and statistics: */ static inline void schedule_debug(struct task_struct *prev) { /* * Test if we are atomic. Since do_exit() needs to call into * schedule() atomically, we ignore that path. Otherwise whine * if we are scheduling when we should not. */ if (unlikely(in_atomic_preempt_off() && prev->state != TASK_DEAD)) __schedule_bug(prev); rcu_sleep_check(); profile_hit(SCHED_PROFILING, __builtin_return_address(0)); schedstat_inc(this_rq(), sched_count); } static void put_prev_task(struct rq *rq, struct task_struct *prev) { if (prev->on_rq || rq->skip_clock_update < 0) update_rq_clock(rq); prev->sched_class->put_prev_task(rq, prev); } /* * Pick up the highest-prio task: */ static inline struct task_struct * pick_next_task(struct rq *rq) { const struct sched_class *class; struct task_struct *p; /* * Optimization: we know that if all tasks are in * the fair class we can call that function directly: */ if (likely(rq->nr_running == rq->cfs.h_nr_running)) { p = fair_sched_class.pick_next_task(rq); if (likely(p)) return p; } for_each_class(class) { p = class->pick_next_task(rq); if (p) return p; } BUG(); /* the idle class will always have a runnable task */ } /* * __schedule() is the main scheduler function. * * The main means of driving the scheduler and thus entering this function are: * * 1. Explicit blocking: mutex, semaphore, waitqueue, etc. * * 2. TIF_NEED_RESCHED flag is checked on interrupt and userspace return * paths. For example, see arch/x86/entry_64.S. * * To drive preemption between tasks, the scheduler sets the flag in timer * interrupt handler scheduler_tick(). * * 3. Wakeups don't really cause entry into schedule(). They add a * task to the run-queue and that's it. * * Now, if the new task added to the run-queue preempts the current * task, then the wakeup sets TIF_NEED_RESCHED and schedule() gets * called on the nearest possible occasion: * * - If the kernel is preemptible (CONFIG_PREEMPT=y): * * - in syscall or exception context, at the next outmost * preempt_enable(). (this might be as soon as the wake_up()'s * spin_unlock()!) * * - in IRQ context, return from interrupt-handler to * preemptible context * * - If the kernel is not preemptible (CONFIG_PREEMPT is not set) * then at the next: * * - cond_resched() call * - explicit schedule() call * - return from syscall or exception to user-space * - return from interrupt-handler to user-space */ static void __sched __schedule(void) { struct task_struct *prev, *next; unsigned long *switch_count; struct rq *rq; int cpu; need_resched: preempt_disable(); cpu = smp_processor_id(); rq = cpu_rq(cpu); rcu_note_context_switch(cpu); prev = rq->curr; schedule_debug(prev); if (sched_feat(HRTICK)) hrtick_clear(rq); /* * Make sure that signal_pending_state()->signal_pending() below * can't be reordered with __set_current_state(TASK_INTERRUPTIBLE) * done by the caller to avoid the race with signal_wake_up(). */ smp_mb__before_spinlock(); raw_spin_lock_irq(&rq->lock); switch_count = &prev->nivcsw; if (prev->state && !(preempt_count() & PREEMPT_ACTIVE)) { if (unlikely(signal_pending_state(prev->state, prev))) { prev->state = TASK_RUNNING; } else { deactivate_task(rq, prev, DEQUEUE_SLEEP); prev->on_rq = 0; /* * If a worker went to sleep, notify and ask workqueue * whether it wants to wake up a task to maintain * concurrency. */ if (prev->flags & PF_WQ_WORKER) { struct task_struct *to_wakeup; to_wakeup = wq_worker_sleeping(prev, cpu); if (to_wakeup) try_to_wake_up_local(to_wakeup); } } switch_count = &prev->nvcsw; } pre_schedule(rq, prev); if (unlikely(!rq->nr_running)) idle_balance(cpu, rq); put_prev_task(rq, prev); next = pick_next_task(rq); clear_tsk_need_resched(prev); clear_preempt_need_resched(); rq->skip_clock_update = 0; if (likely(prev != next)) { rq->nr_switches++; rq->curr = next; ++*switch_count; context_switch(rq, prev, next); /* unlocks the rq */ /* * The context switch have flipped the stack from under us * and restored the local variables which were saved when * this task called schedule() in the past. prev == current * is still correct, but it can be moved to another cpu/rq. */ cpu = smp_processor_id(); rq = cpu_rq(cpu); } else raw_spin_unlock_irq(&rq->lock); post_schedule(rq); sched_preempt_enable_no_resched(); if (need_resched()) goto need_resched; } static inline void sched_submit_work(struct task_struct *tsk) { if (!tsk->state || tsk_is_pi_blocked(tsk)) return; /* * If we are going to sleep and we have plugged IO queued, * make sure to submit it to avoid deadlocks. */ if (blk_needs_flush_plug(tsk)) blk_schedule_flush_plug(tsk); } asmlinkage void __sched schedule(void) { struct task_struct *tsk = current; sched_submit_work(tsk); __schedule(); } EXPORT_SYMBOL(schedule); #ifdef CONFIG_CONTEXT_TRACKING asmlinkage void __sched schedule_user(void) { /* * If we come here after a random call to set_need_resched(), * or we have been woken up remotely but the IPI has not yet arrived, * we haven't yet exited the RCU idle mode. Do it here manually until * we find a better solution. */ user_exit(); schedule(); user_enter(); } #endif /** * schedule_preempt_disabled - called with preemption disabled * * Returns with preemption disabled. Note: preempt_count must be 1 */ void __sched schedule_preempt_disabled(void) { sched_preempt_enable_no_resched(); schedule(); preempt_disable(); } #ifdef CONFIG_PREEMPT /* * this is the entry point to schedule() from in-kernel preemption * off of preempt_enable. Kernel preemptions off return from interrupt * occur there and call schedule directly. */ asmlinkage void __sched notrace preempt_schedule(void) { /* * If there is a non-zero preempt_count or interrupts are disabled, * we do not want to preempt the current task. Just return.. */ if (likely(!preemptible())) return; do { __preempt_count_add(PREEMPT_ACTIVE); __schedule(); __preempt_count_sub(PREEMPT_ACTIVE); /* * Check again in case we missed a preemption opportunity * between schedule and now. */ barrier(); } while (need_resched()); } EXPORT_SYMBOL(preempt_schedule); #endif /* CONFIG_PREEMPT */ /* * this is the entry point to schedule() from kernel preemption * off of irq context. * Note, that this is called and return with irqs disabled. This will * protect us against recursive calling from irq. */ asmlinkage void __sched preempt_schedule_irq(void) { enum ctx_state prev_state; /* Catch callers which need to be fixed */ BUG_ON(preempt_count() || !irqs_disabled()); prev_state = exception_enter(); do { __preempt_count_add(PREEMPT_ACTIVE); local_irq_enable(); __schedule(); local_irq_disable(); __preempt_count_sub(PREEMPT_ACTIVE); /* * Check again in case we missed a preemption opportunity * between schedule and now. */ barrier(); } while (need_resched()); exception_exit(prev_state); } int default_wake_function(wait_queue_t *curr, unsigned mode, int wake_flags, void *key) { return try_to_wake_up(curr->private, mode, wake_flags); } EXPORT_SYMBOL(default_wake_function); static long __sched sleep_on_common(wait_queue_head_t *q, int state, long timeout) { unsigned long flags; wait_queue_t wait; init_waitqueue_entry(&wait, current); __set_current_state(state); spin_lock_irqsave(&q->lock, flags); __add_wait_queue(q, &wait); spin_unlock(&q->lock); timeout = schedule_timeout(timeout); spin_lock_irq(&q->lock); __remove_wait_queue(q, &wait); spin_unlock_irqrestore(&q->lock, flags); return timeout; } void __sched interruptible_sleep_on(wait_queue_head_t *q) { sleep_on_common(q, TASK_INTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT); } EXPORT_SYMBOL(interruptible_sleep_on); long __sched interruptible_sleep_on_timeout(wait_queue_head_t *q, long timeout) { return sleep_on_common(q, TASK_INTERRUPTIBLE, timeout); } EXPORT_SYMBOL(interruptible_sleep_on_timeout); void __sched sleep_on(wait_queue_head_t *q) { sleep_on_common(q, TASK_UNINTERRUPTIBLE, MAX_SCHEDULE_TIMEOUT); } EXPORT_SYMBOL(sleep_on); long __sched sleep_on_timeout(wait_queue_head_t *q, long timeout) { return sleep_on_common(q, TASK_UNINTERRUPTIBLE, timeout); } EXPORT_SYMBOL(sleep_on_timeout); #ifdef CONFIG_RT_MUTEXES /* * rt_mutex_setprio - set the current priority of a task * @p: task * @prio: prio value (kernel-internal form) * * This function changes the 'effective' priority of a task. It does * not touch ->normal_prio like __setscheduler(). * * Used by the rt_mutex code to implement priority inheritance logic. */ void rt_mutex_setprio(struct task_struct *p, int prio) { int oldprio, on_rq, running, enqueue_flag = 0; struct rq *rq; const struct sched_class *prev_class; BUG_ON(prio > MAX_PRIO); rq = __task_rq_lock(p); /* * Idle task boosting is a nono in general. There is one * exception, when PREEMPT_RT and NOHZ is active: * * The idle task calls get_next_timer_interrupt() and holds * the timer wheel base->lock on the CPU and another CPU wants * to access the timer (probably to cancel it). We can safely * ignore the boosting request, as the idle CPU runs this code * with interrupts disabled and will complete the lock * protected section without being interrupted. So there is no * real need to boost. */ if (unlikely(p == rq->idle)) { WARN_ON(p != rq->curr); WARN_ON(p->pi_blocked_on); goto out_unlock; } trace_sched_pi_setprio(p, prio); p->pi_top_task = rt_mutex_get_top_task(p); oldprio = p->prio; prev_class = p->sched_class; on_rq = p->on_rq; running = task_current(rq, p); if (on_rq) dequeue_task(rq, p, 0); if (running) p->sched_class->put_prev_task(rq, p); /* * Boosting condition are: * 1. -rt task is running and holds mutex A * --> -dl task blocks on mutex A * * 2. -dl task is running and holds mutex A * --> -dl task blocks on mutex A and could preempt the * running task */ if (dl_prio(prio)) { if (!dl_prio(p->normal_prio) || (p->pi_top_task && dl_entity_preempt(&p->pi_top_task->dl, &p->dl))) { p->dl.dl_boosted = 1; p->dl.dl_throttled = 0; enqueue_flag = ENQUEUE_REPLENISH; } else p->dl.dl_boosted = 0; p->sched_class = &dl_sched_class; } else if (rt_prio(prio)) { if (dl_prio(oldprio)) p->dl.dl_boosted = 0; if (oldprio < prio) enqueue_flag = ENQUEUE_HEAD; p->sched_class = &rt_sched_class; } else { if (dl_prio(oldprio)) p->dl.dl_boosted = 0; p->sched_class = &fair_sched_class; } p->prio = prio; if (running) p->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, p, enqueue_flag); check_class_changed(rq, p, prev_class, oldprio); out_unlock: __task_rq_unlock(rq); } #endif 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); } EXPORT_SYMBOL(set_user_nice); /* * can_nice - check if a task can reduce its nice value * @p: task * @nice: nice value */ int can_nice(const struct task_struct *p, const int nice) { /* convert nice value [19,-20] to rlimit style value [1,40] */ int nice_rlim = 20 - nice; return (nice_rlim <= task_rlimit(p, RLIMIT_NICE) || capable(CAP_SYS_NICE)); } #ifdef __ARCH_WANT_SYS_NICE /* * sys_nice - change the priority of the current process. * @increment: priority increment * * sys_setpriority is a more generic, but much slower function that * does similar things. */ SYSCALL_DEFINE1(nice, int, increment) { long nice, retval; /* * Setpriority might change our priority at the same moment. * We don't have to worry. Conceptually one call occurs first * and we have a single winner. */ if (increment < -40) increment = -40; if (increment > 40) increment = 40; nice = TASK_NICE(current) + increment; if (nice < -20) nice = -20; if (nice > 19) nice = 19; if (increment < 0 && !can_nice(current, nice)) return -EPERM; retval = security_task_setnice(current, nice); if (retval) return retval; set_user_nice(current, nice); return 0; } #endif /** * task_prio - return the priority value of a given task. * @p: the task in question. * * Return: The priority value as seen by users in /proc. * RT tasks are offset by -200. Normal tasks are centered * around 0, value goes from -16 to +15. */ int task_prio(const struct task_struct *p) { return p->prio - MAX_RT_PRIO; } /** * task_nice - return the nice value of a given task. * @p: the task in question. * * Return: The nice value [ -20 ... 0 ... 19 ]. */ int task_nice(const struct task_struct *p) { return TASK_NICE(p); } EXPORT_SYMBOL(task_nice); /** * idle_cpu - is a given cpu idle currently? * @cpu: the processor in question. * * Return: 1 if the CPU is currently idle. 0 otherwise. */ int idle_cpu(int cpu) { struct rq *rq = cpu_rq(cpu); if (rq->curr != rq->idle) return 0; if (rq->nr_running) return 0; #ifdef CONFIG_SMP if (!llist_empty(&rq->wake_list)) return 0; #endif return 1; } /** * idle_task - return the idle task for a given cpu. * @cpu: the processor in question. * * Return: The idle task for the cpu @cpu. */ struct task_struct *idle_task(int cpu) { return cpu_rq(cpu)->idle; } /** * find_process_by_pid - find a process with a matching PID value. * @pid: the pid in question. * * The task of @pid, if found. %NULL otherwise. */ static struct task_struct *find_process_by_pid(pid_t pid) { return pid ? find_task_by_vpid(pid) : current; } /* * This function initializes the sched_dl_entity of a newly becoming * SCHED_DEADLINE task. * * Only the static values are considered here, the actual runtime and the * absolute deadline will be properly calculated when the task is enqueued * for the first time with its new policy. */ static void __setparam_dl(struct task_struct *p, const struct sched_attr *attr) { struct sched_dl_entity *dl_se = &p->dl; init_dl_task_timer(dl_se); dl_se->dl_runtime = attr->sched_runtime; dl_se->dl_deadline = attr->sched_deadline; dl_se->dl_period = attr->sched_period ?: dl_se->dl_deadline; dl_se->flags = attr->sched_flags; dl_se->dl_bw = to_ratio(dl_se->dl_period, dl_se->dl_runtime); dl_se->dl_throttled = 0; dl_se->dl_new = 1; } /* Actually do priority change: must hold pi & rq lock. */ static void __setscheduler(struct rq *rq, struct task_struct *p, const struct sched_attr *attr) { int policy = attr->sched_policy; if (policy == -1) /* setparam */ policy = p->policy; p->policy = policy; if (dl_policy(policy)) __setparam_dl(p, attr); else if (fair_policy(policy)) p->static_prio = NICE_TO_PRIO(attr->sched_nice); /* * __sched_setscheduler() ensures attr->sched_priority == 0 when * !rt_policy. Always setting this ensures that things like * getparam()/getattr() don't report silly values for !rt tasks. */ p->rt_priority = attr->sched_priority; p->normal_prio = normal_prio(p); p->prio = rt_mutex_getprio(p); if (dl_prio(p->prio)) p->sched_class = &dl_sched_class; else if (rt_prio(p->prio)) p->sched_class = &rt_sched_class; else p->sched_class = &fair_sched_class; set_load_weight(p); } static void __getparam_dl(struct task_struct *p, struct sched_attr *attr) { struct sched_dl_entity *dl_se = &p->dl; attr->sched_priority = p->rt_priority; attr->sched_runtime = dl_se->dl_runtime; attr->sched_deadline = dl_se->dl_deadline; attr->sched_period = dl_se->dl_period; attr->sched_flags = dl_se->flags; } /* * This function validates the new parameters of a -deadline task. * We ask for the deadline not being zero, and greater or equal * than the runtime, as well as the period of being zero or * greater than deadline. Furthermore, we have to be sure that * user parameters are above the internal resolution (1us); we * check sched_runtime only since it is always the smaller one. */ static bool __checkparam_dl(const struct sched_attr *attr) { return attr && attr->sched_deadline != 0 && (attr->sched_period == 0 || (s64)(attr->sched_period - attr->sched_deadline) >= 0) && (s64)(attr->sched_deadline - attr->sched_runtime ) >= 0 && attr->sched_runtime >= (2 << (DL_SCALE - 1)); } /* * check the target process has a UID that matches the current process's */ static bool check_same_owner(struct task_struct *p) { const struct cred *cred = current_cred(), *pcred; bool match; rcu_read_lock(); pcred = __task_cred(p); match = (uid_eq(cred->euid, pcred->euid) || uid_eq(cred->euid, pcred->uid)); rcu_read_unlock(); return match; } static int __sched_setscheduler(struct task_struct *p, const struct sched_attr *attr, bool user) { int retval, oldprio, oldpolicy = -1, on_rq, running; int policy = attr->sched_policy; unsigned long flags; const struct sched_class *prev_class; struct rq *rq; int reset_on_fork; /* may grab non-irq protected spin_locks */ BUG_ON(in_interrupt()); recheck: /* double check policy once rq lock held */ if (policy < 0) { reset_on_fork = p->sched_reset_on_fork; policy = oldpolicy = p->policy; } else { reset_on_fork = !!(attr->sched_flags & SCHED_FLAG_RESET_ON_FORK); if (policy != SCHED_DEADLINE && policy != SCHED_FIFO && policy != SCHED_RR && policy != SCHED_NORMAL && policy != SCHED_BATCH && policy != SCHED_IDLE) return -EINVAL; } if (attr->sched_flags & ~(SCHED_FLAG_RESET_ON_FORK)) return -EINVAL; /* * Valid priorities for SCHED_FIFO and SCHED_RR are * 1..MAX_USER_RT_PRIO-1, valid priority for SCHED_NORMAL, * SCHED_BATCH and SCHED_IDLE is 0. */ if ((p->mm && attr->sched_priority > MAX_USER_RT_PRIO-1) || (!p->mm && attr->sched_priority > MAX_RT_PRIO-1)) return -EINVAL; if ((dl_policy(policy) && !__checkparam_dl(attr)) || (rt_policy(policy) != (attr->sched_priority != 0))) return -EINVAL; /* * Allow unprivileged RT tasks to decrease priority: */ if (user && !capable(CAP_SYS_NICE)) { if (fair_policy(policy)) { if (attr->sched_nice < TASK_NICE(p) && !can_nice(p, attr->sched_nice)) return -EPERM; } if (rt_policy(policy)) { unsigned long rlim_rtprio = task_rlimit(p, RLIMIT_RTPRIO); /* can't set/change the rt policy */ if (policy != p->policy && !rlim_rtprio) return -EPERM; /* can't increase priority */ if (attr->sched_priority > p->rt_priority && attr->sched_priority > rlim_rtprio) return -EPERM; } /* * Treat SCHED_IDLE as nice 20. Only allow a switch to * SCHED_NORMAL if the RLIMIT_NICE would normally permit it. */ if (p->policy == SCHED_IDLE && policy != SCHED_IDLE) { if (!can_nice(p, TASK_NICE(p))) return -EPERM; } /* can't change other user's priorities */ if (!check_same_owner(p)) return -EPERM; /* Normal users shall not reset the sched_reset_on_fork flag */ if (p->sched_reset_on_fork && !reset_on_fork) return -EPERM; } if (user) { retval = security_task_setscheduler(p); if (retval) return retval; } /* * make sure no PI-waiters arrive (or leave) while we are * changing the priority of the task: * * To be able to change p->policy safely, the appropriate * runqueue lock must be held. */ rq = task_rq_lock(p, &flags); /* * Changing the policy of the stop threads its a very bad idea */ if (p == rq->stop) { task_rq_unlock(rq, p, &flags); return -EINVAL; } /* * If not changing anything there's no need to proceed further: */ if (unlikely(policy == p->policy)) { if (fair_policy(policy) && attr->sched_nice != TASK_NICE(p)) goto change; if (rt_policy(policy) && attr->sched_priority != p->rt_priority) goto change; if (dl_policy(policy)) goto change; task_rq_unlock(rq, p, &flags); return 0; } change: if (user) { #ifdef CONFIG_RT_GROUP_SCHED /* * Do not allow realtime tasks into groups that have no runtime * assigned. */ if (rt_bandwidth_enabled() && rt_policy(policy) && task_group(p)->rt_bandwidth.rt_runtime == 0 && !task_group_is_autogroup(task_group(p))) { task_rq_unlock(rq, p, &flags); return -EPERM; } #endif #ifdef CONFIG_SMP if (dl_bandwidth_enabled() && dl_policy(policy)) { cpumask_t *span = rq->rd->span; /* * Don't allow tasks with an affinity mask smaller than * the entire root_domain to become SCHED_DEADLINE. We * will also fail if there's no bandwidth available. */ if (!cpumask_subset(span, &p->cpus_allowed) || rq->rd->dl_bw.bw == 0) { task_rq_unlock(rq, p, &flags); return -EPERM; } } #endif } /* recheck policy now with rq lock held */ if (unlikely(oldpolicy != -1 && oldpolicy != p->policy)) { policy = oldpolicy = -1; task_rq_unlock(rq, p, &flags); goto recheck; } /* * If setscheduling to SCHED_DEADLINE (or changing the parameters * of a SCHED_DEADLINE task) we need to check if enough bandwidth * is available. */ if ((dl_policy(policy) || dl_task(p)) && dl_overflow(p, policy, attr)) { task_rq_unlock(rq, p, &flags); return -EBUSY; } on_rq = p->on_rq; running = task_current(rq, p); if (on_rq) dequeue_task(rq, p, 0); if (running) p->sched_class->put_prev_task(rq, p); p->sched_reset_on_fork = reset_on_fork; oldprio = p->prio; prev_class = p->sched_class; __setscheduler(rq, p, attr); if (running) p->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, p, 0); check_class_changed(rq, p, prev_class, oldprio); task_rq_unlock(rq, p, &flags); rt_mutex_adjust_pi(p); return 0; } static int _sched_setscheduler(struct task_struct *p, int policy, const struct sched_param *param, bool check) { struct sched_attr attr = { .sched_policy = policy, .sched_priority = param->sched_priority, .sched_nice = PRIO_TO_NICE(p->static_prio), }; /* * Fixup the legacy SCHED_RESET_ON_FORK hack */ if (policy & SCHED_RESET_ON_FORK) { attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK; policy &= ~SCHED_RESET_ON_FORK; attr.sched_policy = policy; } return __sched_setscheduler(p, &attr, check); } /** * sched_setscheduler - change the scheduling policy and/or RT priority of a thread. * @p: the task in question. * @policy: new policy. * @param: structure containing the new RT priority. * * Return: 0 on success. An error code otherwise. * * NOTE that the task may be already dead. */ int sched_setscheduler(struct task_struct *p, int policy, const struct sched_param *param) { return _sched_setscheduler(p, policy, param, true); } EXPORT_SYMBOL_GPL(sched_setscheduler); int sched_setattr(struct task_struct *p, const struct sched_attr *attr) { return __sched_setscheduler(p, attr, true); } EXPORT_SYMBOL_GPL(sched_setattr); /** * sched_setscheduler_nocheck - change the scheduling policy and/or RT priority of a thread from kernelspace. * @p: the task in question. * @policy: new policy. * @param: structure containing the new RT priority. * * Just like sched_setscheduler, only don't bother checking if the * current context has permission. For example, this is needed in * stop_machine(): we create temporary high priority worker threads, * but our caller might not have that capability. * * Return: 0 on success. An error code otherwise. */ int sched_setscheduler_nocheck(struct task_struct *p, int policy, const struct sched_param *param) { return _sched_setscheduler(p, policy, param, false); } static int do_sched_setscheduler(pid_t pid, int policy, struct sched_param __user *param) { struct sched_param lparam; struct task_struct *p; int retval; if (!param || pid < 0) return -EINVAL; if (copy_from_user(&lparam, param, sizeof(struct sched_param))) return -EFAULT; rcu_read_lock(); retval = -ESRCH; p = find_process_by_pid(pid); if (p != NULL) retval = sched_setscheduler(p, policy, &lparam); rcu_read_unlock(); return retval; } /* * Mimics kernel/events/core.c perf_copy_attr(). */ static int sched_copy_attr(struct sched_attr __user *uattr, struct sched_attr *attr) { u32 size; int ret; if (!access_ok(VERIFY_WRITE, uattr, SCHED_ATTR_SIZE_VER0)) return -EFAULT; /* * zero the full structure, so that a short copy will be nice. */ memset(attr, 0, sizeof(*attr)); ret = get_user(size, &uattr->size); if (ret) return ret; if (size > PAGE_SIZE) /* silly large */ goto err_size; if (!size) /* abi compat */ size = SCHED_ATTR_SIZE_VER0; if (size < SCHED_ATTR_SIZE_VER0) goto err_size; /* * If we're handed a bigger struct than we know of, * ensure all the unknown bits are 0 - i.e. new * user-space does not rely on any kernel feature * extensions we dont know about yet. */ if (size > sizeof(*attr)) { unsigned char __user *addr; unsigned char __user *end; unsigned char val; addr = (void __user *)uattr + sizeof(*attr); end = (void __user *)uattr + size; for (; addr < end; addr++) { ret = get_user(val, addr); if (ret) return ret; if (val) goto err_size; } size = sizeof(*attr); } ret = copy_from_user(attr, uattr, size); if (ret) return -EFAULT; /* * XXX: do we want to be lenient like existing syscalls; or do we want * to be strict and return an error on out-of-bounds values? */ attr->sched_nice = clamp(attr->sched_nice, -20, 19); out: return ret; err_size: put_user(sizeof(*attr), &uattr->size); ret = -E2BIG; goto out; } /** * sys_sched_setscheduler - set/change the scheduler policy and RT priority * @pid: the pid in question. * @policy: new policy. * @param: structure containing the new RT priority. * * Return: 0 on success. An error code otherwise. */ SYSCALL_DEFINE3(sched_setscheduler, pid_t, pid, int, policy, struct sched_param __user *, param) { /* negative values for policy are not valid */ if (policy < 0) return -EINVAL; return do_sched_setscheduler(pid, policy, param); } /** * sys_sched_setparam - set/change the RT priority of a thread * @pid: the pid in question. * @param: structure containing the new RT priority. * * Return: 0 on success. An error code otherwise. */ SYSCALL_DEFINE2(sched_setparam, pid_t, pid, struct sched_param __user *, param) { return do_sched_setscheduler(pid, -1, param); } /** * sys_sched_setattr - same as above, but with extended sched_attr * @pid: the pid in question. * @uattr: structure containing the extended parameters. */ SYSCALL_DEFINE2(sched_setattr, pid_t, pid, struct sched_attr __user *, uattr) { struct sched_attr attr; struct task_struct *p; int retval; if (!uattr || pid < 0) return -EINVAL; if (sched_copy_attr(uattr, &attr)) return -EFAULT; rcu_read_lock(); retval = -ESRCH; p = find_process_by_pid(pid); if (p != NULL) retval = sched_setattr(p, &attr); rcu_read_unlock(); return retval; } /** * sys_sched_getscheduler - get the policy (scheduling class) of a thread * @pid: the pid in question. * * Return: On success, the policy of the thread. Otherwise, a negative error * code. */ SYSCALL_DEFINE1(sched_getscheduler, pid_t, pid) { struct task_struct *p; int retval; if (pid < 0) return -EINVAL; retval = -ESRCH; rcu_read_lock(); p = find_process_by_pid(pid); if (p) { retval = security_task_getscheduler(p); if (!retval) retval = p->policy | (p->sched_reset_on_fork ? SCHED_RESET_ON_FORK : 0); } rcu_read_unlock(); return retval; } /** * sys_sched_getparam - get the RT priority of a thread * @pid: the pid in question. * @param: structure containing the RT priority. * * Return: On success, 0 and the RT priority is in @param. Otherwise, an error * code. */ SYSCALL_DEFINE2(sched_getparam, pid_t, pid, struct sched_param __user *, param) { struct sched_param lp; struct task_struct *p; int retval; if (!param || pid < 0) return -EINVAL; rcu_read_lock(); p = find_process_by_pid(pid); retval = -ESRCH; if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; if (task_has_dl_policy(p)) { retval = -EINVAL; goto out_unlock; } lp.sched_priority = p->rt_priority; rcu_read_unlock(); /* * This one might sleep, we cannot do it with a spinlock held ... */ retval = copy_to_user(param, &lp, sizeof(*param)) ? -EFAULT : 0; return retval; out_unlock: rcu_read_unlock(); return retval; } static int sched_read_attr(struct sched_attr __user *uattr, struct sched_attr *attr, unsigned int usize) { int ret; if (!access_ok(VERIFY_WRITE, uattr, usize)) return -EFAULT; /* * If we're handed a smaller struct than we know of, * ensure all the unknown bits are 0 - i.e. old * user-space does not get uncomplete information. */ if (usize < sizeof(*attr)) { unsigned char *addr; unsigned char *end; addr = (void *)attr + usize; end = (void *)attr + sizeof(*attr); for (; addr < end; addr++) { if (*addr) goto err_size; } attr->size = usize; } ret = copy_to_user(uattr, attr, attr->size); if (ret) return -EFAULT; out: return ret; err_size: ret = -E2BIG; goto out; } /** * sys_sched_getattr - similar to sched_getparam, but with sched_attr * @pid: the pid in question. * @uattr: structure containing the extended parameters. * @size: sizeof(attr) for fwd/bwd comp. */ SYSCALL_DEFINE3(sched_getattr, pid_t, pid, struct sched_attr __user *, uattr, unsigned int, size) { struct sched_attr attr = { .size = sizeof(struct sched_attr), }; struct task_struct *p; int retval; if (!uattr || pid < 0 || size > PAGE_SIZE || size < SCHED_ATTR_SIZE_VER0) return -EINVAL; rcu_read_lock(); p = find_process_by_pid(pid); retval = -ESRCH; if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; attr.sched_policy = p->policy; if (p->sched_reset_on_fork) attr.sched_flags |= SCHED_FLAG_RESET_ON_FORK; if (task_has_dl_policy(p)) __getparam_dl(p, &attr); else if (task_has_rt_policy(p)) attr.sched_priority = p->rt_priority; else attr.sched_nice = TASK_NICE(p); rcu_read_unlock(); retval = sched_read_attr(uattr, &attr, size); return retval; out_unlock: rcu_read_unlock(); return retval; } long sched_setaffinity(pid_t pid, const struct cpumask *in_mask) { cpumask_var_t cpus_allowed, new_mask; struct task_struct *p; int retval; rcu_read_lock(); p = find_process_by_pid(pid); if (!p) { rcu_read_unlock(); return -ESRCH; } /* Prevent p going away */ get_task_struct(p); rcu_read_unlock(); if (p->flags & PF_NO_SETAFFINITY) { retval = -EINVAL; goto out_put_task; } if (!alloc_cpumask_var(&cpus_allowed, GFP_KERNEL)) { retval = -ENOMEM; goto out_put_task; } if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) { retval = -ENOMEM; goto out_free_cpus_allowed; } retval = -EPERM; if (!check_same_owner(p)) { rcu_read_lock(); if (!ns_capable(__task_cred(p)->user_ns, CAP_SYS_NICE)) { rcu_read_unlock(); goto out_unlock; } rcu_read_unlock(); } retval = security_task_setscheduler(p); if (retval) goto out_unlock; cpuset_cpus_allowed(p, cpus_allowed); cpumask_and(new_mask, in_mask, cpus_allowed); /* * Since bandwidth control happens on root_domain basis, * if admission test is enabled, we only admit -deadline * tasks allowed to run on all the CPUs in the task's * root_domain. */ #ifdef CONFIG_SMP if (task_has_dl_policy(p)) { const struct cpumask *span = task_rq(p)->rd->span; if (dl_bandwidth_enabled() && !cpumask_subset(span, new_mask)) { retval = -EBUSY; goto out_unlock; } } #endif again: retval = set_cpus_allowed_ptr(p, new_mask); if (!retval) { cpuset_cpus_allowed(p, cpus_allowed); if (!cpumask_subset(new_mask, cpus_allowed)) { /* * We must have raced with a concurrent cpuset * update. Just reset the cpus_allowed to the * cpuset's cpus_allowed */ cpumask_copy(new_mask, cpus_allowed); goto again; } } out_unlock: free_cpumask_var(new_mask); out_free_cpus_allowed: free_cpumask_var(cpus_allowed); out_put_task: put_task_struct(p); return retval; } static int get_user_cpu_mask(unsigned long __user *user_mask_ptr, unsigned len, struct cpumask *new_mask) { if (len < cpumask_size()) cpumask_clear(new_mask); else if (len > cpumask_size()) len = cpumask_size(); return copy_from_user(new_mask, user_mask_ptr, len) ? -EFAULT : 0; } /** * sys_sched_setaffinity - set the cpu affinity of a process * @pid: pid of the process * @len: length in bytes of the bitmask pointed to by user_mask_ptr * @user_mask_ptr: user-space pointer to the new cpu mask * * Return: 0 on success. An error code otherwise. */ SYSCALL_DEFINE3(sched_setaffinity, pid_t, pid, unsigned int, len, unsigned long __user *, user_mask_ptr) { cpumask_var_t new_mask; int retval; if (!alloc_cpumask_var(&new_mask, GFP_KERNEL)) return -ENOMEM; retval = get_user_cpu_mask(user_mask_ptr, len, new_mask); if (retval == 0) retval = sched_setaffinity(pid, new_mask); free_cpumask_var(new_mask); return retval; } long sched_getaffinity(pid_t pid, struct cpumask *mask) { struct task_struct *p; unsigned long flags; int retval; rcu_read_lock(); retval = -ESRCH; p = find_process_by_pid(pid); if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; raw_spin_lock_irqsave(&p->pi_lock, flags); cpumask_and(mask, &p->cpus_allowed, cpu_active_mask); raw_spin_unlock_irqrestore(&p->pi_lock, flags); out_unlock: rcu_read_unlock(); return retval; } /** * sys_sched_getaffinity - get the cpu affinity of a process * @pid: pid of the process * @len: length in bytes of the bitmask pointed to by user_mask_ptr * @user_mask_ptr: user-space pointer to hold the current cpu mask * * Return: 0 on success. An error code otherwise. */ SYSCALL_DEFINE3(sched_getaffinity, pid_t, pid, unsigned int, len, unsigned long __user *, user_mask_ptr) { int ret; cpumask_var_t mask; if ((len * BITS_PER_BYTE) < nr_cpu_ids) return -EINVAL; if (len & (sizeof(unsigned long)-1)) return -EINVAL; if (!alloc_cpumask_var(&mask, GFP_KERNEL)) return -ENOMEM; ret = sched_getaffinity(pid, mask); if (ret == 0) { size_t retlen = min_t(size_t, len, cpumask_size()); if (copy_to_user(user_mask_ptr, mask, retlen)) ret = -EFAULT; else ret = retlen; } free_cpumask_var(mask); return ret; } /** * sys_sched_yield - yield the current processor to other threads. * * This function yields the current CPU to other tasks. If there are no * other threads running on this CPU then this function will return. * * Return: 0. */ SYSCALL_DEFINE0(sched_yield) { struct rq *rq = this_rq_lock(); schedstat_inc(rq, yld_count); current->sched_class->yield_task(rq); /* * Since we are going to call schedule() anyway, there's * no need to preempt or enable interrupts: */ __release(rq->lock); spin_release(&rq->lock.dep_map, 1, _THIS_IP_); do_raw_spin_unlock(&rq->lock); sched_preempt_enable_no_resched(); schedule(); return 0; } static void __cond_resched(void) { __preempt_count_add(PREEMPT_ACTIVE); __schedule(); __preempt_count_sub(PREEMPT_ACTIVE); } int __sched _cond_resched(void) { if (should_resched()) { __cond_resched(); return 1; } return 0; } EXPORT_SYMBOL(_cond_resched); /* * __cond_resched_lock() - if a reschedule is pending, drop the given lock, * call schedule, and on return reacquire the lock. * * This works OK both with and without CONFIG_PREEMPT. We do strange low-level * operations here to prevent schedule() from being called twice (once via * spin_unlock(), once by hand). */ int __cond_resched_lock(spinlock_t *lock) { int resched = should_resched(); int ret = 0; lockdep_assert_held(lock); if (spin_needbreak(lock) || resched) { spin_unlock(lock); if (resched) __cond_resched(); else cpu_relax(); ret = 1; spin_lock(lock); } return ret; } EXPORT_SYMBOL(__cond_resched_lock); int __sched __cond_resched_softirq(void) { BUG_ON(!in_softirq()); if (should_resched()) { local_bh_enable(); __cond_resched(); local_bh_disable(); return 1; } return 0; } EXPORT_SYMBOL(__cond_resched_softirq); /** * yield - yield the current processor to other threads. * * Do not ever use this function, there's a 99% chance you're doing it wrong. * * The scheduler is at all times free to pick the calling task as the most * eligible task to run, if removing the yield() call from your code breaks * it, its already broken. * * Typical broken usage is: * * while (!event) * yield(); * * where one assumes that yield() will let 'the other' process run that will * make event true. If the current task is a SCHED_FIFO task that will never * happen. Never use yield() as a progress guarantee!! * * If you want to use yield() to wait for something, use wait_event(). * If you want to use yield() to be 'nice' for others, use cond_resched(). * If you still want to use yield(), do not! */ void __sched yield(void) { set_current_state(TASK_RUNNING); sys_sched_yield(); } EXPORT_SYMBOL(yield); /** * yield_to - yield the current processor to another thread in * your thread group, or accelerate that thread toward the * processor it's on. * @p: target task * @preempt: whether task preemption is allowed or not * * It's the caller's job to ensure that the target task struct * can't go away on us before we can do any checks. * * Return: * true (>0) if we indeed boosted the target task. * false (0) if we failed to boost the target. * -ESRCH if there's no task to yield to. */ bool __sched yield_to(struct task_struct *p, bool preempt) { struct task_struct *curr = current; struct rq *rq, *p_rq; unsigned long flags; int yielded = 0; local_irq_save(flags); rq = this_rq(); again: p_rq = task_rq(p); /* * If we're the only runnable task on the rq and target rq also * has only one task, there's absolutely no point in yielding. */ if (rq->nr_running == 1 && p_rq->nr_running == 1) { yielded = -ESRCH; goto out_irq; } double_rq_lock(rq, p_rq); if (task_rq(p) != p_rq) { double_rq_unlock(rq, p_rq); goto again; } if (!curr->sched_class->yield_to_task) goto out_unlock; if (curr->sched_class != p->sched_class) goto out_unlock; if (task_running(p_rq, p) || p->state) goto out_unlock; yielded = curr->sched_class->yield_to_task(rq, p, preempt); if (yielded) { schedstat_inc(rq, yld_count); /* * Make p's CPU reschedule; pick_next_entity takes care of * fairness. */ if (preempt && rq != p_rq) resched_task(p_rq->curr); } out_unlock: double_rq_unlock(rq, p_rq); out_irq: local_irq_restore(flags); if (yielded > 0) schedule(); return yielded; } EXPORT_SYMBOL_GPL(yield_to); /* * This task is about to go to sleep on IO. Increment rq->nr_iowait so * that process accounting knows that this is a task in IO wait state. */ void __sched io_schedule(void) { struct rq *rq = raw_rq(); delayacct_blkio_start(); atomic_inc(&rq->nr_iowait); blk_flush_plug(current); current->in_iowait = 1; schedule(); current->in_iowait = 0; atomic_dec(&rq->nr_iowait); delayacct_blkio_end(); } EXPORT_SYMBOL(io_schedule); long __sched io_schedule_timeout(long timeout) { struct rq *rq = raw_rq(); long ret; delayacct_blkio_start(); atomic_inc(&rq->nr_iowait); blk_flush_plug(current); current->in_iowait = 1; ret = schedule_timeout(timeout); current->in_iowait = 0; atomic_dec(&rq->nr_iowait); delayacct_blkio_end(); return ret; } /** * sys_sched_get_priority_max - return maximum RT priority. * @policy: scheduling class. * * Return: On success, this syscall returns the maximum * rt_priority that can be used by a given scheduling class. * On failure, a negative error code is returned. */ SYSCALL_DEFINE1(sched_get_priority_max, int, policy) { int ret = -EINVAL; switch (policy) { case SCHED_FIFO: case SCHED_RR: ret = MAX_USER_RT_PRIO-1; break; case SCHED_DEADLINE: case SCHED_NORMAL: case SCHED_BATCH: case SCHED_IDLE: ret = 0; break; } return ret; } /** * sys_sched_get_priority_min - return minimum RT priority. * @policy: scheduling class. * * Return: On success, this syscall returns the minimum * rt_priority that can be used by a given scheduling class. * On failure, a negative error code is returned. */ SYSCALL_DEFINE1(sched_get_priority_min, int, policy) { int ret = -EINVAL; switch (policy) { case SCHED_FIFO: case SCHED_RR: ret = 1; break; case SCHED_DEADLINE: case SCHED_NORMAL: case SCHED_BATCH: case SCHED_IDLE: ret = 0; } return ret; } /** * sys_sched_rr_get_interval - return the default timeslice of a process. * @pid: pid of the process. * @interval: userspace pointer to the timeslice value. * * this syscall writes the default timeslice value of a given process * into the user-space timespec buffer. A value of '0' means infinity. * * Return: On success, 0 and the timeslice is in @interval. Otherwise, * an error code. */ SYSCALL_DEFINE2(sched_rr_get_interval, pid_t, pid, struct timespec __user *, interval) { struct task_struct *p; unsigned int time_slice; unsigned long flags; struct rq *rq; int retval; struct timespec t; if (pid < 0) return -EINVAL; retval = -ESRCH; rcu_read_lock(); p = find_process_by_pid(pid); if (!p) goto out_unlock; retval = security_task_getscheduler(p); if (retval) goto out_unlock; rq = task_rq_lock(p, &flags); time_slice = 0; if (p->sched_class->get_rr_interval) time_slice = p->sched_class->get_rr_interval(rq, p); task_rq_unlock(rq, p, &flags); rcu_read_unlock(); jiffies_to_timespec(time_slice, &t); retval = copy_to_user(interval, &t, sizeof(t)) ? -EFAULT : 0; return retval; out_unlock: rcu_read_unlock(); return retval; } static const char stat_nam[] = TASK_STATE_TO_CHAR_STR; void sched_show_task(struct task_struct *p) { unsigned long free = 0; int ppid; unsigned state; state = p->state ? __ffs(p->state) + 1 : 0; printk(KERN_INFO "%-15.15s %c", p->comm, state < sizeof(stat_nam) - 1 ? stat_nam[state] : '?'); #if BITS_PER_LONG == 32 if (state == TASK_RUNNING) printk(KERN_CONT " running "); else printk(KERN_CONT " %08lx ", thread_saved_pc(p)); #else if (state == TASK_RUNNING) printk(KERN_CONT " running task "); else printk(KERN_CONT " %016lx ", thread_saved_pc(p)); #endif #ifdef CONFIG_DEBUG_STACK_USAGE free = stack_not_used(p); #endif rcu_read_lock(); ppid = task_pid_nr(rcu_dereference(p->real_parent)); rcu_read_unlock(); printk(KERN_CONT "%5lu %5d %6d 0x%08lx\n", free, task_pid_nr(p), ppid, (unsigned long)task_thread_info(p)->flags); print_worker_info(KERN_INFO, p); show_stack(p, NULL); } void show_state_filter(unsigned long state_filter) { struct task_struct *g, *p; #if BITS_PER_LONG == 32 printk(KERN_INFO " task PC stack pid father\n"); #else printk(KERN_INFO " task PC stack pid father\n"); #endif rcu_read_lock(); do_each_thread(g, p) { /* * reset the NMI-timeout, listing all files on a slow * console might take a lot of time: */ touch_nmi_watchdog(); if (!state_filter || (p->state & state_filter)) sched_show_task(p); } while_each_thread(g, p); touch_all_softlockup_watchdogs(); #ifdef CONFIG_SCHED_DEBUG sysrq_sched_debug_show(); #endif rcu_read_unlock(); /* * Only show locks if all tasks are dumped: */ if (!state_filter) debug_show_all_locks(); } void init_idle_bootup_task(struct task_struct *idle) { idle->sched_class = &idle_sched_class; } /** * init_idle - set up an idle thread for a given CPU * @idle: task in question * @cpu: cpu the idle task belongs to * * NOTE: this function does not set the idle thread's NEED_RESCHED * flag, to make booting more robust. */ void init_idle(struct task_struct *idle, int cpu) { struct rq *rq = cpu_rq(cpu); unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); __sched_fork(0, idle); idle->state = TASK_RUNNING; idle->se.exec_start = sched_clock(); do_set_cpus_allowed(idle, cpumask_of(cpu)); /* * We're having a chicken and egg problem, even though we are * holding rq->lock, the cpu isn't yet set to this cpu so the * lockdep check in task_group() will fail. * * Similar case to sched_fork(). / Alternatively we could * use task_rq_lock() here and obtain the other rq->lock. * * Silence PROVE_RCU */ rcu_read_lock(); __set_task_cpu(idle, cpu); rcu_read_unlock(); rq->curr = rq->idle = idle; #if defined(CONFIG_SMP) idle->on_cpu = 1; #endif raw_spin_unlock_irqrestore(&rq->lock, flags); /* Set the preempt count _outside_ the spinlocks! */ init_idle_preempt_count(idle, cpu); /* * The idle tasks have their own, simple scheduling class: */ idle->sched_class = &idle_sched_class; ftrace_graph_init_idle_task(idle, cpu); vtime_init_idle(idle, cpu); #if defined(CONFIG_SMP) sprintf(idle->comm, "%s/%d", INIT_TASK_COMM, cpu); #endif } #ifdef CONFIG_SMP void do_set_cpus_allowed(struct task_struct *p, const struct cpumask *new_mask) { if (p->sched_class && p->sched_class->set_cpus_allowed) p->sched_class->set_cpus_allowed(p, new_mask); cpumask_copy(&p->cpus_allowed, new_mask); p->nr_cpus_allowed = cpumask_weight(new_mask); } /* * This is how migration works: * * 1) we invoke migration_cpu_stop() on the target CPU using * stop_one_cpu(). * 2) stopper starts to run (implicitly forcing the migrated thread * off the CPU) * 3) it checks whether the migrated task is still in the wrong runqueue. * 4) if it's in the wrong runqueue then the migration thread removes * it and puts it into the right queue. * 5) stopper completes and stop_one_cpu() returns and the migration * is done. */ /* * Change a given task's CPU affinity. Migrate the thread to a * proper CPU and schedule it away if the CPU it's executing on * is removed from the allowed bitmask. * * NOTE: the caller must have a valid reference to the task, the * task must not exit() & deallocate itself prematurely. The * call is not atomic; no spinlocks may be held. */ int set_cpus_allowed_ptr(struct task_struct *p, const struct cpumask *new_mask) { unsigned long flags; struct rq *rq; unsigned int dest_cpu; int ret = 0; rq = task_rq_lock(p, &flags); if (cpumask_equal(&p->cpus_allowed, new_mask)) goto out; if (!cpumask_intersects(new_mask, cpu_active_mask)) { ret = -EINVAL; goto out; } do_set_cpus_allowed(p, new_mask); /* Can the task run on the task's current CPU? If so, we're done */ if (cpumask_test_cpu(task_cpu(p), new_mask)) goto out; dest_cpu = cpumask_any_and(cpu_active_mask, new_mask); if (p->on_rq) { struct migration_arg arg = { p, dest_cpu }; /* Need help from migration thread: drop lock and wait. */ task_rq_unlock(rq, p, &flags); stop_one_cpu(cpu_of(rq), migration_cpu_stop, &arg); tlb_migrate_finish(p->mm); return 0; } out: task_rq_unlock(rq, p, &flags); return ret; } EXPORT_SYMBOL_GPL(set_cpus_allowed_ptr); /* * Move (not current) task off this cpu, onto dest cpu. We're doing * this because either it can't run here any more (set_cpus_allowed() * away from this CPU, or CPU going down), or because we're * attempting to rebalance this task on exec (sched_exec). * * So we race with normal scheduler movements, but that's OK, as long * as the task is no longer on this CPU. * * Returns non-zero if task was successfully migrated. */ static int __migrate_task(struct task_struct *p, int src_cpu, int dest_cpu) { struct rq *rq_dest, *rq_src; int ret = 0; if (unlikely(!cpu_active(dest_cpu))) return ret; rq_src = cpu_rq(src_cpu); rq_dest = cpu_rq(dest_cpu); raw_spin_lock(&p->pi_lock); double_rq_lock(rq_src, rq_dest); /* Already moved. */ if (task_cpu(p) != src_cpu) goto done; /* Affinity changed (again). */ if (!cpumask_test_cpu(dest_cpu, tsk_cpus_allowed(p))) goto fail; /* * If we're not on a rq, the next wake-up will ensure we're * placed properly. */ if (p->on_rq) { dequeue_task(rq_src, p, 0); set_task_cpu(p, dest_cpu); enqueue_task(rq_dest, p, 0); check_preempt_curr(rq_dest, p, 0); } done: ret = 1; fail: double_rq_unlock(rq_src, rq_dest); raw_spin_unlock(&p->pi_lock); return ret; } #ifdef CONFIG_NUMA_BALANCING /* Migrate current task p to target_cpu */ int migrate_task_to(struct task_struct *p, int target_cpu) { struct migration_arg arg = { p, target_cpu }; int curr_cpu = task_cpu(p); if (curr_cpu == target_cpu) return 0; if (!cpumask_test_cpu(target_cpu, tsk_cpus_allowed(p))) return -EINVAL; /* TODO: This is not properly updating schedstats */ trace_sched_move_numa(p, curr_cpu, target_cpu); return stop_one_cpu(curr_cpu, migration_cpu_stop, &arg); } /* * Requeue a task on a given node and accurately track the number of NUMA * tasks on the runqueues */ void sched_setnuma(struct task_struct *p, int nid) { struct rq *rq; unsigned long flags; bool on_rq, running; rq = task_rq_lock(p, &flags); on_rq = p->on_rq; running = task_current(rq, p); if (on_rq) dequeue_task(rq, p, 0); if (running) p->sched_class->put_prev_task(rq, p); p->numa_preferred_nid = nid; if (running) p->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, p, 0); task_rq_unlock(rq, p, &flags); } #endif /* * migration_cpu_stop - this will be executed by a highprio stopper thread * and performs thread migration by bumping thread off CPU then * 'pushing' onto another runqueue. */ static int migration_cpu_stop(void *data) { struct migration_arg *arg = data; /* * The original target cpu might have gone down and we might * be on another cpu but it doesn't matter. */ local_irq_disable(); __migrate_task(arg->task, raw_smp_processor_id(), arg->dest_cpu); local_irq_enable(); return 0; } #ifdef CONFIG_HOTPLUG_CPU /* * Ensures that the idle task is using init_mm right before its cpu goes * offline. */ void idle_task_exit(void) { struct mm_struct *mm = current->active_mm; BUG_ON(cpu_online(smp_processor_id())); if (mm != &init_mm) switch_mm(mm, &init_mm, current); mmdrop(mm); } /* * Since this CPU is going 'away' for a while, fold any nr_active delta * we might have. Assumes we're called after migrate_tasks() so that the * nr_active count is stable. * * Also see the comment "Global load-average calculations". */ static void calc_load_migrate(struct rq *rq) { long delta = calc_load_fold_active(rq); if (delta) atomic_long_add(delta, &calc_load_tasks); } /* * Migrate all tasks from the rq, sleeping tasks will be migrated by * try_to_wake_up()->select_task_rq(). * * Called with rq->lock held even though we'er in stop_machine() and * there's no concurrency possible, we hold the required locks anyway * because of lock validation efforts. */ static void migrate_tasks(unsigned int dead_cpu) { struct rq *rq = cpu_rq(dead_cpu); struct task_struct *next, *stop = rq->stop; int dest_cpu; /* * Fudge the rq selection such that the below task selection loop * doesn't get stuck on the currently eligible stop task. * * We're currently inside stop_machine() and the rq is either stuck * in the stop_machine_cpu_stop() loop, or we're executing this code, * either way we should never end up calling schedule() until we're * done here. */ rq->stop = NULL; /* * put_prev_task() and pick_next_task() sched * class method both need to have an up-to-date * value of rq->clock[_task] */ update_rq_clock(rq); for ( ; ; ) { /* * There's this thread running, bail when that's the only * remaining thread. */ if (rq->nr_running == 1) break; next = pick_next_task(rq); BUG_ON(!next); next->sched_class->put_prev_task(rq, next); /* Find suitable destination for @next, with force if needed. */ dest_cpu = select_fallback_rq(dead_cpu, next); raw_spin_unlock(&rq->lock); __migrate_task(next, dead_cpu, dest_cpu); raw_spin_lock(&rq->lock); } rq->stop = stop; } #endif /* CONFIG_HOTPLUG_CPU */ #if defined(CONFIG_SCHED_DEBUG) && defined(CONFIG_SYSCTL) static struct ctl_table sd_ctl_dir[] = { { .procname = "sched_domain", .mode = 0555, }, {} }; static struct ctl_table sd_ctl_root[] = { { .procname = "kernel", .mode = 0555, .child = sd_ctl_dir, }, {} }; static struct ctl_table *sd_alloc_ctl_entry(int n) { struct ctl_table *entry = kcalloc(n, sizeof(struct ctl_table), GFP_KERNEL); return entry; } static void sd_free_ctl_entry(struct ctl_table **tablep) { struct ctl_table *entry; /* * In the intermediate directories, both the child directory and * procname are dynamically allocated and could fail but the mode * will always be set. In the lowest directory the names are * static strings and all have proc handlers. */ for (entry = *tablep; entry->mode; entry++) { if (entry->child) sd_free_ctl_entry(&entry->child); if (entry->proc_handler == NULL) kfree(entry->procname); } kfree(*tablep); *tablep = NULL; } static int min_load_idx = 0; static int max_load_idx = CPU_LOAD_IDX_MAX-1; static void set_table_entry(struct ctl_table *entry, const char *procname, void *data, int maxlen, umode_t mode, proc_handler *proc_handler, bool load_idx) { entry->procname = procname; entry->data = data; entry->maxlen = maxlen; entry->mode = mode; entry->proc_handler = proc_handler; if (load_idx) { entry->extra1 = &min_load_idx; entry->extra2 = &max_load_idx; } } static struct ctl_table * sd_alloc_ctl_domain_table(struct sched_domain *sd) { struct ctl_table *table = sd_alloc_ctl_entry(13); if (table == NULL) return NULL; set_table_entry(&table[0], "min_interval", &sd->min_interval, sizeof(long), 0644, proc_doulongvec_minmax, false); set_table_entry(&table[1], "max_interval", &sd->max_interval, sizeof(long), 0644, proc_doulongvec_minmax, false); set_table_entry(&table[2], "busy_idx", &sd->busy_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[3], "idle_idx", &sd->idle_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[4], "newidle_idx", &sd->newidle_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[5], "wake_idx", &sd->wake_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[6], "forkexec_idx", &sd->forkexec_idx, sizeof(int), 0644, proc_dointvec_minmax, true); set_table_entry(&table[7], "busy_factor", &sd->busy_factor, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[8], "imbalance_pct", &sd->imbalance_pct, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[9], "cache_nice_tries", &sd->cache_nice_tries, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[10], "flags", &sd->flags, sizeof(int), 0644, proc_dointvec_minmax, false); set_table_entry(&table[11], "name", sd->name, CORENAME_MAX_SIZE, 0444, proc_dostring, false); /* &table[12] is terminator */ return table; } static struct ctl_table *sd_alloc_ctl_cpu_table(int cpu) { struct ctl_table *entry, *table; struct sched_domain *sd; int domain_num = 0, i; char buf[32]; for_each_domain(cpu, sd) domain_num++; entry = table = sd_alloc_ctl_entry(domain_num + 1); if (table == NULL) return NULL; i = 0; for_each_domain(cpu, sd) { snprintf(buf, 32, "domain%d", i); entry->procname = kstrdup(buf, GFP_KERNEL); entry->mode = 0555; entry->child = sd_alloc_ctl_domain_table(sd); entry++; i++; } return table; } static struct ctl_table_header *sd_sysctl_header; static void register_sched_domain_sysctl(void) { int i, cpu_num = num_possible_cpus(); struct ctl_table *entry = sd_alloc_ctl_entry(cpu_num + 1); char buf[32]; WARN_ON(sd_ctl_dir[0].child); sd_ctl_dir[0].child = entry; if (entry == NULL) return; for_each_possible_cpu(i) { snprintf(buf, 32, "cpu%d", i); entry->procname = kstrdup(buf, GFP_KERNEL); entry->mode = 0555; entry->child = sd_alloc_ctl_cpu_table(i); entry++; } WARN_ON(sd_sysctl_header); sd_sysctl_header = register_sysctl_table(sd_ctl_root); } /* may be called multiple times per register */ static void unregister_sched_domain_sysctl(void) { if (sd_sysctl_header) unregister_sysctl_table(sd_sysctl_header); sd_sysctl_header = NULL; if (sd_ctl_dir[0].child) sd_free_ctl_entry(&sd_ctl_dir[0].child); } #else static void register_sched_domain_sysctl(void) { } static void unregister_sched_domain_sysctl(void) { } #endif static void set_rq_online(struct rq *rq) { if (!rq->online) { const struct sched_class *class; cpumask_set_cpu(rq->cpu, rq->rd->online); rq->online = 1; for_each_class(class) { if (class->rq_online) class->rq_online(rq); } } } static void set_rq_offline(struct rq *rq) { if (rq->online) { const struct sched_class *class; for_each_class(class) { if (class->rq_offline) class->rq_offline(rq); } cpumask_clear_cpu(rq->cpu, rq->rd->online); rq->online = 0; } } /* * migration_call - callback that gets triggered when a CPU is added. * Here we can start up the necessary migration thread for the new CPU. */ static int migration_call(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (long)hcpu; unsigned long flags; struct rq *rq = cpu_rq(cpu); switch (action & ~CPU_TASKS_FROZEN) { case CPU_UP_PREPARE: rq->calc_load_update = calc_load_update; break; case CPU_ONLINE: /* Update our root-domain */ raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); set_rq_online(rq); } raw_spin_unlock_irqrestore(&rq->lock, flags); break; #ifdef CONFIG_HOTPLUG_CPU case CPU_DYING: sched_ttwu_pending(); /* Update our root-domain */ raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { BUG_ON(!cpumask_test_cpu(cpu, rq->rd->span)); set_rq_offline(rq); } migrate_tasks(cpu); BUG_ON(rq->nr_running != 1); /* the migration thread */ raw_spin_unlock_irqrestore(&rq->lock, flags); break; case CPU_DEAD: calc_load_migrate(rq); break; #endif } update_max_interval(); return NOTIFY_OK; } /* * Register at high priority so that task migration (migrate_all_tasks) * happens before everything else. This has to be lower priority than * the notifier in the perf_event subsystem, though. */ static struct notifier_block migration_notifier = { .notifier_call = migration_call, .priority = CPU_PRI_MIGRATION, }; static int sched_cpu_active(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action & ~CPU_TASKS_FROZEN) { case CPU_STARTING: case CPU_DOWN_FAILED: set_cpu_active((long)hcpu, true); return NOTIFY_OK; default: return NOTIFY_DONE; } } static int sched_cpu_inactive(struct notifier_block *nfb, unsigned long action, void *hcpu) { unsigned long flags; long cpu = (long)hcpu; switch (action & ~CPU_TASKS_FROZEN) { case CPU_DOWN_PREPARE: set_cpu_active(cpu, false); /* explicitly allow suspend */ if (!(action & CPU_TASKS_FROZEN)) { struct dl_bw *dl_b = dl_bw_of(cpu); bool overflow; int cpus; raw_spin_lock_irqsave(&dl_b->lock, flags); cpus = dl_bw_cpus(cpu); overflow = __dl_overflow(dl_b, cpus, 0, 0); raw_spin_unlock_irqrestore(&dl_b->lock, flags); if (overflow) return notifier_from_errno(-EBUSY); } return NOTIFY_OK; } return NOTIFY_DONE; } static int __init migration_init(void) { void *cpu = (void *)(long)smp_processor_id(); int err; /* Initialize migration for the boot CPU */ err = migration_call(&migration_notifier, CPU_UP_PREPARE, cpu); BUG_ON(err == NOTIFY_BAD); migration_call(&migration_notifier, CPU_ONLINE, cpu); register_cpu_notifier(&migration_notifier); /* Register cpu active notifiers */ cpu_notifier(sched_cpu_active, CPU_PRI_SCHED_ACTIVE); cpu_notifier(sched_cpu_inactive, CPU_PRI_SCHED_INACTIVE); return 0; } early_initcall(migration_init); #endif #ifdef CONFIG_SMP static cpumask_var_t sched_domains_tmpmask; /* sched_domains_mutex */ #ifdef CONFIG_SCHED_DEBUG static __read_mostly int sched_debug_enabled; static int __init sched_debug_setup(char *str) { sched_debug_enabled = 1; return 0; } early_param("sched_debug", sched_debug_setup); static inline bool sched_debug(void) { return sched_debug_enabled; } static int sched_domain_debug_one(struct sched_domain *sd, int cpu, int level, struct cpumask *groupmask) { struct sched_group *group = sd->groups; char str[256]; cpulist_scnprintf(str, sizeof(str), sched_domain_span(sd)); cpumask_clear(groupmask); printk(KERN_DEBUG "%*s domain %d: ", level, "", level); if (!(sd->flags & SD_LOAD_BALANCE)) { printk("does not load-balance\n"); if (sd->parent) printk(KERN_ERR "ERROR: !SD_LOAD_BALANCE domain" " has parent"); return -1; } printk(KERN_CONT "span %s level %s\n", str, sd->name); if (!cpumask_test_cpu(cpu, sched_domain_span(sd))) { printk(KERN_ERR "ERROR: domain->span does not contain " "CPU%d\n", cpu); } if (!cpumask_test_cpu(cpu, sched_group_cpus(group))) { printk(KERN_ERR "ERROR: domain->groups does not contain" " CPU%d\n", cpu); } printk(KERN_DEBUG "%*s groups:", level + 1, ""); do { if (!group) { printk("\n"); printk(KERN_ERR "ERROR: group is NULL\n"); break; } /* * Even though we initialize ->power to something semi-sane, * we leave power_orig unset. This allows us to detect if * domain iteration is still funny without causing /0 traps. */ if (!group->sgp->power_orig) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: domain->cpu_power not " "set\n"); break; } if (!cpumask_weight(sched_group_cpus(group))) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: empty group\n"); break; } if (!(sd->flags & SD_OVERLAP) && cpumask_intersects(groupmask, sched_group_cpus(group))) { printk(KERN_CONT "\n"); printk(KERN_ERR "ERROR: repeated CPUs\n"); break; } cpumask_or(groupmask, groupmask, sched_group_cpus(group)); cpulist_scnprintf(str, sizeof(str), sched_group_cpus(group)); printk(KERN_CONT " %s", str); if (group->sgp->power != SCHED_POWER_SCALE) { printk(KERN_CONT " (cpu_power = %d)", group->sgp->power); } group = group->next; } while (group != sd->groups); printk(KERN_CONT "\n"); if (!cpumask_equal(sched_domain_span(sd), groupmask)) printk(KERN_ERR "ERROR: groups don't span domain->span\n"); if (sd->parent && !cpumask_subset(groupmask, sched_domain_span(sd->parent))) printk(KERN_ERR "ERROR: parent span is not a superset " "of domain->span\n"); return 0; } static void sched_domain_debug(struct sched_domain *sd, int cpu) { int level = 0; if (!sched_debug_enabled) return; if (!sd) { printk(KERN_DEBUG "CPU%d attaching NULL sched-domain.\n", cpu); return; } printk(KERN_DEBUG "CPU%d attaching sched-domain:\n", cpu); for (;;) { if (sched_domain_debug_one(sd, cpu, level, sched_domains_tmpmask)) break; level++; sd = sd->parent; if (!sd) break; } } #else /* !CONFIG_SCHED_DEBUG */ # define sched_domain_debug(sd, cpu) do { } while (0) static inline bool sched_debug(void) { return false; } #endif /* CONFIG_SCHED_DEBUG */ static int sd_degenerate(struct sched_domain *sd) { if (cpumask_weight(sched_domain_span(sd)) == 1) return 1; /* Following flags need at least 2 groups */ if (sd->flags & (SD_LOAD_BALANCE | SD_BALANCE_NEWIDLE | SD_BALANCE_FORK | SD_BALANCE_EXEC | SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES)) { if (sd->groups != sd->groups->next) return 0; } /* Following flags don't use groups */ if (sd->flags & (SD_WAKE_AFFINE)) return 0; return 1; } static int sd_parent_degenerate(struct sched_domain *sd, struct sched_domain *parent) { unsigned long cflags = sd->flags, pflags = parent->flags; if (sd_degenerate(parent)) return 1; if (!cpumask_equal(sched_domain_span(sd), sched_domain_span(parent))) return 0; /* Flags needing groups don't count if only 1 group in parent */ if (parent->groups == parent->groups->next) { pflags &= ~(SD_LOAD_BALANCE | SD_BALANCE_NEWIDLE | SD_BALANCE_FORK | SD_BALANCE_EXEC | SD_SHARE_CPUPOWER | SD_SHARE_PKG_RESOURCES | SD_PREFER_SIBLING); if (nr_node_ids == 1) pflags &= ~SD_SERIALIZE; } if (~cflags & pflags) return 0; return 1; } static void free_rootdomain(struct rcu_head *rcu) { struct root_domain *rd = container_of(rcu, struct root_domain, rcu); cpupri_cleanup(&rd->cpupri); cpudl_cleanup(&rd->cpudl); free_cpumask_var(rd->dlo_mask); free_cpumask_var(rd->rto_mask); free_cpumask_var(rd->online); free_cpumask_var(rd->span); kfree(rd); } static void rq_attach_root(struct rq *rq, struct root_domain *rd) { struct root_domain *old_rd = NULL; unsigned long flags; raw_spin_lock_irqsave(&rq->lock, flags); if (rq->rd) { old_rd = rq->rd; if (cpumask_test_cpu(rq->cpu, old_rd->online)) set_rq_offline(rq); cpumask_clear_cpu(rq->cpu, old_rd->span); /* * If we dont want to free the old_rd yet then * set old_rd to NULL to skip the freeing later * in this function: */ if (!atomic_dec_and_test(&old_rd->refcount)) old_rd = NULL; } atomic_inc(&rd->refcount); rq->rd = rd; cpumask_set_cpu(rq->cpu, rd->span); if (cpumask_test_cpu(rq->cpu, cpu_active_mask)) set_rq_online(rq); raw_spin_unlock_irqrestore(&rq->lock, flags); if (old_rd) call_rcu_sched(&old_rd->rcu, free_rootdomain); } static int init_rootdomain(struct root_domain *rd) { memset(rd, 0, sizeof(*rd)); if (!alloc_cpumask_var(&rd->span, GFP_KERNEL)) goto out; if (!alloc_cpumask_var(&rd->online, GFP_KERNEL)) goto free_span; if (!alloc_cpumask_var(&rd->dlo_mask, GFP_KERNEL)) goto free_online; if (!alloc_cpumask_var(&rd->rto_mask, GFP_KERNEL)) goto free_dlo_mask; init_dl_bw(&rd->dl_bw); if (cpudl_init(&rd->cpudl) != 0) goto free_dlo_mask; if (cpupri_init(&rd->cpupri) != 0) goto free_rto_mask; return 0; free_rto_mask: free_cpumask_var(rd->rto_mask); free_dlo_mask: free_cpumask_var(rd->dlo_mask); free_online: free_cpumask_var(rd->online); free_span: free_cpumask_var(rd->span); out: return -ENOMEM; } /* * By default the system creates a single root-domain with all cpus as * members (mimicking the global state we have today). */ struct root_domain def_root_domain; static void init_defrootdomain(void) { init_rootdomain(&def_root_domain); atomic_set(&def_root_domain.refcount, 1); } static struct root_domain *alloc_rootdomain(void) { struct root_domain *rd; rd = kmalloc(sizeof(*rd), GFP_KERNEL); if (!rd) return NULL; if (init_rootdomain(rd) != 0) { kfree(rd); return NULL; } return rd; } static void free_sched_groups(struct sched_group *sg, int free_sgp) { struct sched_group *tmp, *first; if (!sg) return; first = sg; do { tmp = sg->next; if (free_sgp && atomic_dec_and_test(&sg->sgp->ref)) kfree(sg->sgp); kfree(sg); sg = tmp; } while (sg != first); } static void free_sched_domain(struct rcu_head *rcu) { struct sched_domain *sd = container_of(rcu, struct sched_domain, rcu); /* * If its an overlapping domain it has private groups, iterate and * nuke them all. */ if (sd->flags & SD_OVERLAP) { free_sched_groups(sd->groups, 1); } else if (atomic_dec_and_test(&sd->groups->ref)) { kfree(sd->groups->sgp); kfree(sd->groups); } kfree(sd); } static void destroy_sched_domain(struct sched_domain *sd, int cpu) { call_rcu(&sd->rcu, free_sched_domain); } static void destroy_sched_domains(struct sched_domain *sd, int cpu) { for (; sd; sd = sd->parent) destroy_sched_domain(sd, cpu); } /* * Keep a special pointer to the highest sched_domain that has * SD_SHARE_PKG_RESOURCE set (Last Level Cache Domain) for this * allows us to avoid some pointer chasing select_idle_sibling(). * * Also keep a unique ID per domain (we use the first cpu number in * the cpumask of the domain), this allows us to quickly tell if * two cpus are in the same cache domain, see cpus_share_cache(). */ DEFINE_PER_CPU(struct sched_domain *, sd_llc); DEFINE_PER_CPU(int, sd_llc_size); DEFINE_PER_CPU(int, sd_llc_id); DEFINE_PER_CPU(struct sched_domain *, sd_numa); DEFINE_PER_CPU(struct sched_domain *, sd_busy); DEFINE_PER_CPU(struct sched_domain *, sd_asym); static void update_top_cache_domain(int cpu) { struct sched_domain *sd; struct sched_domain *busy_sd = NULL; int id = cpu; int size = 1; sd = highest_flag_domain(cpu, SD_SHARE_PKG_RESOURCES); if (sd) { id = cpumask_first(sched_domain_span(sd)); size = cpumask_weight(sched_domain_span(sd)); busy_sd = sd->parent; /* sd_busy */ } rcu_assign_pointer(per_cpu(sd_busy, cpu), busy_sd); rcu_assign_pointer(per_cpu(sd_llc, cpu), sd); per_cpu(sd_llc_size, cpu) = size; per_cpu(sd_llc_id, cpu) = id; sd = lowest_flag_domain(cpu, SD_NUMA); rcu_assign_pointer(per_cpu(sd_numa, cpu), sd); sd = highest_flag_domain(cpu, SD_ASYM_PACKING); rcu_assign_pointer(per_cpu(sd_asym, cpu), sd); } /* * Attach the domain 'sd' to 'cpu' as its base domain. Callers must * hold the hotplug lock. */ static void cpu_attach_domain(struct sched_domain *sd, struct root_domain *rd, int cpu) { struct rq *rq = cpu_rq(cpu); struct sched_domain *tmp; /* Remove the sched domains which do not contribute to scheduling. */ for (tmp = sd; tmp; ) { struct sched_domain *parent = tmp->parent; if (!parent) break; if (sd_parent_degenerate(tmp, parent)) { tmp->parent = parent->parent; if (parent->parent) parent->parent->child = tmp; /* * Transfer SD_PREFER_SIBLING down in case of a * degenerate parent; the spans match for this * so the property transfers. */ if (parent->flags & SD_PREFER_SIBLING) tmp->flags |= SD_PREFER_SIBLING; destroy_sched_domain(parent, cpu); } else tmp = tmp->parent; } if (sd && sd_degenerate(sd)) { tmp = sd; sd = sd->parent; destroy_sched_domain(tmp, cpu); if (sd) sd->child = NULL; } sched_domain_debug(sd, cpu); rq_attach_root(rq, rd); tmp = rq->sd; rcu_assign_pointer(rq->sd, sd); destroy_sched_domains(tmp, cpu); update_top_cache_domain(cpu); } /* cpus with isolated domains */ static cpumask_var_t cpu_isolated_map; /* Setup the mask of cpus configured for isolated domains */ static int __init isolated_cpu_setup(char *str) { alloc_bootmem_cpumask_var(&cpu_isolated_map); cpulist_parse(str, cpu_isolated_map); return 1; } __setup("isolcpus=", isolated_cpu_setup); static const struct cpumask *cpu_cpu_mask(int cpu) { return cpumask_of_node(cpu_to_node(cpu)); } struct sd_data { struct sched_domain **__percpu sd; struct sched_group **__percpu sg; struct sched_group_power **__percpu sgp; }; struct s_data { struct sched_domain ** __percpu sd; struct root_domain *rd; }; enum s_alloc { sa_rootdomain, sa_sd, sa_sd_storage, sa_none, }; struct sched_domain_topology_level; typedef struct sched_domain *(*sched_domain_init_f)(struct sched_domain_topology_level *tl, int cpu); typedef const struct cpumask *(*sched_domain_mask_f)(int cpu); #define SDTL_OVERLAP 0x01 struct sched_domain_topology_level { sched_domain_init_f init; sched_domain_mask_f mask; int flags; int numa_level; struct sd_data data; }; /* * Build an iteration mask that can exclude certain CPUs from the upwards * domain traversal. * * Asymmetric node setups can result in situations where the domain tree is of * unequal depth, make sure to skip domains that already cover the entire * range. * * In that case build_sched_domains() will have terminated the iteration early * and our sibling sd spans will be empty. Domains should always include the * cpu they're built on, so check that. * */ static void build_group_mask(struct sched_domain *sd, struct sched_group *sg) { const struct cpumask *span = sched_domain_span(sd); struct sd_data *sdd = sd->private; struct sched_domain *sibling; int i; for_each_cpu(i, span) { sibling = *per_cpu_ptr(sdd->sd, i); if (!cpumask_test_cpu(i, sched_domain_span(sibling))) continue; cpumask_set_cpu(i, sched_group_mask(sg)); } } /* * Return the canonical balance cpu for this group, this is the first cpu * of this group that's also in the iteration mask. */ int group_balance_cpu(struct sched_group *sg) { return cpumask_first_and(sched_group_cpus(sg), sched_group_mask(sg)); } static int build_overlap_sched_groups(struct sched_domain *sd, int cpu) { struct sched_group *first = NULL, *last = NULL, *groups = NULL, *sg; const struct cpumask *span = sched_domain_span(sd); struct cpumask *covered = sched_domains_tmpmask; struct sd_data *sdd = sd->private; struct sched_domain *child; int i; cpumask_clear(covered); for_each_cpu(i, span) { struct cpumask *sg_span; if (cpumask_test_cpu(i, covered)) continue; child = *per_cpu_ptr(sdd->sd, i); /* See the comment near build_group_mask(). */ if (!cpumask_test_cpu(i, sched_domain_span(child))) continue; sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), GFP_KERNEL, cpu_to_node(cpu)); if (!sg) goto fail; sg_span = sched_group_cpus(sg); if (child->child) { child = child->child; cpumask_copy(sg_span, sched_domain_span(child)); } else cpumask_set_cpu(i, sg_span); cpumask_or(covered, covered, sg_span); sg->sgp = *per_cpu_ptr(sdd->sgp, i); if (atomic_inc_return(&sg->sgp->ref) == 1) build_group_mask(sd, sg); /* * Initialize sgp->power such that even if we mess up the * domains and no possible iteration will get us here, we won't * die on a /0 trap. */ sg->sgp->power = SCHED_POWER_SCALE * cpumask_weight(sg_span); sg->sgp->power_orig = sg->sgp->power; /* * Make sure the first group of this domain contains the * canonical balance cpu. Otherwise the sched_domain iteration * breaks. See update_sg_lb_stats(). */ if ((!groups && cpumask_test_cpu(cpu, sg_span)) || group_balance_cpu(sg) == cpu) groups = sg; if (!first) first = sg; if (last) last->next = sg; last = sg; last->next = first; } sd->groups = groups; return 0; fail: free_sched_groups(first, 0); return -ENOMEM; } static int get_group(int cpu, struct sd_data *sdd, struct sched_group **sg) { struct sched_domain *sd = *per_cpu_ptr(sdd->sd, cpu); struct sched_domain *child = sd->child; if (child) cpu = cpumask_first(sched_domain_span(child)); if (sg) { *sg = *per_cpu_ptr(sdd->sg, cpu); (*sg)->sgp = *per_cpu_ptr(sdd->sgp, cpu); atomic_set(&(*sg)->sgp->ref, 1); /* for claim_allocations */ } return cpu; } /* * build_sched_groups will build a circular linked list of the groups * covered by the given span, and will set each group's ->cpumask correctly, * and ->cpu_power to 0. * * Assumes the sched_domain tree is fully constructed */ static int build_sched_groups(struct sched_domain *sd, int cpu) { struct sched_group *first = NULL, *last = NULL; struct sd_data *sdd = sd->private; const struct cpumask *span = sched_domain_span(sd); struct cpumask *covered; int i; get_group(cpu, sdd, &sd->groups); atomic_inc(&sd->groups->ref); if (cpu != cpumask_first(span)) return 0; lockdep_assert_held(&sched_domains_mutex); covered = sched_domains_tmpmask; cpumask_clear(covered); for_each_cpu(i, span) { struct sched_group *sg; int group, j; if (cpumask_test_cpu(i, covered)) continue; group = get_group(i, sdd, &sg); cpumask_clear(sched_group_cpus(sg)); sg->sgp->power = 0; cpumask_setall(sched_group_mask(sg)); for_each_cpu(j, span) { if (get_group(j, sdd, NULL) != group) continue; cpumask_set_cpu(j, covered); cpumask_set_cpu(j, sched_group_cpus(sg)); } if (!first) first = sg; if (last) last->next = sg; last = sg; } last->next = first; return 0; } /* * Initialize sched groups cpu_power. * * cpu_power indicates the capacity of sched group, which is used while * distributing the load between different sched groups in a sched domain. * Typically cpu_power for all the groups in a sched domain will be same unless * there are asymmetries in the topology. If there are asymmetries, group * having more cpu_power will pickup more load compared to the group having * less cpu_power. */ static void init_sched_groups_power(int cpu, struct sched_domain *sd) { struct sched_group *sg = sd->groups; WARN_ON(!sg); do { sg->group_weight = cpumask_weight(sched_group_cpus(sg)); sg = sg->next; } while (sg != sd->groups); if (cpu != group_balance_cpu(sg)) return; update_group_power(sd, cpu); atomic_set(&sg->sgp->nr_busy_cpus, sg->group_weight); } int __weak arch_sd_sibling_asym_packing(void) { return 0*SD_ASYM_PACKING; } /* * Initializers for schedule domains * Non-inlined to reduce accumulated stack pressure in build_sched_domains() */ #ifdef CONFIG_SCHED_DEBUG # define SD_INIT_NAME(sd, type) sd->name = #type #else # define SD_INIT_NAME(sd, type) do { } while (0) #endif #define SD_INIT_FUNC(type) \ static noinline struct sched_domain * \ sd_init_##type(struct sched_domain_topology_level *tl, int cpu) \ { \ struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); \ *sd = SD_##type##_INIT; \ SD_INIT_NAME(sd, type); \ sd->private = &tl->data; \ return sd; \ } SD_INIT_FUNC(CPU) #ifdef CONFIG_SCHED_SMT SD_INIT_FUNC(SIBLING) #endif #ifdef CONFIG_SCHED_MC SD_INIT_FUNC(MC) #endif #ifdef CONFIG_SCHED_BOOK SD_INIT_FUNC(BOOK) #endif static int default_relax_domain_level = -1; int sched_domain_level_max; static int __init setup_relax_domain_level(char *str) { if (kstrtoint(str, 0, &default_relax_domain_level)) pr_warn("Unable to set relax_domain_level\n"); return 1; } __setup("relax_domain_level=", setup_relax_domain_level); static void set_domain_attribute(struct sched_domain *sd, struct sched_domain_attr *attr) { int request; if (!attr || attr->relax_domain_level < 0) { if (default_relax_domain_level < 0) return; else request = default_relax_domain_level; } else request = attr->relax_domain_level; if (request < sd->level) { /* turn off idle balance on this domain */ sd->flags &= ~(SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); } else { /* turn on idle balance on this domain */ sd->flags |= (SD_BALANCE_WAKE|SD_BALANCE_NEWIDLE); } } static void __sdt_free(const struct cpumask *cpu_map); static int __sdt_alloc(const struct cpumask *cpu_map); static void __free_domain_allocs(struct s_data *d, enum s_alloc what, const struct cpumask *cpu_map) { switch (what) { case sa_rootdomain: if (!atomic_read(&d->rd->refcount)) free_rootdomain(&d->rd->rcu); /* fall through */ case sa_sd: free_percpu(d->sd); /* fall through */ case sa_sd_storage: __sdt_free(cpu_map); /* fall through */ case sa_none: break; } } static enum s_alloc __visit_domain_allocation_hell(struct s_data *d, const struct cpumask *cpu_map) { memset(d, 0, sizeof(*d)); if (__sdt_alloc(cpu_map)) return sa_sd_storage; d->sd = alloc_percpu(struct sched_domain *); if (!d->sd) return sa_sd_storage; d->rd = alloc_rootdomain(); if (!d->rd) return sa_sd; return sa_rootdomain; } /* * NULL the sd_data elements we've used to build the sched_domain and * sched_group structure so that the subsequent __free_domain_allocs() * will not free the data we're using. */ static void claim_allocations(int cpu, struct sched_domain *sd) { struct sd_data *sdd = sd->private; WARN_ON_ONCE(*per_cpu_ptr(sdd->sd, cpu) != sd); *per_cpu_ptr(sdd->sd, cpu) = NULL; if (atomic_read(&(*per_cpu_ptr(sdd->sg, cpu))->ref)) *per_cpu_ptr(sdd->sg, cpu) = NULL; if (atomic_read(&(*per_cpu_ptr(sdd->sgp, cpu))->ref)) *per_cpu_ptr(sdd->sgp, cpu) = NULL; } #ifdef CONFIG_SCHED_SMT static const struct cpumask *cpu_smt_mask(int cpu) { return topology_thread_cpumask(cpu); } #endif /* * Topology list, bottom-up. */ static struct sched_domain_topology_level default_topology[] = { #ifdef CONFIG_SCHED_SMT { sd_init_SIBLING, cpu_smt_mask, }, #endif #ifdef CONFIG_SCHED_MC { sd_init_MC, cpu_coregroup_mask, }, #endif #ifdef CONFIG_SCHED_BOOK { sd_init_BOOK, cpu_book_mask, }, #endif { sd_init_CPU, cpu_cpu_mask, }, { NULL, }, }; static struct sched_domain_topology_level *sched_domain_topology = default_topology; #define for_each_sd_topology(tl) \ for (tl = sched_domain_topology; tl->init; tl++) #ifdef CONFIG_NUMA static int sched_domains_numa_levels; static int *sched_domains_numa_distance; static struct cpumask ***sched_domains_numa_masks; static int sched_domains_curr_level; static inline int sd_local_flags(int level) { if (sched_domains_numa_distance[level] > RECLAIM_DISTANCE) return 0; return SD_BALANCE_EXEC | SD_BALANCE_FORK | SD_WAKE_AFFINE; } static struct sched_domain * sd_numa_init(struct sched_domain_topology_level *tl, int cpu) { struct sched_domain *sd = *per_cpu_ptr(tl->data.sd, cpu); int level = tl->numa_level; int sd_weight = cpumask_weight( sched_domains_numa_masks[level][cpu_to_node(cpu)]); *sd = (struct sched_domain){ .min_interval = sd_weight, .max_interval = 2*sd_weight, .busy_factor = 32, .imbalance_pct = 125, .cache_nice_tries = 2, .busy_idx = 3, .idle_idx = 2, .newidle_idx = 0, .wake_idx = 0, .forkexec_idx = 0, .flags = 1*SD_LOAD_BALANCE | 1*SD_BALANCE_NEWIDLE | 0*SD_BALANCE_EXEC | 0*SD_BALANCE_FORK | 0*SD_BALANCE_WAKE | 0*SD_WAKE_AFFINE | 0*SD_SHARE_CPUPOWER | 0*SD_SHARE_PKG_RESOURCES | 1*SD_SERIALIZE | 0*SD_PREFER_SIBLING | 1*SD_NUMA | sd_local_flags(level) , .last_balance = jiffies, .balance_interval = sd_weight, }; SD_INIT_NAME(sd, NUMA); sd->private = &tl->data; /* * Ugly hack to pass state to sd_numa_mask()... */ sched_domains_curr_level = tl->numa_level; return sd; } static const struct cpumask *sd_numa_mask(int cpu) { return sched_domains_numa_masks[sched_domains_curr_level][cpu_to_node(cpu)]; } static void sched_numa_warn(const char *str) { static int done = false; int i,j; if (done) return; done = true; printk(KERN_WARNING "ERROR: %s\n\n", str); for (i = 0; i < nr_node_ids; i++) { printk(KERN_WARNING " "); for (j = 0; j < nr_node_ids; j++) printk(KERN_CONT "%02d ", node_distance(i,j)); printk(KERN_CONT "\n"); } printk(KERN_WARNING "\n"); } static bool find_numa_distance(int distance) { int i; if (distance == node_distance(0, 0)) return true; for (i = 0; i < sched_domains_numa_levels; i++) { if (sched_domains_numa_distance[i] == distance) return true; } return false; } static void sched_init_numa(void) { int next_distance, curr_distance = node_distance(0, 0); struct sched_domain_topology_level *tl; int level = 0; int i, j, k; sched_domains_numa_distance = kzalloc(sizeof(int) * nr_node_ids, GFP_KERNEL); if (!sched_domains_numa_distance) return; /* * O(nr_nodes^2) deduplicating selection sort -- in order to find the * unique distances in the node_distance() table. * * Assumes node_distance(0,j) includes all distances in * node_distance(i,j) in order to avoid cubic time. */ next_distance = curr_distance; for (i = 0; i < nr_node_ids; i++) { for (j = 0; j < nr_node_ids; j++) { for (k = 0; k < nr_node_ids; k++) { int distance = node_distance(i, k); if (distance > curr_distance && (distance < next_distance || next_distance == curr_distance)) next_distance = distance; /* * While not a strong assumption it would be nice to know * about cases where if node A is connected to B, B is not * equally connected to A. */ if (sched_debug() && node_distance(k, i) != distance) sched_numa_warn("Node-distance not symmetric"); if (sched_debug() && i && !find_numa_distance(distance)) sched_numa_warn("Node-0 not representative"); } if (next_distance != curr_distance) { sched_domains_numa_distance[level++] = next_distance; sched_domains_numa_levels = level; curr_distance = next_distance; } else break; } /* * In case of sched_debug() we verify the above assumption. */ if (!sched_debug()) break; } /* * 'level' contains the number of unique distances, excluding the * identity distance node_distance(i,i). * * The sched_domains_numa_distance[] array includes the actual distance * numbers. */ /* * Here, we should temporarily reset sched_domains_numa_levels to 0. * If it fails to allocate memory for array sched_domains_numa_masks[][], * the array will contain less then 'level' members. This could be * dangerous when we use it to iterate array sched_domains_numa_masks[][] * in other functions. * * We reset it to 'level' at the end of this function. */ sched_domains_numa_levels = 0; sched_domains_numa_masks = kzalloc(sizeof(void *) * level, GFP_KERNEL); if (!sched_domains_numa_masks) return; /* * Now for each level, construct a mask per node which contains all * cpus of nodes that are that many hops away from us. */ for (i = 0; i < level; i++) { sched_domains_numa_masks[i] = kzalloc(nr_node_ids * sizeof(void *), GFP_KERNEL); if (!sched_domains_numa_masks[i]) return; for (j = 0; j < nr_node_ids; j++) { struct cpumask *mask = kzalloc(cpumask_size(), GFP_KERNEL); if (!mask) return; sched_domains_numa_masks[i][j] = mask; for (k = 0; k < nr_node_ids; k++) { if (node_distance(j, k) > sched_domains_numa_distance[i]) continue; cpumask_or(mask, mask, cpumask_of_node(k)); } } } tl = kzalloc((ARRAY_SIZE(default_topology) + level) * sizeof(struct sched_domain_topology_level), GFP_KERNEL); if (!tl) return; /* * Copy the default topology bits.. */ for (i = 0; default_topology[i].init; i++) tl[i] = default_topology[i]; /* * .. and append 'j' levels of NUMA goodness. */ for (j = 0; j < level; i++, j++) { tl[i] = (struct sched_domain_topology_level){ .init = sd_numa_init, .mask = sd_numa_mask, .flags = SDTL_OVERLAP, .numa_level = j, }; } sched_domain_topology = tl; sched_domains_numa_levels = level; } static void sched_domains_numa_masks_set(int cpu) { int i, j; int node = cpu_to_node(cpu); for (i = 0; i < sched_domains_numa_levels; i++) { for (j = 0; j < nr_node_ids; j++) { if (node_distance(j, node) <= sched_domains_numa_distance[i]) cpumask_set_cpu(cpu, sched_domains_numa_masks[i][j]); } } } static void sched_domains_numa_masks_clear(int cpu) { int i, j; for (i = 0; i < sched_domains_numa_levels; i++) { for (j = 0; j < nr_node_ids; j++) cpumask_clear_cpu(cpu, sched_domains_numa_masks[i][j]); } } /* * Update sched_domains_numa_masks[level][node] array when new cpus * are onlined. */ static int sched_domains_numa_masks_update(struct notifier_block *nfb, unsigned long action, void *hcpu) { int cpu = (long)hcpu; switch (action & ~CPU_TASKS_FROZEN) { case CPU_ONLINE: sched_domains_numa_masks_set(cpu); break; case CPU_DEAD: sched_domains_numa_masks_clear(cpu); break; default: return NOTIFY_DONE; } return NOTIFY_OK; } #else static inline void sched_init_numa(void) { } static int sched_domains_numa_masks_update(struct notifier_block *nfb, unsigned long action, void *hcpu) { return 0; } #endif /* CONFIG_NUMA */ static int __sdt_alloc(const struct cpumask *cpu_map) { struct sched_domain_topology_level *tl; int j; for_each_sd_topology(tl) { struct sd_data *sdd = &tl->data; sdd->sd = alloc_percpu(struct sched_domain *); if (!sdd->sd) return -ENOMEM; sdd->sg = alloc_percpu(struct sched_group *); if (!sdd->sg) return -ENOMEM; sdd->sgp = alloc_percpu(struct sched_group_power *); if (!sdd->sgp) return -ENOMEM; for_each_cpu(j, cpu_map) { struct sched_domain *sd; struct sched_group *sg; struct sched_group_power *sgp; sd = kzalloc_node(sizeof(struct sched_domain) + cpumask_size(), GFP_KERNEL, cpu_to_node(j)); if (!sd) return -ENOMEM; *per_cpu_ptr(sdd->sd, j) = sd; sg = kzalloc_node(sizeof(struct sched_group) + cpumask_size(), GFP_KERNEL, cpu_to_node(j)); if (!sg) return -ENOMEM; sg->next = sg; *per_cpu_ptr(sdd->sg, j) = sg; sgp = kzalloc_node(sizeof(struct sched_group_power) + cpumask_size(), GFP_KERNEL, cpu_to_node(j)); if (!sgp) return -ENOMEM; *per_cpu_ptr(sdd->sgp, j) = sgp; } } return 0; } static void __sdt_free(const struct cpumask *cpu_map) { struct sched_domain_topology_level *tl; int j; for_each_sd_topology(tl) { struct sd_data *sdd = &tl->data; for_each_cpu(j, cpu_map) { struct sched_domain *sd; if (sdd->sd) { sd = *per_cpu_ptr(sdd->sd, j); if (sd && (sd->flags & SD_OVERLAP)) free_sched_groups(sd->groups, 0); kfree(*per_cpu_ptr(sdd->sd, j)); } if (sdd->sg) kfree(*per_cpu_ptr(sdd->sg, j)); if (sdd->sgp) kfree(*per_cpu_ptr(sdd->sgp, j)); } free_percpu(sdd->sd); sdd->sd = NULL; free_percpu(sdd->sg); sdd->sg = NULL; free_percpu(sdd->sgp); sdd->sgp = NULL; } } struct sched_domain *build_sched_domain(struct sched_domain_topology_level *tl, const struct cpumask *cpu_map, struct sched_domain_attr *attr, struct sched_domain *child, int cpu) { struct sched_domain *sd = tl->init(tl, cpu); if (!sd) return child; cpumask_and(sched_domain_span(sd), cpu_map, tl->mask(cpu)); if (child) { sd->level = child->level + 1; sched_domain_level_max = max(sched_domain_level_max, sd->level); child->parent = sd; sd->child = child; } set_domain_attribute(sd, attr); return sd; } /* * Build sched domains for a given set of cpus and attach the sched domains * to the individual cpus */ static int build_sched_domains(const struct cpumask *cpu_map, struct sched_domain_attr *attr) { enum s_alloc alloc_state; struct sched_domain *sd; struct s_data d; int i, ret = -ENOMEM; alloc_state = __visit_domain_allocation_hell(&d, cpu_map); if (alloc_state != sa_rootdomain) goto error; /* Set up domains for cpus specified by the cpu_map. */ for_each_cpu(i, cpu_map) { struct sched_domain_topology_level *tl; sd = NULL; for_each_sd_topology(tl) { sd = build_sched_domain(tl, cpu_map, attr, sd, i); if (tl == sched_domain_topology) *per_cpu_ptr(d.sd, i) = sd; if (tl->flags & SDTL_OVERLAP || sched_feat(FORCE_SD_OVERLAP)) sd->flags |= SD_OVERLAP; if (cpumask_equal(cpu_map, sched_domain_span(sd))) break; } } /* Build the groups for the domains */ for_each_cpu(i, cpu_map) { for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { sd->span_weight = cpumask_weight(sched_domain_span(sd)); if (sd->flags & SD_OVERLAP) { if (build_overlap_sched_groups(sd, i)) goto error; } else { if (build_sched_groups(sd, i)) goto error; } } } /* Calculate CPU power for physical packages and nodes */ for (i = nr_cpumask_bits-1; i >= 0; i--) { if (!cpumask_test_cpu(i, cpu_map)) continue; for (sd = *per_cpu_ptr(d.sd, i); sd; sd = sd->parent) { claim_allocations(i, sd); init_sched_groups_power(i, sd); } } /* Attach the domains */ rcu_read_lock(); for_each_cpu(i, cpu_map) { sd = *per_cpu_ptr(d.sd, i); cpu_attach_domain(sd, d.rd, i); } rcu_read_unlock(); ret = 0; error: __free_domain_allocs(&d, alloc_state, cpu_map); return ret; } static cpumask_var_t *doms_cur; /* current sched domains */ static int ndoms_cur; /* number of sched domains in 'doms_cur' */ static struct sched_domain_attr *dattr_cur; /* attribues of custom domains in 'doms_cur' */ /* * Special case: If a kmalloc of a doms_cur partition (array of * cpumask) fails, then fallback to a single sched domain, * as determined by the single cpumask fallback_doms. */ static cpumask_var_t fallback_doms; /* * arch_update_cpu_topology lets virtualized architectures update the * cpu core maps. It is supposed to return 1 if the topology changed * or 0 if it stayed the same. */ int __attribute__((weak)) arch_update_cpu_topology(void) { return 0; } cpumask_var_t *alloc_sched_domains(unsigned int ndoms) { int i; cpumask_var_t *doms; doms = kmalloc(sizeof(*doms) * ndoms, GFP_KERNEL); if (!doms) return NULL; for (i = 0; i < ndoms; i++) { if (!alloc_cpumask_var(&doms[i], GFP_KERNEL)) { free_sched_domains(doms, i); return NULL; } } return doms; } void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms) { unsigned int i; for (i = 0; i < ndoms; i++) free_cpumask_var(doms[i]); kfree(doms); } /* * Set up scheduler domains and groups. Callers must hold the hotplug lock. * For now this just excludes isolated cpus, but could be used to * exclude other special cases in the future. */ static int init_sched_domains(const struct cpumask *cpu_map) { int err; arch_update_cpu_topology(); ndoms_cur = 1; doms_cur = alloc_sched_domains(ndoms_cur); if (!doms_cur) doms_cur = &fallback_doms; cpumask_andnot(doms_cur[0], cpu_map, cpu_isolated_map); err = build_sched_domains(doms_cur[0], NULL); register_sched_domain_sysctl(); return err; } /* * Detach sched domains from a group of cpus specified in cpu_map * These cpus will now be attached to the NULL domain */ static void detach_destroy_domains(const struct cpumask *cpu_map) { int i; rcu_read_lock(); for_each_cpu(i, cpu_map) cpu_attach_domain(NULL, &def_root_domain, i); rcu_read_unlock(); } /* handle null as "default" */ static int dattrs_equal(struct sched_domain_attr *cur, int idx_cur, struct sched_domain_attr *new, int idx_new) { struct sched_domain_attr tmp; /* fast path */ if (!new && !cur) return 1; tmp = SD_ATTR_INIT; return !memcmp(cur ? (cur + idx_cur) : &tmp, new ? (new + idx_new) : &tmp, sizeof(struct sched_domain_attr)); } /* * Partition sched domains as specified by the 'ndoms_new' * cpumasks in the array doms_new[] of cpumasks. This compares * doms_new[] to the current sched domain partitioning, doms_cur[]. * It destroys each deleted domain and builds each new domain. * * 'doms_new' is an array of cpumask_var_t's of length 'ndoms_new'. * The masks don't intersect (don't overlap.) We should setup one * sched domain for each mask. CPUs not in any of the cpumasks will * not be load balanced. If the same cpumask appears both in the * current 'doms_cur' domains and in the new 'doms_new', we can leave * it as it is. * * The passed in 'doms_new' should be allocated using * alloc_sched_domains. This routine takes ownership of it and will * free_sched_domains it when done with it. If the caller failed the * alloc call, then it can pass in doms_new == NULL && ndoms_new == 1, * and partition_sched_domains() will fallback to the single partition * 'fallback_doms', it also forces the domains to be rebuilt. * * If doms_new == NULL it will be replaced with cpu_online_mask. * ndoms_new == 0 is a special case for destroying existing domains, * and it will not create the default domain. * * Call with hotplug lock held */ void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[], struct sched_domain_attr *dattr_new) { int i, j, n; int new_topology; mutex_lock(&sched_domains_mutex); /* always unregister in case we don't destroy any domains */ unregister_sched_domain_sysctl(); /* Let architecture update cpu core mappings. */ new_topology = arch_update_cpu_topology(); n = doms_new ? ndoms_new : 0; /* Destroy deleted domains */ for (i = 0; i < ndoms_cur; i++) { for (j = 0; j < n && !new_topology; j++) { if (cpumask_equal(doms_cur[i], doms_new[j]) && dattrs_equal(dattr_cur, i, dattr_new, j)) goto match1; } /* no match - a current sched domain not in new doms_new[] */ detach_destroy_domains(doms_cur[i]); match1: ; } n = ndoms_cur; if (doms_new == NULL) { n = 0; doms_new = &fallback_doms; cpumask_andnot(doms_new[0], cpu_active_mask, cpu_isolated_map); WARN_ON_ONCE(dattr_new); } /* Build new domains */ for (i = 0; i < ndoms_new; i++) { for (j = 0; j < n && !new_topology; j++) { if (cpumask_equal(doms_new[i], doms_cur[j]) && dattrs_equal(dattr_new, i, dattr_cur, j)) goto match2; } /* no match - add a new doms_new */ build_sched_domains(doms_new[i], dattr_new ? dattr_new + i : NULL); match2: ; } /* Remember the new sched domains */ if (doms_cur != &fallback_doms) free_sched_domains(doms_cur, ndoms_cur); kfree(dattr_cur); /* kfree(NULL) is safe */ doms_cur = doms_new; dattr_cur = dattr_new; ndoms_cur = ndoms_new; register_sched_domain_sysctl(); mutex_unlock(&sched_domains_mutex); } static int num_cpus_frozen; /* used to mark begin/end of suspend/resume */ /* * Update cpusets according to cpu_active mask. If cpusets are * disabled, cpuset_update_active_cpus() becomes a simple wrapper * around partition_sched_domains(). * * If we come here as part of a suspend/resume, don't touch cpusets because we * want to restore it back to its original state upon resume anyway. */ static int cpuset_cpu_active(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action) { case CPU_ONLINE_FROZEN: case CPU_DOWN_FAILED_FROZEN: /* * num_cpus_frozen tracks how many CPUs are involved in suspend * resume sequence. As long as this is not the last online * operation in the resume sequence, just build a single sched * domain, ignoring cpusets. */ num_cpus_frozen--; if (likely(num_cpus_frozen)) { partition_sched_domains(1, NULL, NULL); break; } /* * This is the last CPU online operation. So fall through and * restore the original sched domains by considering the * cpuset configurations. */ case CPU_ONLINE: case CPU_DOWN_FAILED: cpuset_update_active_cpus(true); break; default: return NOTIFY_DONE; } return NOTIFY_OK; } static int cpuset_cpu_inactive(struct notifier_block *nfb, unsigned long action, void *hcpu) { switch (action) { case CPU_DOWN_PREPARE: cpuset_update_active_cpus(false); break; case CPU_DOWN_PREPARE_FROZEN: num_cpus_frozen++; partition_sched_domains(1, NULL, NULL); break; default: return NOTIFY_DONE; } return NOTIFY_OK; } void __init sched_init_smp(void) { cpumask_var_t non_isolated_cpus; alloc_cpumask_var(&non_isolated_cpus, GFP_KERNEL); alloc_cpumask_var(&fallback_doms, GFP_KERNEL); sched_init_numa(); /* * There's no userspace yet to cause hotplug operations; hence all the * cpu masks are stable and all blatant races in the below code cannot * happen. */ mutex_lock(&sched_domains_mutex); init_sched_domains(cpu_active_mask); cpumask_andnot(non_isolated_cpus, cpu_possible_mask, cpu_isolated_map); if (cpumask_empty(non_isolated_cpus)) cpumask_set_cpu(smp_processor_id(), non_isolated_cpus); mutex_unlock(&sched_domains_mutex); hotcpu_notifier(sched_domains_numa_masks_update, CPU_PRI_SCHED_ACTIVE); hotcpu_notifier(cpuset_cpu_active, CPU_PRI_CPUSET_ACTIVE); hotcpu_notifier(cpuset_cpu_inactive, CPU_PRI_CPUSET_INACTIVE); init_hrtick(); /* Move init over to a non-isolated CPU */ if (set_cpus_allowed_ptr(current, non_isolated_cpus) < 0) BUG(); sched_init_granularity(); free_cpumask_var(non_isolated_cpus); init_sched_rt_class(); init_sched_dl_class(); } #else void __init sched_init_smp(void) { sched_init_granularity(); } #endif /* CONFIG_SMP */ const_debug unsigned int sysctl_timer_migration = 1; int in_sched_functions(unsigned long addr) { return in_lock_functions(addr) || (addr >= (unsigned long)__sched_text_start && addr < (unsigned long)__sched_text_end); } #ifdef CONFIG_CGROUP_SCHED /* * Default task group. * Every task in system belongs to this group at bootup. */ struct task_group root_task_group; LIST_HEAD(task_groups); #endif DECLARE_PER_CPU(cpumask_var_t, load_balance_mask); void __init sched_init(void) { int i, j; unsigned long alloc_size = 0, ptr; #ifdef CONFIG_FAIR_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_RT_GROUP_SCHED alloc_size += 2 * nr_cpu_ids * sizeof(void **); #endif #ifdef CONFIG_CPUMASK_OFFSTACK alloc_size += num_possible_cpus() * cpumask_size(); #endif if (alloc_size) { ptr = (unsigned long)kzalloc(alloc_size, GFP_NOWAIT); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.se = (struct sched_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.cfs_rq = (struct cfs_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED root_task_group.rt_se = (struct sched_rt_entity **)ptr; ptr += nr_cpu_ids * sizeof(void **); root_task_group.rt_rq = (struct rt_rq **)ptr; ptr += nr_cpu_ids * sizeof(void **); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CPUMASK_OFFSTACK for_each_possible_cpu(i) { per_cpu(load_balance_mask, i) = (void *)ptr; ptr += cpumask_size(); } #endif /* CONFIG_CPUMASK_OFFSTACK */ } init_rt_bandwidth(&def_rt_bandwidth, global_rt_period(), global_rt_runtime()); init_dl_bandwidth(&def_dl_bandwidth, global_rt_period(), global_rt_runtime()); #ifdef CONFIG_SMP init_defrootdomain(); #endif #ifdef CONFIG_RT_GROUP_SCHED init_rt_bandwidth(&root_task_group.rt_bandwidth, global_rt_period(), global_rt_runtime()); #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_CGROUP_SCHED list_add(&root_task_group.list, &task_groups); INIT_LIST_HEAD(&root_task_group.children); INIT_LIST_HEAD(&root_task_group.siblings); autogroup_init(&init_task); #endif /* CONFIG_CGROUP_SCHED */ for_each_possible_cpu(i) { struct rq *rq; rq = cpu_rq(i); raw_spin_lock_init(&rq->lock); rq->nr_running = 0; rq->calc_load_active = 0; rq->calc_load_update = jiffies + LOAD_FREQ; init_cfs_rq(&rq->cfs); init_rt_rq(&rq->rt, rq); init_dl_rq(&rq->dl, rq); #ifdef CONFIG_FAIR_GROUP_SCHED root_task_group.shares = ROOT_TASK_GROUP_LOAD; INIT_LIST_HEAD(&rq->leaf_cfs_rq_list); /* * How much cpu bandwidth does root_task_group get? * * In case of task-groups formed thr' the cgroup filesystem, it * gets 100% of the cpu resources in the system. This overall * system cpu resource is divided among the tasks of * root_task_group and its child task-groups in a fair manner, * based on each entity's (task or task-group's) weight * (se->load.weight). * * In other words, if root_task_group has 10 tasks of weight * 1024) and two child groups A0 and A1 (of weight 1024 each), * then A0's share of the cpu resource is: * * A0's bandwidth = 1024 / (10*1024 + 1024 + 1024) = 8.33% * * We achieve this by letting root_task_group's tasks sit * directly in rq->cfs (i.e root_task_group->se[] = NULL). */ init_cfs_bandwidth(&root_task_group.cfs_bandwidth); init_tg_cfs_entry(&root_task_group, &rq->cfs, NULL, i, NULL); #endif /* CONFIG_FAIR_GROUP_SCHED */ rq->rt.rt_runtime = def_rt_bandwidth.rt_runtime; #ifdef CONFIG_RT_GROUP_SCHED INIT_LIST_HEAD(&rq->leaf_rt_rq_list); init_tg_rt_entry(&root_task_group, &rq->rt, NULL, i, NULL); #endif for (j = 0; j < CPU_LOAD_IDX_MAX; j++) rq->cpu_load[j] = 0; rq->last_load_update_tick = jiffies; #ifdef CONFIG_SMP rq->sd = NULL; rq->rd = NULL; rq->cpu_power = SCHED_POWER_SCALE; rq->post_schedule = 0; rq->active_balance = 0; rq->next_balance = jiffies; rq->push_cpu = 0; rq->cpu = i; rq->online = 0; rq->idle_stamp = 0; rq->avg_idle = 2*sysctl_sched_migration_cost; rq->max_idle_balance_cost = sysctl_sched_migration_cost; INIT_LIST_HEAD(&rq->cfs_tasks); rq_attach_root(rq, &def_root_domain); #ifdef CONFIG_NO_HZ_COMMON rq->nohz_flags = 0; #endif #ifdef CONFIG_NO_HZ_FULL rq->last_sched_tick = 0; #endif #endif init_rq_hrtick(rq); atomic_set(&rq->nr_iowait, 0); } set_load_weight(&init_task); #ifdef CONFIG_PREEMPT_NOTIFIERS INIT_HLIST_HEAD(&init_task.preempt_notifiers); #endif /* * The boot idle thread does lazy MMU switching as well: */ atomic_inc(&init_mm.mm_count); enter_lazy_tlb(&init_mm, current); /* * Make us the idle thread. Technically, schedule() should not be * called from this thread, however somewhere below it might be, * but because we are the idle thread, we just pick up running again * when this runqueue becomes "idle". */ init_idle(current, smp_processor_id()); calc_load_update = jiffies + LOAD_FREQ; /* * During early bootup we pretend to be a normal task: */ current->sched_class = &fair_sched_class; #ifdef CONFIG_SMP zalloc_cpumask_var(&sched_domains_tmpmask, GFP_NOWAIT); /* May be allocated at isolcpus cmdline parse time */ if (cpu_isolated_map == NULL) zalloc_cpumask_var(&cpu_isolated_map, GFP_NOWAIT); idle_thread_set_boot_cpu(); #endif init_sched_fair_class(); scheduler_running = 1; } #ifdef CONFIG_DEBUG_ATOMIC_SLEEP static inline int preempt_count_equals(int preempt_offset) { int nested = (preempt_count() & ~PREEMPT_ACTIVE) + rcu_preempt_depth(); return (nested == preempt_offset); } void __might_sleep(const char *file, int line, int preempt_offset) { static unsigned long prev_jiffy; /* ratelimiting */ rcu_sleep_check(); /* WARN_ON_ONCE() by default, no rate limit reqd. */ if ((preempt_count_equals(preempt_offset) && !irqs_disabled()) || system_state != SYSTEM_RUNNING || oops_in_progress) return; if (time_before(jiffies, prev_jiffy + HZ) && prev_jiffy) return; prev_jiffy = jiffies; printk(KERN_ERR "BUG: sleeping function called from invalid context at %s:%d\n", file, line); printk(KERN_ERR "in_atomic(): %d, irqs_disabled(): %d, pid: %d, name: %s\n", in_atomic(), irqs_disabled(), current->pid, current->comm); debug_show_held_locks(current); if (irqs_disabled()) print_irqtrace_events(current); dump_stack(); } EXPORT_SYMBOL(__might_sleep); #endif #ifdef CONFIG_MAGIC_SYSRQ static void normalize_task(struct rq *rq, struct task_struct *p) { const struct sched_class *prev_class = p->sched_class; struct sched_attr attr = { .sched_policy = SCHED_NORMAL, }; int old_prio = p->prio; int on_rq; on_rq = p->on_rq; if (on_rq) dequeue_task(rq, p, 0); __setscheduler(rq, p, &attr); if (on_rq) { enqueue_task(rq, p, 0); resched_task(rq->curr); } check_class_changed(rq, p, prev_class, old_prio); } void normalize_rt_tasks(void) { struct task_struct *g, *p; unsigned long flags; struct rq *rq; read_lock_irqsave(&tasklist_lock, flags); do_each_thread(g, p) { /* * Only normalize user tasks: */ if (!p->mm) continue; p->se.exec_start = 0; #ifdef CONFIG_SCHEDSTATS p->se.statistics.wait_start = 0; p->se.statistics.sleep_start = 0; p->se.statistics.block_start = 0; #endif if (!dl_task(p) && !rt_task(p)) { /* * Renice negative nice level userspace * tasks back to 0: */ if (TASK_NICE(p) < 0 && p->mm) set_user_nice(p, 0); continue; } raw_spin_lock(&p->pi_lock); rq = __task_rq_lock(p); normalize_task(rq, p); __task_rq_unlock(rq); raw_spin_unlock(&p->pi_lock); } while_each_thread(g, p); read_unlock_irqrestore(&tasklist_lock, flags); } #endif /* CONFIG_MAGIC_SYSRQ */ #if defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) /* * These functions are only useful for the IA64 MCA handling, or kdb. * * They can only be called when the whole system has been * stopped - every CPU needs to be quiescent, and no scheduling * activity can take place. Using them for anything else would * be a serious bug, and as a result, they aren't even visible * under any other configuration. */ /** * curr_task - return the current task for a given cpu. * @cpu: the processor in question. * * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! * * Return: The current task for @cpu. */ struct task_struct *curr_task(int cpu) { return cpu_curr(cpu); } #endif /* defined(CONFIG_IA64) || defined(CONFIG_KGDB_KDB) */ #ifdef CONFIG_IA64 /** * set_curr_task - set the current task for a given cpu. * @cpu: the processor in question. * @p: the task pointer to set. * * Description: This function must only be used when non-maskable interrupts * are serviced on a separate stack. It allows the architecture to switch the * notion of the current task on a cpu in a non-blocking manner. This function * must be called with all CPU's synchronized, and interrupts disabled, the * and caller must save the original value of the current task (see * curr_task() above) and restore that value before reenabling interrupts and * re-starting the system. * * ONLY VALID WHEN THE WHOLE SYSTEM IS STOPPED! */ void set_curr_task(int cpu, struct task_struct *p) { cpu_curr(cpu) = p; } #endif #ifdef CONFIG_CGROUP_SCHED /* task_group_lock serializes the addition/removal of task groups */ static DEFINE_SPINLOCK(task_group_lock); static void free_sched_group(struct task_group *tg) { free_fair_sched_group(tg); free_rt_sched_group(tg); autogroup_free(tg); kfree(tg); } /* allocate runqueue etc for a new task group */ struct task_group *sched_create_group(struct task_group *parent) { struct task_group *tg; tg = kzalloc(sizeof(*tg), GFP_KERNEL); if (!tg) return ERR_PTR(-ENOMEM); if (!alloc_fair_sched_group(tg, parent)) goto err; if (!alloc_rt_sched_group(tg, parent)) goto err; return tg; err: free_sched_group(tg); return ERR_PTR(-ENOMEM); } void sched_online_group(struct task_group *tg, struct task_group *parent) { unsigned long flags; spin_lock_irqsave(&task_group_lock, flags); list_add_rcu(&tg->list, &task_groups); WARN_ON(!parent); /* root should already exist */ tg->parent = parent; INIT_LIST_HEAD(&tg->children); list_add_rcu(&tg->siblings, &parent->children); spin_unlock_irqrestore(&task_group_lock, flags); } /* rcu callback to free various structures associated with a task group */ static void free_sched_group_rcu(struct rcu_head *rhp) { /* now it should be safe to free those cfs_rqs */ free_sched_group(container_of(rhp, struct task_group, rcu)); } /* Destroy runqueue etc associated with a task group */ void sched_destroy_group(struct task_group *tg) { /* wait for possible concurrent references to cfs_rqs complete */ call_rcu(&tg->rcu, free_sched_group_rcu); } void sched_offline_group(struct task_group *tg) { unsigned long flags; int i; /* end participation in shares distribution */ for_each_possible_cpu(i) unregister_fair_sched_group(tg, i); spin_lock_irqsave(&task_group_lock, flags); list_del_rcu(&tg->list); list_del_rcu(&tg->siblings); spin_unlock_irqrestore(&task_group_lock, flags); } /* change task's runqueue when it moves between groups. * The caller of this function should have put the task in its new group * by now. This function just updates tsk->se.cfs_rq and tsk->se.parent to * reflect its new group. */ void sched_move_task(struct task_struct *tsk) { struct task_group *tg; int on_rq, running; unsigned long flags; struct rq *rq; rq = task_rq_lock(tsk, &flags); running = task_current(rq, tsk); on_rq = tsk->on_rq; if (on_rq) dequeue_task(rq, tsk, 0); if (unlikely(running)) tsk->sched_class->put_prev_task(rq, tsk); tg = container_of(task_css_check(tsk, cpu_cgroup_subsys_id, lockdep_is_held(&tsk->sighand->siglock)), struct task_group, css); tg = autogroup_task_group(tsk, tg); tsk->sched_task_group = tg; #ifdef CONFIG_FAIR_GROUP_SCHED if (tsk->sched_class->task_move_group) tsk->sched_class->task_move_group(tsk, on_rq); else #endif set_task_rq(tsk, task_cpu(tsk)); if (unlikely(running)) tsk->sched_class->set_curr_task(rq); if (on_rq) enqueue_task(rq, tsk, 0); task_rq_unlock(rq, tsk, &flags); } #endif /* CONFIG_CGROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED /* * Ensure that the real time constraints are schedulable. */ static DEFINE_MUTEX(rt_constraints_mutex); /* Must be called with tasklist_lock held */ static inline int tg_has_rt_tasks(struct task_group *tg) { struct task_struct *g, *p; do_each_thread(g, p) { if (rt_task(p) && task_rq(p)->rt.tg == tg) return 1; } while_each_thread(g, p); return 0; } struct rt_schedulable_data { struct task_group *tg; u64 rt_period; u64 rt_runtime; }; static int tg_rt_schedulable(struct task_group *tg, void *data) { struct rt_schedulable_data *d = data; struct task_group *child; unsigned long total, sum = 0; u64 period, runtime; period = ktime_to_ns(tg->rt_bandwidth.rt_period); runtime = tg->rt_bandwidth.rt_runtime; if (tg == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } /* * Cannot have more runtime than the period. */ if (runtime > period && runtime != RUNTIME_INF) return -EINVAL; /* * Ensure we don't starve existing RT tasks. */ if (rt_bandwidth_enabled() && !runtime && tg_has_rt_tasks(tg)) return -EBUSY; total = to_ratio(period, runtime); /* * Nobody can have more than the global setting allows. */ if (total > to_ratio(global_rt_period(), global_rt_runtime())) return -EINVAL; /* * The sum of our children's runtime should not exceed our own. */ list_for_each_entry_rcu(child, &tg->children, siblings) { period = ktime_to_ns(child->rt_bandwidth.rt_period); runtime = child->rt_bandwidth.rt_runtime; if (child == d->tg) { period = d->rt_period; runtime = d->rt_runtime; } sum += to_ratio(period, runtime); } if (sum > total) return -EINVAL; return 0; } static int __rt_schedulable(struct task_group *tg, u64 period, u64 runtime) { int ret; struct rt_schedulable_data data = { .tg = tg, .rt_period = period, .rt_runtime = runtime, }; rcu_read_lock(); ret = walk_tg_tree(tg_rt_schedulable, tg_nop, &data); rcu_read_unlock(); return ret; } static int tg_set_rt_bandwidth(struct task_group *tg, u64 rt_period, u64 rt_runtime) { int i, err = 0; mutex_lock(&rt_constraints_mutex); read_lock(&tasklist_lock); err = __rt_schedulable(tg, rt_period, rt_runtime); if (err) goto unlock; raw_spin_lock_irq(&tg->rt_bandwidth.rt_runtime_lock); tg->rt_bandwidth.rt_period = ns_to_ktime(rt_period); tg->rt_bandwidth.rt_runtime = rt_runtime; for_each_possible_cpu(i) { struct rt_rq *rt_rq = tg->rt_rq[i]; raw_spin_lock(&rt_rq->rt_runtime_lock); rt_rq->rt_runtime = rt_runtime; raw_spin_unlock(&rt_rq->rt_runtime_lock); } raw_spin_unlock_irq(&tg->rt_bandwidth.rt_runtime_lock); unlock: read_unlock(&tasklist_lock); mutex_unlock(&rt_constraints_mutex); return err; } static int sched_group_set_rt_runtime(struct task_group *tg, long rt_runtime_us) { u64 rt_runtime, rt_period; rt_period = ktime_to_ns(tg->rt_bandwidth.rt_period); rt_runtime = (u64)rt_runtime_us * NSEC_PER_USEC; if (rt_runtime_us < 0) rt_runtime = RUNTIME_INF; return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); } static long sched_group_rt_runtime(struct task_group *tg) { u64 rt_runtime_us; if (tg->rt_bandwidth.rt_runtime == RUNTIME_INF) return -1; rt_runtime_us = tg->rt_bandwidth.rt_runtime; do_div(rt_runtime_us, NSEC_PER_USEC); return rt_runtime_us; } static int sched_group_set_rt_period(struct task_group *tg, long rt_period_us) { u64 rt_runtime, rt_period; rt_period = (u64)rt_period_us * NSEC_PER_USEC; rt_runtime = tg->rt_bandwidth.rt_runtime; if (rt_period == 0) return -EINVAL; return tg_set_rt_bandwidth(tg, rt_period, rt_runtime); } static long sched_group_rt_period(struct task_group *tg) { u64 rt_period_us; rt_period_us = ktime_to_ns(tg->rt_bandwidth.rt_period); do_div(rt_period_us, NSEC_PER_USEC); return rt_period_us; } #endif /* CONFIG_RT_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED static int sched_rt_global_constraints(void) { int ret = 0; mutex_lock(&rt_constraints_mutex); read_lock(&tasklist_lock); ret = __rt_schedulable(NULL, 0, 0); read_unlock(&tasklist_lock); mutex_unlock(&rt_constraints_mutex); return ret; } static int sched_rt_can_attach(struct task_group *tg, struct task_struct *tsk) { /* Don't accept realtime tasks when there is no way for them to run */ if (rt_task(tsk) && tg->rt_bandwidth.rt_runtime == 0) return 0; return 1; } #else /* !CONFIG_RT_GROUP_SCHED */ static int sched_rt_global_constraints(void) { unsigned long flags; int i, ret = 0; raw_spin_lock_irqsave(&def_rt_bandwidth.rt_runtime_lock, flags); for_each_possible_cpu(i) { struct rt_rq *rt_rq = &cpu_rq(i)->rt; raw_spin_lock(&rt_rq->rt_runtime_lock); rt_rq->rt_runtime = global_rt_runtime(); raw_spin_unlock(&rt_rq->rt_runtime_lock); } raw_spin_unlock_irqrestore(&def_rt_bandwidth.rt_runtime_lock, flags); return ret; } #endif /* CONFIG_RT_GROUP_SCHED */ static int sched_dl_global_constraints(void) { u64 runtime = global_rt_runtime(); u64 period = global_rt_period(); u64 new_bw = to_ratio(period, runtime); int cpu, ret = 0; unsigned long flags; /* * Here we want to check the bandwidth not being set to some * value smaller than the currently allocated bandwidth in * any of the root_domains. * * FIXME: Cycling on all the CPUs is overdoing, but simpler than * cycling on root_domains... Discussion on different/better * solutions is welcome! */ for_each_possible_cpu(cpu) { struct dl_bw *dl_b = dl_bw_of(cpu); raw_spin_lock_irqsave(&dl_b->lock, flags); if (new_bw < dl_b->total_bw) ret = -EBUSY; raw_spin_unlock_irqrestore(&dl_b->lock, flags); if (ret) break; } return ret; } static void sched_dl_do_global(void) { u64 new_bw = -1; int cpu; unsigned long flags; def_dl_bandwidth.dl_period = global_rt_period(); def_dl_bandwidth.dl_runtime = global_rt_runtime(); if (global_rt_runtime() != RUNTIME_INF) new_bw = to_ratio(global_rt_period(), global_rt_runtime()); /* * FIXME: As above... */ for_each_possible_cpu(cpu) { struct dl_bw *dl_b = dl_bw_of(cpu); raw_spin_lock_irqsave(&dl_b->lock, flags); dl_b->bw = new_bw; raw_spin_unlock_irqrestore(&dl_b->lock, flags); } } static int sched_rt_global_validate(void) { if (sysctl_sched_rt_period <= 0) return -EINVAL; if ((sysctl_sched_rt_runtime != RUNTIME_INF) && (sysctl_sched_rt_runtime > sysctl_sched_rt_period)) return -EINVAL; return 0; } static void sched_rt_do_global(void) { def_rt_bandwidth.rt_runtime = global_rt_runtime(); def_rt_bandwidth.rt_period = ns_to_ktime(global_rt_period()); } int sched_rt_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int old_period, old_runtime; static DEFINE_MUTEX(mutex); int ret; mutex_lock(&mutex); old_period = sysctl_sched_rt_period; old_runtime = sysctl_sched_rt_runtime; ret = proc_dointvec(table, write, buffer, lenp, ppos); if (!ret && write) { ret = sched_rt_global_validate(); if (ret) goto undo; ret = sched_rt_global_constraints(); if (ret) goto undo; ret = sched_dl_global_constraints(); if (ret) goto undo; sched_rt_do_global(); sched_dl_do_global(); } if (0) { undo: sysctl_sched_rt_period = old_period; sysctl_sched_rt_runtime = old_runtime; } mutex_unlock(&mutex); return ret; } int sched_rr_handler(struct ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int ret; static DEFINE_MUTEX(mutex); mutex_lock(&mutex); ret = proc_dointvec(table, write, buffer, lenp, ppos); /* make sure that internally we keep jiffies */ /* also, writing zero resets timeslice to default */ if (!ret && write) { sched_rr_timeslice = sched_rr_timeslice <= 0 ? RR_TIMESLICE : msecs_to_jiffies(sched_rr_timeslice); } mutex_unlock(&mutex); return ret; } #ifdef CONFIG_CGROUP_SCHED static inline struct task_group *css_tg(struct cgroup_subsys_state *css) { return css ? container_of(css, struct task_group, css) : NULL; } static struct cgroup_subsys_state * cpu_cgroup_css_alloc(struct cgroup_subsys_state *parent_css) { struct task_group *parent = css_tg(parent_css); struct task_group *tg; if (!parent) { /* This is early initialization for the top cgroup */ return &root_task_group.css; } tg = sched_create_group(parent); if (IS_ERR(tg)) return ERR_PTR(-ENOMEM); return &tg->css; } static int cpu_cgroup_css_online(struct cgroup_subsys_state *css) { struct task_group *tg = css_tg(css); struct task_group *parent = css_tg(css_parent(css)); if (parent) sched_online_group(tg, parent); return 0; } static void cpu_cgroup_css_free(struct cgroup_subsys_state *css) { struct task_group *tg = css_tg(css); sched_destroy_group(tg); } static void cpu_cgroup_css_offline(struct cgroup_subsys_state *css) { struct task_group *tg = css_tg(css); sched_offline_group(tg); } static int cpu_cgroup_can_attach(struct cgroup_subsys_state *css, struct cgroup_taskset *tset) { struct task_struct *task; cgroup_taskset_for_each(task, css, tset) { #ifdef CONFIG_RT_GROUP_SCHED if (!sched_rt_can_attach(css_tg(css), task)) return -EINVAL; #else /* We don't support RT-tasks being in separate groups */ if (task->sched_class != &fair_sched_class) return -EINVAL; #endif } return 0; } static void cpu_cgroup_attach(struct cgroup_subsys_state *css, struct cgroup_taskset *tset) { struct task_struct *task; cgroup_taskset_for_each(task, css, tset) sched_move_task(task); } static void cpu_cgroup_exit(struct cgroup_subsys_state *css, struct cgroup_subsys_state *old_css, struct task_struct *task) { /* * cgroup_exit() is called in the copy_process() failure path. * Ignore this case since the task hasn't ran yet, this avoids * trying to poke a half freed task state from generic code. */ if (!(task->flags & PF_EXITING)) return; sched_move_task(task); } #ifdef CONFIG_FAIR_GROUP_SCHED static int cpu_shares_write_u64(struct cgroup_subsys_state *css, struct cftype *cftype, u64 shareval) { return sched_group_set_shares(css_tg(css), scale_load(shareval)); } static u64 cpu_shares_read_u64(struct cgroup_subsys_state *css, struct cftype *cft) { struct task_group *tg = css_tg(css); return (u64) scale_load_down(tg->shares); } #ifdef CONFIG_CFS_BANDWIDTH static DEFINE_MUTEX(cfs_constraints_mutex); const u64 max_cfs_quota_period = 1 * NSEC_PER_SEC; /* 1s */ const u64 min_cfs_quota_period = 1 * NSEC_PER_MSEC; /* 1ms */ static int __cfs_schedulable(struct task_group *tg, u64 period, u64 runtime); static int tg_set_cfs_bandwidth(struct task_group *tg, u64 period, u64 quota) { int i, ret = 0, runtime_enabled, runtime_was_enabled; struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; if (tg == &root_task_group) return -EINVAL; /* * Ensure we have at some amount of bandwidth every period. This is * to prevent reaching a state of large arrears when throttled via * entity_tick() resulting in prolonged exit starvation. */ if (quota < min_cfs_quota_period || period < min_cfs_quota_period) return -EINVAL; /* * Likewise, bound things on the otherside by preventing insane quota * periods. This also allows us to normalize in computing quota * feasibility. */ if (period > max_cfs_quota_period) return -EINVAL; mutex_lock(&cfs_constraints_mutex); ret = __cfs_schedulable(tg, period, quota); if (ret) goto out_unlock; runtime_enabled = quota != RUNTIME_INF; runtime_was_enabled = cfs_b->quota != RUNTIME_INF; /* * If we need to toggle cfs_bandwidth_used, off->on must occur * before making related changes, and on->off must occur afterwards */ if (runtime_enabled && !runtime_was_enabled) cfs_bandwidth_usage_inc(); raw_spin_lock_irq(&cfs_b->lock); cfs_b->period = ns_to_ktime(period); cfs_b->quota = quota; __refill_cfs_bandwidth_runtime(cfs_b); /* restart the period timer (if active) to handle new period expiry */ if (runtime_enabled && cfs_b->timer_active) { /* force a reprogram */ cfs_b->timer_active = 0; __start_cfs_bandwidth(cfs_b); } raw_spin_unlock_irq(&cfs_b->lock); for_each_possible_cpu(i) { struct cfs_rq *cfs_rq = tg->cfs_rq[i]; struct rq *rq = cfs_rq->rq; raw_spin_lock_irq(&rq->lock); cfs_rq->runtime_enabled = runtime_enabled; cfs_rq->runtime_remaining = 0; if (cfs_rq->throttled) unthrottle_cfs_rq(cfs_rq); raw_spin_unlock_irq(&rq->lock); } if (runtime_was_enabled && !runtime_enabled) cfs_bandwidth_usage_dec(); out_unlock: mutex_unlock(&cfs_constraints_mutex); return ret; } int tg_set_cfs_quota(struct task_group *tg, long cfs_quota_us) { u64 quota, period; period = ktime_to_ns(tg->cfs_bandwidth.period); if (cfs_quota_us < 0) quota = RUNTIME_INF; else quota = (u64)cfs_quota_us * NSEC_PER_USEC; return tg_set_cfs_bandwidth(tg, period, quota); } long tg_get_cfs_quota(struct task_group *tg) { u64 quota_us; if (tg->cfs_bandwidth.quota == RUNTIME_INF) return -1; quota_us = tg->cfs_bandwidth.quota; do_div(quota_us, NSEC_PER_USEC); return quota_us; } int tg_set_cfs_period(struct task_group *tg, long cfs_period_us) { u64 quota, period; period = (u64)cfs_period_us * NSEC_PER_USEC; quota = tg->cfs_bandwidth.quota; return tg_set_cfs_bandwidth(tg, period, quota); } long tg_get_cfs_period(struct task_group *tg) { u64 cfs_period_us; cfs_period_us = ktime_to_ns(tg->cfs_bandwidth.period); do_div(cfs_period_us, NSEC_PER_USEC); return cfs_period_us; } static s64 cpu_cfs_quota_read_s64(struct cgroup_subsys_state *css, struct cftype *cft) { return tg_get_cfs_quota(css_tg(css)); } static int cpu_cfs_quota_write_s64(struct cgroup_subsys_state *css, struct cftype *cftype, s64 cfs_quota_us) { return tg_set_cfs_quota(css_tg(css), cfs_quota_us); } static u64 cpu_cfs_period_read_u64(struct cgroup_subsys_state *css, struct cftype *cft) { return tg_get_cfs_period(css_tg(css)); } static int cpu_cfs_period_write_u64(struct cgroup_subsys_state *css, struct cftype *cftype, u64 cfs_period_us) { return tg_set_cfs_period(css_tg(css), cfs_period_us); } struct cfs_schedulable_data { struct task_group *tg; u64 period, quota; }; /* * normalize group quota/period to be quota/max_period * note: units are usecs */ static u64 normalize_cfs_quota(struct task_group *tg, struct cfs_schedulable_data *d) { u64 quota, period; if (tg == d->tg) { period = d->period; quota = d->quota; } else { period = tg_get_cfs_period(tg); quota = tg_get_cfs_quota(tg); } /* note: these should typically be equivalent */ if (quota == RUNTIME_INF || quota == -1) return RUNTIME_INF; return to_ratio(period, quota); } static int tg_cfs_schedulable_down(struct task_group *tg, void *data) { struct cfs_schedulable_data *d = data; struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; s64 quota = 0, parent_quota = -1; if (!tg->parent) { quota = RUNTIME_INF; } else { struct cfs_bandwidth *parent_b = &tg->parent->cfs_bandwidth; quota = normalize_cfs_quota(tg, d); parent_quota = parent_b->hierarchal_quota; /* * ensure max(child_quota) <= parent_quota, inherit when no * limit is set */ if (quota == RUNTIME_INF) quota = parent_quota; else if (parent_quota != RUNTIME_INF && quota > parent_quota) return -EINVAL; } cfs_b->hierarchal_quota = quota; return 0; } static int __cfs_schedulable(struct task_group *tg, u64 period, u64 quota) { int ret; struct cfs_schedulable_data data = { .tg = tg, .period = period, .quota = quota, }; if (quota != RUNTIME_INF) { do_div(data.period, NSEC_PER_USEC); do_div(data.quota, NSEC_PER_USEC); } rcu_read_lock(); ret = walk_tg_tree(tg_cfs_schedulable_down, tg_nop, &data); rcu_read_unlock(); return ret; } static int cpu_stats_show(struct seq_file *sf, void *v) { struct task_group *tg = css_tg(seq_css(sf)); struct cfs_bandwidth *cfs_b = &tg->cfs_bandwidth; seq_printf(sf, "nr_periods %d\n", cfs_b->nr_periods); seq_printf(sf, "nr_throttled %d\n", cfs_b->nr_throttled); seq_printf(sf, "throttled_time %llu\n", cfs_b->throttled_time); return 0; } #endif /* CONFIG_CFS_BANDWIDTH */ #endif /* CONFIG_FAIR_GROUP_SCHED */ #ifdef CONFIG_RT_GROUP_SCHED static int cpu_rt_runtime_write(struct cgroup_subsys_state *css, struct cftype *cft, s64 val) { return sched_group_set_rt_runtime(css_tg(css), val); } static s64 cpu_rt_runtime_read(struct cgroup_subsys_state *css, struct cftype *cft) { return sched_group_rt_runtime(css_tg(css)); } static int cpu_rt_period_write_uint(struct cgroup_subsys_state *css, struct cftype *cftype, u64 rt_period_us) { return sched_group_set_rt_period(css_tg(css), rt_period_us); } static u64 cpu_rt_period_read_uint(struct cgroup_subsys_state *css, struct cftype *cft) { return sched_group_rt_period(css_tg(css)); } #endif /* CONFIG_RT_GROUP_SCHED */ static struct cftype cpu_files[] = { #ifdef CONFIG_FAIR_GROUP_SCHED { .name = "shares", .read_u64 = cpu_shares_read_u64, .write_u64 = cpu_shares_write_u64, }, #endif #ifdef CONFIG_CFS_BANDWIDTH { .name = "cfs_quota_us", .read_s64 = cpu_cfs_quota_read_s64, .write_s64 = cpu_cfs_quota_write_s64, }, { .name = "cfs_period_us", .read_u64 = cpu_cfs_period_read_u64, .write_u64 = cpu_cfs_period_write_u64, }, { .name = "stat", .seq_show = cpu_stats_show, }, #endif #ifdef CONFIG_RT_GROUP_SCHED { .name = "rt_runtime_us", .read_s64 = cpu_rt_runtime_read, .write_s64 = cpu_rt_runtime_write, }, { .name = "rt_period_us", .read_u64 = cpu_rt_period_read_uint, .write_u64 = cpu_rt_period_write_uint, }, #endif { } /* terminate */ }; struct cgroup_subsys cpu_cgroup_subsys = { .name = "cpu", .css_alloc = cpu_cgroup_css_alloc, .css_free = cpu_cgroup_css_free, .css_online = cpu_cgroup_css_online, .css_offline = cpu_cgroup_css_offline, .can_attach = cpu_cgroup_can_attach, .attach = cpu_cgroup_attach, .exit = cpu_cgroup_exit, .subsys_id = cpu_cgroup_subsys_id, .base_cftypes = cpu_files, .early_init = 1, }; #endif /* CONFIG_CGROUP_SCHED */ void dump_cpu_task(int cpu) { pr_info("Task dump for CPU %d:\n", cpu); sched_show_task(cpu_curr(cpu)); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2426_0
crossvul-cpp_data_good_1124_4
/* * Elliptic curve DSA * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ /* * References: * * SEC1 http://www.secg.org/index.php?action=secg,docs_secg */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_ECDSA_C) #include "mbedtls/ecdsa.h" #include "mbedtls/asn1write.h" #include <string.h> #if defined(MBEDTLS_ECDSA_DETERMINISTIC) #include "mbedtls/hmac_drbg.h" #endif /* * Derive a suitable integer for group grp from a buffer of length len * SEC1 4.1.3 step 5 aka SEC1 4.1.4 step 3 */ static int derive_mpi( const mbedtls_ecp_group *grp, mbedtls_mpi *x, const unsigned char *buf, size_t blen ) { int ret; size_t n_size = ( grp->nbits + 7 ) / 8; size_t use_size = blen > n_size ? n_size : blen; MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( x, buf, use_size ) ); if( use_size * 8 > grp->nbits ) MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( x, use_size * 8 - grp->nbits ) ); /* While at it, reduce modulo N */ if( mbedtls_mpi_cmp_mpi( x, &grp->N ) >= 0 ) MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( x, x, &grp->N ) ); cleanup: return( ret ); } #if !defined(MBEDTLS_ECDSA_SIGN_ALT) /* * Compute ECDSA signature of a hashed message (SEC1 4.1.3) * Obviously, compared to SEC1 4.1.3, we skip step 4 (hash message) */ static int ecdsa_sign_internal( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { int ret, key_tries, sign_tries, blind_tries; mbedtls_ecp_point R; mbedtls_mpi k, e, t; /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* Make sure d is in range 1..n-1 */ if( mbedtls_mpi_cmp_int( d, 1 ) < 0 || mbedtls_mpi_cmp_mpi( d, &grp->N ) >= 0 ) return( MBEDTLS_ERR_ECP_INVALID_KEY ); mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &k ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &t ); sign_tries = 0; do { /* * Steps 1-3: generate a suitable ephemeral keypair * and set r = xR mod n */ key_tries = 0; do { MBEDTLS_MPI_CHK( mbedtls_ecp_gen_privkey( grp, &k, f_rng, p_rng ) ); MBEDTLS_MPI_CHK( mbedtls_ecp_mul( grp, &R, &k, &grp->G, f_rng_blind, p_rng_blind ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( r, &R.X, &grp->N ) ); if( key_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( r, 0 ) == 0 ); /* * Step 5: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Generate a random value to blind inv_mod in next step, * avoiding a potential timing leak. * * This loop does the same job as mbedtls_ecp_gen_privkey() and it is * replaced by a call to it in the mainline. This change is not * necessary to backport the fix separating the blinding and ephemeral * key generating RNGs, therefore the original code is kept. */ blind_tries = 0; do { size_t n_size = ( grp->nbits + 7 ) / 8; MBEDTLS_MPI_CHK( mbedtls_mpi_fill_random( &t, n_size, f_rng_blind, p_rng_blind ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_shift_r( &t, 8 * n_size - grp->nbits ) ); if( ++blind_tries > 30 ) return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); } while( mbedtls_mpi_cmp_int( &t, 1 ) < 0 || mbedtls_mpi_cmp_mpi( &t, &grp->N ) >= 0 ); /* * Step 6: compute s = (e + r * d) / k = t (e + rd) / (kt) mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, r, d ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_add_mpi( &e, &e, s ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &e, &e, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &k, &k, &t ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( s, &k, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( s, s, &e ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( s, s, &grp->N ) ); if( sign_tries++ > 10 ) { ret = MBEDTLS_ERR_ECP_RANDOM_FAILED; goto cleanup; } } while( mbedtls_mpi_cmp_int( s, 0 ) == 0 ); cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &k ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &t ); return( ret ); } int mbedtls_ecdsa_sign( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { /* Use the same RNG for both blinding and ephemeral key generation */ return( ecdsa_sign_internal( grp, r, s, d, buf, blen, f_rng, p_rng, f_rng, p_rng ) ); } #endif /* MBEDTLS_ECDSA_SIGN_ALT */ #if defined(MBEDTLS_ECDSA_DETERMINISTIC) static int ecdsa_sign_det_internal( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { int ret; mbedtls_hmac_drbg_context rng_ctx; unsigned char data[2 * MBEDTLS_ECP_MAX_BYTES]; size_t grp_len = ( grp->nbits + 7 ) / 8; const mbedtls_md_info_t *md_info; mbedtls_mpi h; /* Variables for deterministic blinding fallback */ const char* blind_label = "BLINDING CONTEXT"; mbedtls_hmac_drbg_context rng_ctx_blind; if( ( md_info = mbedtls_md_info_from_type( md_alg ) ) == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); mbedtls_mpi_init( &h ); mbedtls_hmac_drbg_init( &rng_ctx ); mbedtls_hmac_drbg_init( &rng_ctx_blind ); /* Use private key and message hash (reduced) to initialize HMAC_DRBG */ MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( d, data, grp_len ) ); MBEDTLS_MPI_CHK( derive_mpi( grp, &h, buf, blen ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &h, data + grp_len, grp_len ) ); mbedtls_hmac_drbg_seed_buf( &rng_ctx, md_info, data, 2 * grp_len ); if( f_rng_blind != NULL ) ret = ecdsa_sign_internal( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, &rng_ctx, f_rng_blind, p_rng_blind ); else { /* * To avoid reusing rng_ctx and risking incorrect behavior we seed a * second HMAC-DRBG with the same seed. We also apply a label to avoid * reusing the bits of the ephemeral key for blinding and eliminate the * risk that they leak this way. */ mbedtls_hmac_drbg_seed_buf( &rng_ctx_blind, md_info, data, 2 * grp_len ); ret = mbedtls_hmac_drbg_update_ret( &rng_ctx_blind, (const unsigned char*) blind_label, strlen( blind_label ) ); if( ret != 0 ) goto cleanup; /* * Since the output of the RNGs is always the same for the same key and * message, this limits the efficiency of blinding and leaks information * through side channels. After mbedtls_ecdsa_sign_det() is removed NULL * won't be a valid value for f_rng_blind anymore. Therefore it should * be checked by the caller and this branch and check can be removed. */ ret = ecdsa_sign_internal( grp, r, s, d, buf, blen, mbedtls_hmac_drbg_random, &rng_ctx, mbedtls_hmac_drbg_random, &rng_ctx_blind ); } cleanup: mbedtls_hmac_drbg_free( &rng_ctx ); mbedtls_hmac_drbg_free( &rng_ctx_blind ); mbedtls_mpi_free( &h ); return( ret ); } /* * Deterministic signature wrappers */ int mbedtls_ecdsa_sign_det( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg ) { return( ecdsa_sign_det_internal( grp, r, s, d, buf, blen, md_alg, NULL, NULL ) ); } int mbedtls_ecdsa_sign_det_ext( mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s, const mbedtls_mpi *d, const unsigned char *buf, size_t blen, mbedtls_md_type_t md_alg, int (*f_rng_blind)(void *, unsigned char *, size_t), void *p_rng_blind ) { return( ecdsa_sign_det_internal( grp, r, s, d, buf, blen, md_alg, f_rng_blind, p_rng_blind ) ); } #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ #if !defined(MBEDTLS_ECDSA_VERIFY_ALT) /* * Verify ECDSA signature of hashed message (SEC1 4.1.4) * Obviously, compared to SEC1 4.1.3, we skip step 2 (hash message) */ int mbedtls_ecdsa_verify( mbedtls_ecp_group *grp, const unsigned char *buf, size_t blen, const mbedtls_ecp_point *Q, const mbedtls_mpi *r, const mbedtls_mpi *s) { int ret; mbedtls_mpi e, s_inv, u1, u2; mbedtls_ecp_point R; mbedtls_ecp_point_init( &R ); mbedtls_mpi_init( &e ); mbedtls_mpi_init( &s_inv ); mbedtls_mpi_init( &u1 ); mbedtls_mpi_init( &u2 ); /* Fail cleanly on curves such as Curve25519 that can't be used for ECDSA */ if( grp->N.p == NULL ) return( MBEDTLS_ERR_ECP_BAD_INPUT_DATA ); /* * Step 1: make sure r and s are in range 1..n-1 */ if( mbedtls_mpi_cmp_int( r, 1 ) < 0 || mbedtls_mpi_cmp_mpi( r, &grp->N ) >= 0 || mbedtls_mpi_cmp_int( s, 1 ) < 0 || mbedtls_mpi_cmp_mpi( s, &grp->N ) >= 0 ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } /* * Additional precaution: make sure Q is valid */ MBEDTLS_MPI_CHK( mbedtls_ecp_check_pubkey( grp, Q ) ); /* * Step 3: derive MPI from hashed message */ MBEDTLS_MPI_CHK( derive_mpi( grp, &e, buf, blen ) ); /* * Step 4: u1 = e / s mod n, u2 = r / s mod n */ MBEDTLS_MPI_CHK( mbedtls_mpi_inv_mod( &s_inv, s, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u1, &e, &s_inv ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u1, &u1, &grp->N ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &u2, r, &s_inv ) ); MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &u2, &u2, &grp->N ) ); /* * Step 5: R = u1 G + u2 Q * * Since we're not using any secret data, no need to pass a RNG to * mbedtls_ecp_mul() for countermesures. */ MBEDTLS_MPI_CHK( mbedtls_ecp_muladd( grp, &R, &u1, &grp->G, &u2, Q ) ); if( mbedtls_ecp_is_zero( &R ) ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } /* * Step 6: convert xR to an integer (no-op) * Step 7: reduce xR mod n (gives v) */ MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &R.X, &R.X, &grp->N ) ); /* * Step 8: check if v (that is, R.X) is equal to r */ if( mbedtls_mpi_cmp_mpi( &R.X, r ) != 0 ) { ret = MBEDTLS_ERR_ECP_VERIFY_FAILED; goto cleanup; } cleanup: mbedtls_ecp_point_free( &R ); mbedtls_mpi_free( &e ); mbedtls_mpi_free( &s_inv ); mbedtls_mpi_free( &u1 ); mbedtls_mpi_free( &u2 ); return( ret ); } #endif /* MBEDTLS_ECDSA_VERIFY_ALT */ /* * Convert a signature (given by context) to ASN.1 */ static int ecdsa_signature_to_asn1( const mbedtls_mpi *r, const mbedtls_mpi *s, unsigned char *sig, size_t *slen ) { int ret; unsigned char buf[MBEDTLS_ECDSA_MAX_LEN]; unsigned char *p = buf + sizeof( buf ); size_t len = 0; MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, s ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_mpi( &p, buf, r ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_len( &p, buf, len ) ); MBEDTLS_ASN1_CHK_ADD( len, mbedtls_asn1_write_tag( &p, buf, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ); memcpy( sig, p, len ); *slen = len; return( 0 ); } /* * Compute and write signature */ int mbedtls_ecdsa_write_signature( mbedtls_ecdsa_context *ctx, mbedtls_md_type_t md_alg, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret; mbedtls_mpi r, s; mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); #if defined(MBEDTLS_ECDSA_DETERMINISTIC) MBEDTLS_MPI_CHK( ecdsa_sign_det_internal( &ctx->grp, &r, &s, &ctx->d, hash, hlen, md_alg, f_rng, p_rng ) ); #else (void) md_alg; MBEDTLS_MPI_CHK( mbedtls_ecdsa_sign( &ctx->grp, &r, &s, &ctx->d, hash, hlen, f_rng, p_rng ) ); #endif /* MBEDTLS_ECDSA_DETERMINISTIC */ MBEDTLS_MPI_CHK( ecdsa_signature_to_asn1( &r, &s, sig, slen ) ); cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } #if ! defined(MBEDTLS_DEPRECATED_REMOVED) && \ defined(MBEDTLS_ECDSA_DETERMINISTIC) int mbedtls_ecdsa_write_signature_det( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, unsigned char *sig, size_t *slen, mbedtls_md_type_t md_alg ) { return( mbedtls_ecdsa_write_signature( ctx, md_alg, hash, hlen, sig, slen, NULL, NULL ) ); } #endif /* * Read and check signature */ int mbedtls_ecdsa_read_signature( mbedtls_ecdsa_context *ctx, const unsigned char *hash, size_t hlen, const unsigned char *sig, size_t slen ) { int ret; unsigned char *p = (unsigned char *) sig; const unsigned char *end = sig + slen; size_t len; mbedtls_mpi r, s; mbedtls_mpi_init( &r ); mbedtls_mpi_init( &s ); if( ( ret = mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) ) != 0 ) { ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } if( p + len != end ) { ret = MBEDTLS_ERR_ECP_BAD_INPUT_DATA + MBEDTLS_ERR_ASN1_LENGTH_MISMATCH; goto cleanup; } if( ( ret = mbedtls_asn1_get_mpi( &p, end, &r ) ) != 0 || ( ret = mbedtls_asn1_get_mpi( &p, end, &s ) ) != 0 ) { ret += MBEDTLS_ERR_ECP_BAD_INPUT_DATA; goto cleanup; } if( ( ret = mbedtls_ecdsa_verify( &ctx->grp, hash, hlen, &ctx->Q, &r, &s ) ) != 0 ) goto cleanup; /* At this point we know that the buffer starts with a valid signature. * Return 0 if the buffer just contains the signature, and a specific * error code if the valid signature is followed by more data. */ if( p != end ) ret = MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH; cleanup: mbedtls_mpi_free( &r ); mbedtls_mpi_free( &s ); return( ret ); } #if !defined(MBEDTLS_ECDSA_GENKEY_ALT) /* * Generate key pair */ int mbedtls_ecdsa_genkey( mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ) { int ret = 0; ret = mbedtls_ecp_group_load( &ctx->grp, gid ); if( ret != 0 ) return( ret ); return( mbedtls_ecp_gen_keypair( &ctx->grp, &ctx->d, &ctx->Q, f_rng, p_rng ) ); } #endif /* MBEDTLS_ECDSA_GENKEY_ALT */ /* * Set context from an mbedtls_ecp_keypair */ int mbedtls_ecdsa_from_keypair( mbedtls_ecdsa_context *ctx, const mbedtls_ecp_keypair *key ) { int ret; if( ( ret = mbedtls_ecp_group_copy( &ctx->grp, &key->grp ) ) != 0 || ( ret = mbedtls_mpi_copy( &ctx->d, &key->d ) ) != 0 || ( ret = mbedtls_ecp_copy( &ctx->Q, &key->Q ) ) != 0 ) { mbedtls_ecdsa_free( ctx ); } return( ret ); } /* * Initialize context */ void mbedtls_ecdsa_init( mbedtls_ecdsa_context *ctx ) { mbedtls_ecp_keypair_init( ctx ); } /* * Free context */ void mbedtls_ecdsa_free( mbedtls_ecdsa_context *ctx ) { mbedtls_ecp_keypair_free( ctx ); } #endif /* MBEDTLS_ECDSA_C */
./CrossVul/dataset_final_sorted/CWE-200/c/good_1124_4
crossvul-cpp_data_bad_2527_0
/* * Timers abstract layer * Copyright (c) by Jaroslav Kysela <perex@perex.cz> * * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ #include <linux/delay.h> #include <linux/init.h> #include <linux/slab.h> #include <linux/time.h> #include <linux/mutex.h> #include <linux/device.h> #include <linux/module.h> #include <linux/string.h> #include <linux/sched/signal.h> #include <sound/core.h> #include <sound/timer.h> #include <sound/control.h> #include <sound/info.h> #include <sound/minors.h> #include <sound/initval.h> #include <linux/kmod.h> /* internal flags */ #define SNDRV_TIMER_IFLG_PAUSED 0x00010000 #if IS_ENABLED(CONFIG_SND_HRTIMER) #define DEFAULT_TIMER_LIMIT 4 #else #define DEFAULT_TIMER_LIMIT 1 #endif static int timer_limit = DEFAULT_TIMER_LIMIT; static int timer_tstamp_monotonic = 1; MODULE_AUTHOR("Jaroslav Kysela <perex@perex.cz>, Takashi Iwai <tiwai@suse.de>"); MODULE_DESCRIPTION("ALSA timer interface"); MODULE_LICENSE("GPL"); module_param(timer_limit, int, 0444); MODULE_PARM_DESC(timer_limit, "Maximum global timers in system."); module_param(timer_tstamp_monotonic, int, 0444); MODULE_PARM_DESC(timer_tstamp_monotonic, "Use posix monotonic clock source for timestamps (default)."); MODULE_ALIAS_CHARDEV(CONFIG_SND_MAJOR, SNDRV_MINOR_TIMER); MODULE_ALIAS("devname:snd/timer"); struct snd_timer_user { struct snd_timer_instance *timeri; int tread; /* enhanced read with timestamps and events */ unsigned long ticks; unsigned long overrun; int qhead; int qtail; int qused; int queue_size; bool disconnected; struct snd_timer_read *queue; struct snd_timer_tread *tqueue; spinlock_t qlock; unsigned long last_resolution; unsigned int filter; struct timespec tstamp; /* trigger tstamp */ wait_queue_head_t qchange_sleep; struct fasync_struct *fasync; struct mutex ioctl_lock; }; /* list of timers */ static LIST_HEAD(snd_timer_list); /* list of slave instances */ static LIST_HEAD(snd_timer_slave_list); /* lock for slave active lists */ static DEFINE_SPINLOCK(slave_active_lock); static DEFINE_MUTEX(register_mutex); static int snd_timer_free(struct snd_timer *timer); static int snd_timer_dev_free(struct snd_device *device); static int snd_timer_dev_register(struct snd_device *device); static int snd_timer_dev_disconnect(struct snd_device *device); static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left); /* * create a timer instance with the given owner string. * when timer is not NULL, increments the module counter */ static struct snd_timer_instance *snd_timer_instance_new(char *owner, struct snd_timer *timer) { struct snd_timer_instance *timeri; timeri = kzalloc(sizeof(*timeri), GFP_KERNEL); if (timeri == NULL) return NULL; timeri->owner = kstrdup(owner, GFP_KERNEL); if (! timeri->owner) { kfree(timeri); return NULL; } INIT_LIST_HEAD(&timeri->open_list); INIT_LIST_HEAD(&timeri->active_list); INIT_LIST_HEAD(&timeri->ack_list); INIT_LIST_HEAD(&timeri->slave_list_head); INIT_LIST_HEAD(&timeri->slave_active_head); timeri->timer = timer; if (timer && !try_module_get(timer->module)) { kfree(timeri->owner); kfree(timeri); return NULL; } return timeri; } /* * find a timer instance from the given timer id */ static struct snd_timer *snd_timer_find(struct snd_timer_id *tid) { struct snd_timer *timer = NULL; list_for_each_entry(timer, &snd_timer_list, device_list) { if (timer->tmr_class != tid->dev_class) continue; if ((timer->tmr_class == SNDRV_TIMER_CLASS_CARD || timer->tmr_class == SNDRV_TIMER_CLASS_PCM) && (timer->card == NULL || timer->card->number != tid->card)) continue; if (timer->tmr_device != tid->device) continue; if (timer->tmr_subdevice != tid->subdevice) continue; return timer; } return NULL; } #ifdef CONFIG_MODULES static void snd_timer_request(struct snd_timer_id *tid) { switch (tid->dev_class) { case SNDRV_TIMER_CLASS_GLOBAL: if (tid->device < timer_limit) request_module("snd-timer-%i", tid->device); break; case SNDRV_TIMER_CLASS_CARD: case SNDRV_TIMER_CLASS_PCM: if (tid->card < snd_ecards_limit) request_module("snd-card-%i", tid->card); break; default: break; } } #endif /* * look for a master instance matching with the slave id of the given slave. * when found, relink the open_link of the slave. * * call this with register_mutex down. */ static void snd_timer_check_slave(struct snd_timer_instance *slave) { struct snd_timer *timer; struct snd_timer_instance *master; /* FIXME: it's really dumb to look up all entries.. */ list_for_each_entry(timer, &snd_timer_list, device_list) { list_for_each_entry(master, &timer->open_list_head, open_list) { if (slave->slave_class == master->slave_class && slave->slave_id == master->slave_id) { list_move_tail(&slave->open_list, &master->slave_list_head); spin_lock_irq(&slave_active_lock); slave->master = master; slave->timer = master->timer; spin_unlock_irq(&slave_active_lock); return; } } } } /* * look for slave instances matching with the slave id of the given master. * when found, relink the open_link of slaves. * * call this with register_mutex down. */ static void snd_timer_check_master(struct snd_timer_instance *master) { struct snd_timer_instance *slave, *tmp; /* check all pending slaves */ list_for_each_entry_safe(slave, tmp, &snd_timer_slave_list, open_list) { if (slave->slave_class == master->slave_class && slave->slave_id == master->slave_id) { list_move_tail(&slave->open_list, &master->slave_list_head); spin_lock_irq(&slave_active_lock); spin_lock(&master->timer->lock); slave->master = master; slave->timer = master->timer; if (slave->flags & SNDRV_TIMER_IFLG_RUNNING) list_add_tail(&slave->active_list, &master->slave_active_head); spin_unlock(&master->timer->lock); spin_unlock_irq(&slave_active_lock); } } } /* * open a timer instance * when opening a master, the slave id must be here given. */ int snd_timer_open(struct snd_timer_instance **ti, char *owner, struct snd_timer_id *tid, unsigned int slave_id) { struct snd_timer *timer; struct snd_timer_instance *timeri = NULL; if (tid->dev_class == SNDRV_TIMER_CLASS_SLAVE) { /* open a slave instance */ if (tid->dev_sclass <= SNDRV_TIMER_SCLASS_NONE || tid->dev_sclass > SNDRV_TIMER_SCLASS_OSS_SEQUENCER) { pr_debug("ALSA: timer: invalid slave class %i\n", tid->dev_sclass); return -EINVAL; } mutex_lock(&register_mutex); timeri = snd_timer_instance_new(owner, NULL); if (!timeri) { mutex_unlock(&register_mutex); return -ENOMEM; } timeri->slave_class = tid->dev_sclass; timeri->slave_id = tid->device; timeri->flags |= SNDRV_TIMER_IFLG_SLAVE; list_add_tail(&timeri->open_list, &snd_timer_slave_list); snd_timer_check_slave(timeri); mutex_unlock(&register_mutex); *ti = timeri; return 0; } /* open a master instance */ mutex_lock(&register_mutex); timer = snd_timer_find(tid); #ifdef CONFIG_MODULES if (!timer) { mutex_unlock(&register_mutex); snd_timer_request(tid); mutex_lock(&register_mutex); timer = snd_timer_find(tid); } #endif if (!timer) { mutex_unlock(&register_mutex); return -ENODEV; } if (!list_empty(&timer->open_list_head)) { timeri = list_entry(timer->open_list_head.next, struct snd_timer_instance, open_list); if (timeri->flags & SNDRV_TIMER_IFLG_EXCLUSIVE) { mutex_unlock(&register_mutex); return -EBUSY; } } timeri = snd_timer_instance_new(owner, timer); if (!timeri) { mutex_unlock(&register_mutex); return -ENOMEM; } /* take a card refcount for safe disconnection */ if (timer->card) get_device(&timer->card->card_dev); timeri->slave_class = tid->dev_sclass; timeri->slave_id = slave_id; if (list_empty(&timer->open_list_head) && timer->hw.open) { int err = timer->hw.open(timer); if (err) { kfree(timeri->owner); kfree(timeri); if (timer->card) put_device(&timer->card->card_dev); module_put(timer->module); mutex_unlock(&register_mutex); return err; } } list_add_tail(&timeri->open_list, &timer->open_list_head); snd_timer_check_master(timeri); mutex_unlock(&register_mutex); *ti = timeri; return 0; } /* * close a timer instance */ int snd_timer_close(struct snd_timer_instance *timeri) { struct snd_timer *timer = NULL; struct snd_timer_instance *slave, *tmp; if (snd_BUG_ON(!timeri)) return -ENXIO; mutex_lock(&register_mutex); list_del(&timeri->open_list); /* force to stop the timer */ snd_timer_stop(timeri); timer = timeri->timer; if (timer) { /* wait, until the active callback is finished */ spin_lock_irq(&timer->lock); while (timeri->flags & SNDRV_TIMER_IFLG_CALLBACK) { spin_unlock_irq(&timer->lock); udelay(10); spin_lock_irq(&timer->lock); } spin_unlock_irq(&timer->lock); /* remove slave links */ spin_lock_irq(&slave_active_lock); spin_lock(&timer->lock); list_for_each_entry_safe(slave, tmp, &timeri->slave_list_head, open_list) { list_move_tail(&slave->open_list, &snd_timer_slave_list); slave->master = NULL; slave->timer = NULL; list_del_init(&slave->ack_list); list_del_init(&slave->active_list); } spin_unlock(&timer->lock); spin_unlock_irq(&slave_active_lock); /* slave doesn't need to release timer resources below */ if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) timer = NULL; } if (timeri->private_free) timeri->private_free(timeri); kfree(timeri->owner); kfree(timeri); if (timer) { if (list_empty(&timer->open_list_head) && timer->hw.close) timer->hw.close(timer); /* release a card refcount for safe disconnection */ if (timer->card) put_device(&timer->card->card_dev); module_put(timer->module); } mutex_unlock(&register_mutex); return 0; } unsigned long snd_timer_resolution(struct snd_timer_instance *timeri) { struct snd_timer * timer; if (timeri == NULL) return 0; if ((timer = timeri->timer) != NULL) { if (timer->hw.c_resolution) return timer->hw.c_resolution(timer); return timer->hw.resolution; } return 0; } static void snd_timer_notify1(struct snd_timer_instance *ti, int event) { struct snd_timer *timer; unsigned long resolution = 0; struct snd_timer_instance *ts; struct timespec tstamp; if (timer_tstamp_monotonic) ktime_get_ts(&tstamp); else getnstimeofday(&tstamp); if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_START || event > SNDRV_TIMER_EVENT_PAUSE)) return; if (event == SNDRV_TIMER_EVENT_START || event == SNDRV_TIMER_EVENT_CONTINUE) resolution = snd_timer_resolution(ti); if (ti->ccallback) ti->ccallback(ti, event, &tstamp, resolution); if (ti->flags & SNDRV_TIMER_IFLG_SLAVE) return; timer = ti->timer; if (timer == NULL) return; if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE) return; list_for_each_entry(ts, &ti->slave_active_head, active_list) if (ts->ccallback) ts->ccallback(ts, event + 100, &tstamp, resolution); } /* start/continue a master timer */ static int snd_timer_start1(struct snd_timer_instance *timeri, bool start, unsigned long ticks) { struct snd_timer *timer; int result; unsigned long flags; timer = timeri->timer; if (!timer) return -EINVAL; spin_lock_irqsave(&timer->lock, flags); if (timer->card && timer->card->shutdown) { result = -ENODEV; goto unlock; } if (timeri->flags & (SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START)) { result = -EBUSY; goto unlock; } if (start) timeri->ticks = timeri->cticks = ticks; else if (!timeri->cticks) timeri->cticks = 1; timeri->pticks = 0; list_move_tail(&timeri->active_list, &timer->active_list_head); if (timer->running) { if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE) goto __start_now; timer->flags |= SNDRV_TIMER_FLG_RESCHED; timeri->flags |= SNDRV_TIMER_IFLG_START; result = 1; /* delayed start */ } else { if (start) timer->sticks = ticks; timer->hw.start(timer); __start_now: timer->running++; timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; result = 0; } snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START : SNDRV_TIMER_EVENT_CONTINUE); unlock: spin_unlock_irqrestore(&timer->lock, flags); return result; } /* start/continue a slave timer */ static int snd_timer_start_slave(struct snd_timer_instance *timeri, bool start) { unsigned long flags; spin_lock_irqsave(&slave_active_lock, flags); if (timeri->flags & SNDRV_TIMER_IFLG_RUNNING) { spin_unlock_irqrestore(&slave_active_lock, flags); return -EBUSY; } timeri->flags |= SNDRV_TIMER_IFLG_RUNNING; if (timeri->master && timeri->timer) { spin_lock(&timeri->timer->lock); list_add_tail(&timeri->active_list, &timeri->master->slave_active_head); snd_timer_notify1(timeri, start ? SNDRV_TIMER_EVENT_START : SNDRV_TIMER_EVENT_CONTINUE); spin_unlock(&timeri->timer->lock); } spin_unlock_irqrestore(&slave_active_lock, flags); return 1; /* delayed start */ } /* stop/pause a master timer */ static int snd_timer_stop1(struct snd_timer_instance *timeri, bool stop) { struct snd_timer *timer; int result = 0; unsigned long flags; timer = timeri->timer; if (!timer) return -EINVAL; spin_lock_irqsave(&timer->lock, flags); if (!(timeri->flags & (SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START))) { result = -EBUSY; goto unlock; } list_del_init(&timeri->ack_list); list_del_init(&timeri->active_list); if (timer->card && timer->card->shutdown) goto unlock; if (stop) { timeri->cticks = timeri->ticks; timeri->pticks = 0; } if ((timeri->flags & SNDRV_TIMER_IFLG_RUNNING) && !(--timer->running)) { timer->hw.stop(timer); if (timer->flags & SNDRV_TIMER_FLG_RESCHED) { timer->flags &= ~SNDRV_TIMER_FLG_RESCHED; snd_timer_reschedule(timer, 0); if (timer->flags & SNDRV_TIMER_FLG_CHANGE) { timer->flags &= ~SNDRV_TIMER_FLG_CHANGE; timer->hw.start(timer); } } } timeri->flags &= ~(SNDRV_TIMER_IFLG_RUNNING | SNDRV_TIMER_IFLG_START); if (stop) timeri->flags &= ~SNDRV_TIMER_IFLG_PAUSED; else timeri->flags |= SNDRV_TIMER_IFLG_PAUSED; snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP : SNDRV_TIMER_EVENT_CONTINUE); unlock: spin_unlock_irqrestore(&timer->lock, flags); return result; } /* stop/pause a slave timer */ static int snd_timer_stop_slave(struct snd_timer_instance *timeri, bool stop) { unsigned long flags; spin_lock_irqsave(&slave_active_lock, flags); if (!(timeri->flags & SNDRV_TIMER_IFLG_RUNNING)) { spin_unlock_irqrestore(&slave_active_lock, flags); return -EBUSY; } timeri->flags &= ~SNDRV_TIMER_IFLG_RUNNING; if (timeri->timer) { spin_lock(&timeri->timer->lock); list_del_init(&timeri->ack_list); list_del_init(&timeri->active_list); snd_timer_notify1(timeri, stop ? SNDRV_TIMER_EVENT_STOP : SNDRV_TIMER_EVENT_CONTINUE); spin_unlock(&timeri->timer->lock); } spin_unlock_irqrestore(&slave_active_lock, flags); return 0; } /* * start the timer instance */ int snd_timer_start(struct snd_timer_instance *timeri, unsigned int ticks) { if (timeri == NULL || ticks < 1) return -EINVAL; if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) return snd_timer_start_slave(timeri, true); else return snd_timer_start1(timeri, true, ticks); } /* * stop the timer instance. * * do not call this from the timer callback! */ int snd_timer_stop(struct snd_timer_instance *timeri) { if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) return snd_timer_stop_slave(timeri, true); else return snd_timer_stop1(timeri, true); } /* * start again.. the tick is kept. */ int snd_timer_continue(struct snd_timer_instance *timeri) { /* timer can continue only after pause */ if (!(timeri->flags & SNDRV_TIMER_IFLG_PAUSED)) return -EINVAL; if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) return snd_timer_start_slave(timeri, false); else return snd_timer_start1(timeri, false, 0); } /* * pause.. remember the ticks left */ int snd_timer_pause(struct snd_timer_instance * timeri) { if (timeri->flags & SNDRV_TIMER_IFLG_SLAVE) return snd_timer_stop_slave(timeri, false); else return snd_timer_stop1(timeri, false); } /* * reschedule the timer * * start pending instances and check the scheduling ticks. * when the scheduling ticks is changed set CHANGE flag to reprogram the timer. */ static void snd_timer_reschedule(struct snd_timer * timer, unsigned long ticks_left) { struct snd_timer_instance *ti; unsigned long ticks = ~0UL; list_for_each_entry(ti, &timer->active_list_head, active_list) { if (ti->flags & SNDRV_TIMER_IFLG_START) { ti->flags &= ~SNDRV_TIMER_IFLG_START; ti->flags |= SNDRV_TIMER_IFLG_RUNNING; timer->running++; } if (ti->flags & SNDRV_TIMER_IFLG_RUNNING) { if (ticks > ti->cticks) ticks = ti->cticks; } } if (ticks == ~0UL) { timer->flags &= ~SNDRV_TIMER_FLG_RESCHED; return; } if (ticks > timer->hw.ticks) ticks = timer->hw.ticks; if (ticks_left != ticks) timer->flags |= SNDRV_TIMER_FLG_CHANGE; timer->sticks = ticks; } /* * timer tasklet * */ static void snd_timer_tasklet(unsigned long arg) { struct snd_timer *timer = (struct snd_timer *) arg; struct snd_timer_instance *ti; struct list_head *p; unsigned long resolution, ticks; unsigned long flags; if (timer->card && timer->card->shutdown) return; spin_lock_irqsave(&timer->lock, flags); /* now process all callbacks */ while (!list_empty(&timer->sack_list_head)) { p = timer->sack_list_head.next; /* get first item */ ti = list_entry(p, struct snd_timer_instance, ack_list); /* remove from ack_list and make empty */ list_del_init(p); ticks = ti->pticks; ti->pticks = 0; resolution = ti->resolution; ti->flags |= SNDRV_TIMER_IFLG_CALLBACK; spin_unlock(&timer->lock); if (ti->callback) ti->callback(ti, resolution, ticks); spin_lock(&timer->lock); ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK; } spin_unlock_irqrestore(&timer->lock, flags); } /* * timer interrupt * * ticks_left is usually equal to timer->sticks. * */ void snd_timer_interrupt(struct snd_timer * timer, unsigned long ticks_left) { struct snd_timer_instance *ti, *ts, *tmp; unsigned long resolution, ticks; struct list_head *p, *ack_list_head; unsigned long flags; int use_tasklet = 0; if (timer == NULL) return; if (timer->card && timer->card->shutdown) return; spin_lock_irqsave(&timer->lock, flags); /* remember the current resolution */ if (timer->hw.c_resolution) resolution = timer->hw.c_resolution(timer); else resolution = timer->hw.resolution; /* loop for all active instances * Here we cannot use list_for_each_entry because the active_list of a * processed instance is relinked to done_list_head before the callback * is called. */ list_for_each_entry_safe(ti, tmp, &timer->active_list_head, active_list) { if (!(ti->flags & SNDRV_TIMER_IFLG_RUNNING)) continue; ti->pticks += ticks_left; ti->resolution = resolution; if (ti->cticks < ticks_left) ti->cticks = 0; else ti->cticks -= ticks_left; if (ti->cticks) /* not expired */ continue; if (ti->flags & SNDRV_TIMER_IFLG_AUTO) { ti->cticks = ti->ticks; } else { ti->flags &= ~SNDRV_TIMER_IFLG_RUNNING; --timer->running; list_del_init(&ti->active_list); } if ((timer->hw.flags & SNDRV_TIMER_HW_TASKLET) || (ti->flags & SNDRV_TIMER_IFLG_FAST)) ack_list_head = &timer->ack_list_head; else ack_list_head = &timer->sack_list_head; if (list_empty(&ti->ack_list)) list_add_tail(&ti->ack_list, ack_list_head); list_for_each_entry(ts, &ti->slave_active_head, active_list) { ts->pticks = ti->pticks; ts->resolution = resolution; if (list_empty(&ts->ack_list)) list_add_tail(&ts->ack_list, ack_list_head); } } if (timer->flags & SNDRV_TIMER_FLG_RESCHED) snd_timer_reschedule(timer, timer->sticks); if (timer->running) { if (timer->hw.flags & SNDRV_TIMER_HW_STOP) { timer->hw.stop(timer); timer->flags |= SNDRV_TIMER_FLG_CHANGE; } if (!(timer->hw.flags & SNDRV_TIMER_HW_AUTO) || (timer->flags & SNDRV_TIMER_FLG_CHANGE)) { /* restart timer */ timer->flags &= ~SNDRV_TIMER_FLG_CHANGE; timer->hw.start(timer); } } else { timer->hw.stop(timer); } /* now process all fast callbacks */ while (!list_empty(&timer->ack_list_head)) { p = timer->ack_list_head.next; /* get first item */ ti = list_entry(p, struct snd_timer_instance, ack_list); /* remove from ack_list and make empty */ list_del_init(p); ticks = ti->pticks; ti->pticks = 0; ti->flags |= SNDRV_TIMER_IFLG_CALLBACK; spin_unlock(&timer->lock); if (ti->callback) ti->callback(ti, resolution, ticks); spin_lock(&timer->lock); ti->flags &= ~SNDRV_TIMER_IFLG_CALLBACK; } /* do we have any slow callbacks? */ use_tasklet = !list_empty(&timer->sack_list_head); spin_unlock_irqrestore(&timer->lock, flags); if (use_tasklet) tasklet_schedule(&timer->task_queue); } /* */ int snd_timer_new(struct snd_card *card, char *id, struct snd_timer_id *tid, struct snd_timer **rtimer) { struct snd_timer *timer; int err; static struct snd_device_ops ops = { .dev_free = snd_timer_dev_free, .dev_register = snd_timer_dev_register, .dev_disconnect = snd_timer_dev_disconnect, }; if (snd_BUG_ON(!tid)) return -EINVAL; if (rtimer) *rtimer = NULL; timer = kzalloc(sizeof(*timer), GFP_KERNEL); if (!timer) return -ENOMEM; timer->tmr_class = tid->dev_class; timer->card = card; timer->tmr_device = tid->device; timer->tmr_subdevice = tid->subdevice; if (id) strlcpy(timer->id, id, sizeof(timer->id)); timer->sticks = 1; INIT_LIST_HEAD(&timer->device_list); INIT_LIST_HEAD(&timer->open_list_head); INIT_LIST_HEAD(&timer->active_list_head); INIT_LIST_HEAD(&timer->ack_list_head); INIT_LIST_HEAD(&timer->sack_list_head); spin_lock_init(&timer->lock); tasklet_init(&timer->task_queue, snd_timer_tasklet, (unsigned long)timer); if (card != NULL) { timer->module = card->module; err = snd_device_new(card, SNDRV_DEV_TIMER, timer, &ops); if (err < 0) { snd_timer_free(timer); return err; } } if (rtimer) *rtimer = timer; return 0; } static int snd_timer_free(struct snd_timer *timer) { if (!timer) return 0; mutex_lock(&register_mutex); if (! list_empty(&timer->open_list_head)) { struct list_head *p, *n; struct snd_timer_instance *ti; pr_warn("ALSA: timer %p is busy?\n", timer); list_for_each_safe(p, n, &timer->open_list_head) { list_del_init(p); ti = list_entry(p, struct snd_timer_instance, open_list); ti->timer = NULL; } } list_del(&timer->device_list); mutex_unlock(&register_mutex); if (timer->private_free) timer->private_free(timer); kfree(timer); return 0; } static int snd_timer_dev_free(struct snd_device *device) { struct snd_timer *timer = device->device_data; return snd_timer_free(timer); } static int snd_timer_dev_register(struct snd_device *dev) { struct snd_timer *timer = dev->device_data; struct snd_timer *timer1; if (snd_BUG_ON(!timer || !timer->hw.start || !timer->hw.stop)) return -ENXIO; if (!(timer->hw.flags & SNDRV_TIMER_HW_SLAVE) && !timer->hw.resolution && timer->hw.c_resolution == NULL) return -EINVAL; mutex_lock(&register_mutex); list_for_each_entry(timer1, &snd_timer_list, device_list) { if (timer1->tmr_class > timer->tmr_class) break; if (timer1->tmr_class < timer->tmr_class) continue; if (timer1->card && timer->card) { if (timer1->card->number > timer->card->number) break; if (timer1->card->number < timer->card->number) continue; } if (timer1->tmr_device > timer->tmr_device) break; if (timer1->tmr_device < timer->tmr_device) continue; if (timer1->tmr_subdevice > timer->tmr_subdevice) break; if (timer1->tmr_subdevice < timer->tmr_subdevice) continue; /* conflicts.. */ mutex_unlock(&register_mutex); return -EBUSY; } list_add_tail(&timer->device_list, &timer1->device_list); mutex_unlock(&register_mutex); return 0; } static int snd_timer_dev_disconnect(struct snd_device *device) { struct snd_timer *timer = device->device_data; struct snd_timer_instance *ti; mutex_lock(&register_mutex); list_del_init(&timer->device_list); /* wake up pending sleepers */ list_for_each_entry(ti, &timer->open_list_head, open_list) { if (ti->disconnect) ti->disconnect(ti); } mutex_unlock(&register_mutex); return 0; } void snd_timer_notify(struct snd_timer *timer, int event, struct timespec *tstamp) { unsigned long flags; unsigned long resolution = 0; struct snd_timer_instance *ti, *ts; if (timer->card && timer->card->shutdown) return; if (! (timer->hw.flags & SNDRV_TIMER_HW_SLAVE)) return; if (snd_BUG_ON(event < SNDRV_TIMER_EVENT_MSTART || event > SNDRV_TIMER_EVENT_MRESUME)) return; spin_lock_irqsave(&timer->lock, flags); if (event == SNDRV_TIMER_EVENT_MSTART || event == SNDRV_TIMER_EVENT_MCONTINUE || event == SNDRV_TIMER_EVENT_MRESUME) { if (timer->hw.c_resolution) resolution = timer->hw.c_resolution(timer); else resolution = timer->hw.resolution; } list_for_each_entry(ti, &timer->active_list_head, active_list) { if (ti->ccallback) ti->ccallback(ti, event, tstamp, resolution); list_for_each_entry(ts, &ti->slave_active_head, active_list) if (ts->ccallback) ts->ccallback(ts, event, tstamp, resolution); } spin_unlock_irqrestore(&timer->lock, flags); } /* * exported functions for global timers */ int snd_timer_global_new(char *id, int device, struct snd_timer **rtimer) { struct snd_timer_id tid; tid.dev_class = SNDRV_TIMER_CLASS_GLOBAL; tid.dev_sclass = SNDRV_TIMER_SCLASS_NONE; tid.card = -1; tid.device = device; tid.subdevice = 0; return snd_timer_new(NULL, id, &tid, rtimer); } int snd_timer_global_free(struct snd_timer *timer) { return snd_timer_free(timer); } int snd_timer_global_register(struct snd_timer *timer) { struct snd_device dev; memset(&dev, 0, sizeof(dev)); dev.device_data = timer; return snd_timer_dev_register(&dev); } /* * System timer */ struct snd_timer_system_private { struct timer_list tlist; unsigned long last_expires; unsigned long last_jiffies; unsigned long correction; }; static void snd_timer_s_function(unsigned long data) { struct snd_timer *timer = (struct snd_timer *)data; struct snd_timer_system_private *priv = timer->private_data; unsigned long jiff = jiffies; if (time_after(jiff, priv->last_expires)) priv->correction += (long)jiff - (long)priv->last_expires; snd_timer_interrupt(timer, (long)jiff - (long)priv->last_jiffies); } static int snd_timer_s_start(struct snd_timer * timer) { struct snd_timer_system_private *priv; unsigned long njiff; priv = (struct snd_timer_system_private *) timer->private_data; njiff = (priv->last_jiffies = jiffies); if (priv->correction > timer->sticks - 1) { priv->correction -= timer->sticks - 1; njiff++; } else { njiff += timer->sticks - priv->correction; priv->correction = 0; } priv->last_expires = njiff; mod_timer(&priv->tlist, njiff); return 0; } static int snd_timer_s_stop(struct snd_timer * timer) { struct snd_timer_system_private *priv; unsigned long jiff; priv = (struct snd_timer_system_private *) timer->private_data; del_timer(&priv->tlist); jiff = jiffies; if (time_before(jiff, priv->last_expires)) timer->sticks = priv->last_expires - jiff; else timer->sticks = 1; priv->correction = 0; return 0; } static int snd_timer_s_close(struct snd_timer *timer) { struct snd_timer_system_private *priv; priv = (struct snd_timer_system_private *)timer->private_data; del_timer_sync(&priv->tlist); return 0; } static struct snd_timer_hardware snd_timer_system = { .flags = SNDRV_TIMER_HW_FIRST | SNDRV_TIMER_HW_TASKLET, .resolution = 1000000000L / HZ, .ticks = 10000000L, .close = snd_timer_s_close, .start = snd_timer_s_start, .stop = snd_timer_s_stop }; static void snd_timer_free_system(struct snd_timer *timer) { kfree(timer->private_data); } static int snd_timer_register_system(void) { struct snd_timer *timer; struct snd_timer_system_private *priv; int err; err = snd_timer_global_new("system", SNDRV_TIMER_GLOBAL_SYSTEM, &timer); if (err < 0) return err; strcpy(timer->name, "system timer"); timer->hw = snd_timer_system; priv = kzalloc(sizeof(*priv), GFP_KERNEL); if (priv == NULL) { snd_timer_free(timer); return -ENOMEM; } setup_timer(&priv->tlist, snd_timer_s_function, (unsigned long) timer); timer->private_data = priv; timer->private_free = snd_timer_free_system; return snd_timer_global_register(timer); } #ifdef CONFIG_SND_PROC_FS /* * Info interface */ static void snd_timer_proc_read(struct snd_info_entry *entry, struct snd_info_buffer *buffer) { struct snd_timer *timer; struct snd_timer_instance *ti; mutex_lock(&register_mutex); list_for_each_entry(timer, &snd_timer_list, device_list) { if (timer->card && timer->card->shutdown) continue; switch (timer->tmr_class) { case SNDRV_TIMER_CLASS_GLOBAL: snd_iprintf(buffer, "G%i: ", timer->tmr_device); break; case SNDRV_TIMER_CLASS_CARD: snd_iprintf(buffer, "C%i-%i: ", timer->card->number, timer->tmr_device); break; case SNDRV_TIMER_CLASS_PCM: snd_iprintf(buffer, "P%i-%i-%i: ", timer->card->number, timer->tmr_device, timer->tmr_subdevice); break; default: snd_iprintf(buffer, "?%i-%i-%i-%i: ", timer->tmr_class, timer->card ? timer->card->number : -1, timer->tmr_device, timer->tmr_subdevice); } snd_iprintf(buffer, "%s :", timer->name); if (timer->hw.resolution) snd_iprintf(buffer, " %lu.%03luus (%lu ticks)", timer->hw.resolution / 1000, timer->hw.resolution % 1000, timer->hw.ticks); if (timer->hw.flags & SNDRV_TIMER_HW_SLAVE) snd_iprintf(buffer, " SLAVE"); snd_iprintf(buffer, "\n"); list_for_each_entry(ti, &timer->open_list_head, open_list) snd_iprintf(buffer, " Client %s : %s\n", ti->owner ? ti->owner : "unknown", ti->flags & (SNDRV_TIMER_IFLG_START | SNDRV_TIMER_IFLG_RUNNING) ? "running" : "stopped"); } mutex_unlock(&register_mutex); } static struct snd_info_entry *snd_timer_proc_entry; static void __init snd_timer_proc_init(void) { struct snd_info_entry *entry; entry = snd_info_create_module_entry(THIS_MODULE, "timers", NULL); if (entry != NULL) { entry->c.text.read = snd_timer_proc_read; if (snd_info_register(entry) < 0) { snd_info_free_entry(entry); entry = NULL; } } snd_timer_proc_entry = entry; } static void __exit snd_timer_proc_done(void) { snd_info_free_entry(snd_timer_proc_entry); } #else /* !CONFIG_SND_PROC_FS */ #define snd_timer_proc_init() #define snd_timer_proc_done() #endif /* * USER SPACE interface */ static void snd_timer_user_interrupt(struct snd_timer_instance *timeri, unsigned long resolution, unsigned long ticks) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_read *r; int prev; spin_lock(&tu->qlock); if (tu->qused > 0) { prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1; r = &tu->queue[prev]; if (r->resolution == resolution) { r->ticks += ticks; goto __wake; } } if (tu->qused >= tu->queue_size) { tu->overrun++; } else { r = &tu->queue[tu->qtail++]; tu->qtail %= tu->queue_size; r->resolution = resolution; r->ticks = ticks; tu->qused++; } __wake: spin_unlock(&tu->qlock); kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); } static void snd_timer_user_append_to_tqueue(struct snd_timer_user *tu, struct snd_timer_tread *tread) { if (tu->qused >= tu->queue_size) { tu->overrun++; } else { memcpy(&tu->tqueue[tu->qtail++], tread, sizeof(*tread)); tu->qtail %= tu->queue_size; tu->qused++; } } static void snd_timer_user_ccallback(struct snd_timer_instance *timeri, int event, struct timespec *tstamp, unsigned long resolution) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread r1; unsigned long flags; if (event >= SNDRV_TIMER_EVENT_START && event <= SNDRV_TIMER_EVENT_PAUSE) tu->tstamp = *tstamp; if ((tu->filter & (1 << event)) == 0 || !tu->tread) return; memset(&r1, 0, sizeof(r1)); r1.event = event; r1.tstamp = *tstamp; r1.val = resolution; spin_lock_irqsave(&tu->qlock, flags); snd_timer_user_append_to_tqueue(tu, &r1); spin_unlock_irqrestore(&tu->qlock, flags); kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); } static void snd_timer_user_disconnect(struct snd_timer_instance *timeri) { struct snd_timer_user *tu = timeri->callback_data; tu->disconnected = true; wake_up(&tu->qchange_sleep); } static void snd_timer_user_tinterrupt(struct snd_timer_instance *timeri, unsigned long resolution, unsigned long ticks) { struct snd_timer_user *tu = timeri->callback_data; struct snd_timer_tread *r, r1; struct timespec tstamp; int prev, append = 0; memset(&r1, 0, sizeof(r1)); memset(&tstamp, 0, sizeof(tstamp)); spin_lock(&tu->qlock); if ((tu->filter & ((1 << SNDRV_TIMER_EVENT_RESOLUTION) | (1 << SNDRV_TIMER_EVENT_TICK))) == 0) { spin_unlock(&tu->qlock); return; } if (tu->last_resolution != resolution || ticks > 0) { if (timer_tstamp_monotonic) ktime_get_ts(&tstamp); else getnstimeofday(&tstamp); } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_RESOLUTION)) && tu->last_resolution != resolution) { r1.event = SNDRV_TIMER_EVENT_RESOLUTION; r1.tstamp = tstamp; r1.val = resolution; snd_timer_user_append_to_tqueue(tu, &r1); tu->last_resolution = resolution; append++; } if ((tu->filter & (1 << SNDRV_TIMER_EVENT_TICK)) == 0) goto __wake; if (ticks == 0) goto __wake; if (tu->qused > 0) { prev = tu->qtail == 0 ? tu->queue_size - 1 : tu->qtail - 1; r = &tu->tqueue[prev]; if (r->event == SNDRV_TIMER_EVENT_TICK) { r->tstamp = tstamp; r->val += ticks; append++; goto __wake; } } r1.event = SNDRV_TIMER_EVENT_TICK; r1.tstamp = tstamp; r1.val = ticks; snd_timer_user_append_to_tqueue(tu, &r1); append++; __wake: spin_unlock(&tu->qlock); if (append == 0) return; kill_fasync(&tu->fasync, SIGIO, POLL_IN); wake_up(&tu->qchange_sleep); } static int snd_timer_user_open(struct inode *inode, struct file *file) { struct snd_timer_user *tu; int err; err = nonseekable_open(inode, file); if (err < 0) return err; tu = kzalloc(sizeof(*tu), GFP_KERNEL); if (tu == NULL) return -ENOMEM; spin_lock_init(&tu->qlock); init_waitqueue_head(&tu->qchange_sleep); mutex_init(&tu->ioctl_lock); tu->ticks = 1; tu->queue_size = 128; tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) { kfree(tu); return -ENOMEM; } file->private_data = tu; return 0; } static int snd_timer_user_release(struct inode *inode, struct file *file) { struct snd_timer_user *tu; if (file->private_data) { tu = file->private_data; file->private_data = NULL; mutex_lock(&tu->ioctl_lock); if (tu->timeri) snd_timer_close(tu->timeri); mutex_unlock(&tu->ioctl_lock); kfree(tu->queue); kfree(tu->tqueue); kfree(tu); } return 0; } static void snd_timer_user_zero_id(struct snd_timer_id *id) { id->dev_class = SNDRV_TIMER_CLASS_NONE; id->dev_sclass = SNDRV_TIMER_SCLASS_NONE; id->card = -1; id->device = -1; id->subdevice = -1; } static void snd_timer_user_copy_id(struct snd_timer_id *id, struct snd_timer *timer) { id->dev_class = timer->tmr_class; id->dev_sclass = SNDRV_TIMER_SCLASS_NONE; id->card = timer->card ? timer->card->number : -1; id->device = timer->tmr_device; id->subdevice = timer->tmr_subdevice; } static int snd_timer_user_next_device(struct snd_timer_id __user *_tid) { struct snd_timer_id id; struct snd_timer *timer; struct list_head *p; if (copy_from_user(&id, _tid, sizeof(id))) return -EFAULT; mutex_lock(&register_mutex); if (id.dev_class < 0) { /* first item */ if (list_empty(&snd_timer_list)) snd_timer_user_zero_id(&id); else { timer = list_entry(snd_timer_list.next, struct snd_timer, device_list); snd_timer_user_copy_id(&id, timer); } } else { switch (id.dev_class) { case SNDRV_TIMER_CLASS_GLOBAL: id.device = id.device < 0 ? 0 : id.device + 1; list_for_each(p, &snd_timer_list) { timer = list_entry(p, struct snd_timer, device_list); if (timer->tmr_class > SNDRV_TIMER_CLASS_GLOBAL) { snd_timer_user_copy_id(&id, timer); break; } if (timer->tmr_device >= id.device) { snd_timer_user_copy_id(&id, timer); break; } } if (p == &snd_timer_list) snd_timer_user_zero_id(&id); break; case SNDRV_TIMER_CLASS_CARD: case SNDRV_TIMER_CLASS_PCM: if (id.card < 0) { id.card = 0; } else { if (id.device < 0) { id.device = 0; } else { if (id.subdevice < 0) id.subdevice = 0; else id.subdevice++; } } list_for_each(p, &snd_timer_list) { timer = list_entry(p, struct snd_timer, device_list); if (timer->tmr_class > id.dev_class) { snd_timer_user_copy_id(&id, timer); break; } if (timer->tmr_class < id.dev_class) continue; if (timer->card->number > id.card) { snd_timer_user_copy_id(&id, timer); break; } if (timer->card->number < id.card) continue; if (timer->tmr_device > id.device) { snd_timer_user_copy_id(&id, timer); break; } if (timer->tmr_device < id.device) continue; if (timer->tmr_subdevice > id.subdevice) { snd_timer_user_copy_id(&id, timer); break; } if (timer->tmr_subdevice < id.subdevice) continue; snd_timer_user_copy_id(&id, timer); break; } if (p == &snd_timer_list) snd_timer_user_zero_id(&id); break; default: snd_timer_user_zero_id(&id); } } mutex_unlock(&register_mutex); if (copy_to_user(_tid, &id, sizeof(*_tid))) return -EFAULT; return 0; } static int snd_timer_user_ginfo(struct file *file, struct snd_timer_ginfo __user *_ginfo) { struct snd_timer_ginfo *ginfo; struct snd_timer_id tid; struct snd_timer *t; struct list_head *p; int err = 0; ginfo = memdup_user(_ginfo, sizeof(*ginfo)); if (IS_ERR(ginfo)) return PTR_ERR(ginfo); tid = ginfo->tid; memset(ginfo, 0, sizeof(*ginfo)); ginfo->tid = tid; mutex_lock(&register_mutex); t = snd_timer_find(&tid); if (t != NULL) { ginfo->card = t->card ? t->card->number : -1; if (t->hw.flags & SNDRV_TIMER_HW_SLAVE) ginfo->flags |= SNDRV_TIMER_FLG_SLAVE; strlcpy(ginfo->id, t->id, sizeof(ginfo->id)); strlcpy(ginfo->name, t->name, sizeof(ginfo->name)); ginfo->resolution = t->hw.resolution; if (t->hw.resolution_min > 0) { ginfo->resolution_min = t->hw.resolution_min; ginfo->resolution_max = t->hw.resolution_max; } list_for_each(p, &t->open_list_head) { ginfo->clients++; } } else { err = -ENODEV; } mutex_unlock(&register_mutex); if (err >= 0 && copy_to_user(_ginfo, ginfo, sizeof(*ginfo))) err = -EFAULT; kfree(ginfo); return err; } static int timer_set_gparams(struct snd_timer_gparams *gparams) { struct snd_timer *t; int err; mutex_lock(&register_mutex); t = snd_timer_find(&gparams->tid); if (!t) { err = -ENODEV; goto _error; } if (!list_empty(&t->open_list_head)) { err = -EBUSY; goto _error; } if (!t->hw.set_period) { err = -ENOSYS; goto _error; } err = t->hw.set_period(t, gparams->period_num, gparams->period_den); _error: mutex_unlock(&register_mutex); return err; } static int snd_timer_user_gparams(struct file *file, struct snd_timer_gparams __user *_gparams) { struct snd_timer_gparams gparams; if (copy_from_user(&gparams, _gparams, sizeof(gparams))) return -EFAULT; return timer_set_gparams(&gparams); } static int snd_timer_user_gstatus(struct file *file, struct snd_timer_gstatus __user *_gstatus) { struct snd_timer_gstatus gstatus; struct snd_timer_id tid; struct snd_timer *t; int err = 0; if (copy_from_user(&gstatus, _gstatus, sizeof(gstatus))) return -EFAULT; tid = gstatus.tid; memset(&gstatus, 0, sizeof(gstatus)); gstatus.tid = tid; mutex_lock(&register_mutex); t = snd_timer_find(&tid); if (t != NULL) { if (t->hw.c_resolution) gstatus.resolution = t->hw.c_resolution(t); else gstatus.resolution = t->hw.resolution; if (t->hw.precise_resolution) { t->hw.precise_resolution(t, &gstatus.resolution_num, &gstatus.resolution_den); } else { gstatus.resolution_num = gstatus.resolution; gstatus.resolution_den = 1000000000uL; } } else { err = -ENODEV; } mutex_unlock(&register_mutex); if (err >= 0 && copy_to_user(_gstatus, &gstatus, sizeof(gstatus))) err = -EFAULT; return err; } static int snd_timer_user_tselect(struct file *file, struct snd_timer_select __user *_tselect) { struct snd_timer_user *tu; struct snd_timer_select tselect; char str[32]; int err = 0; tu = file->private_data; if (tu->timeri) { snd_timer_close(tu->timeri); tu->timeri = NULL; } if (copy_from_user(&tselect, _tselect, sizeof(tselect))) { err = -EFAULT; goto __err; } sprintf(str, "application %i", current->pid); if (tselect.id.dev_class != SNDRV_TIMER_CLASS_SLAVE) tselect.id.dev_sclass = SNDRV_TIMER_SCLASS_APPLICATION; err = snd_timer_open(&tu->timeri, str, &tselect.id, current->pid); if (err < 0) goto __err; kfree(tu->queue); tu->queue = NULL; kfree(tu->tqueue); tu->tqueue = NULL; if (tu->tread) { tu->tqueue = kmalloc(tu->queue_size * sizeof(struct snd_timer_tread), GFP_KERNEL); if (tu->tqueue == NULL) err = -ENOMEM; } else { tu->queue = kmalloc(tu->queue_size * sizeof(struct snd_timer_read), GFP_KERNEL); if (tu->queue == NULL) err = -ENOMEM; } if (err < 0) { snd_timer_close(tu->timeri); tu->timeri = NULL; } else { tu->timeri->flags |= SNDRV_TIMER_IFLG_FAST; tu->timeri->callback = tu->tread ? snd_timer_user_tinterrupt : snd_timer_user_interrupt; tu->timeri->ccallback = snd_timer_user_ccallback; tu->timeri->callback_data = (void *)tu; tu->timeri->disconnect = snd_timer_user_disconnect; } __err: return err; } static int snd_timer_user_info(struct file *file, struct snd_timer_info __user *_info) { struct snd_timer_user *tu; struct snd_timer_info *info; struct snd_timer *t; int err = 0; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; info = kzalloc(sizeof(*info), GFP_KERNEL); if (! info) return -ENOMEM; info->card = t->card ? t->card->number : -1; if (t->hw.flags & SNDRV_TIMER_HW_SLAVE) info->flags |= SNDRV_TIMER_FLG_SLAVE; strlcpy(info->id, t->id, sizeof(info->id)); strlcpy(info->name, t->name, sizeof(info->name)); info->resolution = t->hw.resolution; if (copy_to_user(_info, info, sizeof(*_info))) err = -EFAULT; kfree(info); return err; } static int snd_timer_user_params(struct file *file, struct snd_timer_params __user *_params) { struct snd_timer_user *tu; struct snd_timer_params params; struct snd_timer *t; struct snd_timer_read *tr; struct snd_timer_tread *ttr; int err; tu = file->private_data; if (!tu->timeri) return -EBADFD; t = tu->timeri->timer; if (!t) return -EBADFD; if (copy_from_user(&params, _params, sizeof(params))) return -EFAULT; if (!(t->hw.flags & SNDRV_TIMER_HW_SLAVE)) { u64 resolution; if (params.ticks < 1) { err = -EINVAL; goto _end; } /* Don't allow resolution less than 1ms */ resolution = snd_timer_resolution(tu->timeri); resolution *= params.ticks; if (resolution < 1000000) { err = -EINVAL; goto _end; } } if (params.queue_size > 0 && (params.queue_size < 32 || params.queue_size > 1024)) { err = -EINVAL; goto _end; } if (params.filter & ~((1<<SNDRV_TIMER_EVENT_RESOLUTION)| (1<<SNDRV_TIMER_EVENT_TICK)| (1<<SNDRV_TIMER_EVENT_START)| (1<<SNDRV_TIMER_EVENT_STOP)| (1<<SNDRV_TIMER_EVENT_CONTINUE)| (1<<SNDRV_TIMER_EVENT_PAUSE)| (1<<SNDRV_TIMER_EVENT_SUSPEND)| (1<<SNDRV_TIMER_EVENT_RESUME)| (1<<SNDRV_TIMER_EVENT_MSTART)| (1<<SNDRV_TIMER_EVENT_MSTOP)| (1<<SNDRV_TIMER_EVENT_MCONTINUE)| (1<<SNDRV_TIMER_EVENT_MPAUSE)| (1<<SNDRV_TIMER_EVENT_MSUSPEND)| (1<<SNDRV_TIMER_EVENT_MRESUME))) { err = -EINVAL; goto _end; } snd_timer_stop(tu->timeri); spin_lock_irq(&t->lock); tu->timeri->flags &= ~(SNDRV_TIMER_IFLG_AUTO| SNDRV_TIMER_IFLG_EXCLUSIVE| SNDRV_TIMER_IFLG_EARLY_EVENT); if (params.flags & SNDRV_TIMER_PSFLG_AUTO) tu->timeri->flags |= SNDRV_TIMER_IFLG_AUTO; if (params.flags & SNDRV_TIMER_PSFLG_EXCLUSIVE) tu->timeri->flags |= SNDRV_TIMER_IFLG_EXCLUSIVE; if (params.flags & SNDRV_TIMER_PSFLG_EARLY_EVENT) tu->timeri->flags |= SNDRV_TIMER_IFLG_EARLY_EVENT; spin_unlock_irq(&t->lock); if (params.queue_size > 0 && (unsigned int)tu->queue_size != params.queue_size) { if (tu->tread) { ttr = kmalloc(params.queue_size * sizeof(*ttr), GFP_KERNEL); if (ttr) { kfree(tu->tqueue); tu->queue_size = params.queue_size; tu->tqueue = ttr; } } else { tr = kmalloc(params.queue_size * sizeof(*tr), GFP_KERNEL); if (tr) { kfree(tu->queue); tu->queue_size = params.queue_size; tu->queue = tr; } } } tu->qhead = tu->qtail = tu->qused = 0; if (tu->timeri->flags & SNDRV_TIMER_IFLG_EARLY_EVENT) { if (tu->tread) { struct snd_timer_tread tread; memset(&tread, 0, sizeof(tread)); tread.event = SNDRV_TIMER_EVENT_EARLY; tread.tstamp.tv_sec = 0; tread.tstamp.tv_nsec = 0; tread.val = 0; snd_timer_user_append_to_tqueue(tu, &tread); } else { struct snd_timer_read *r = &tu->queue[0]; r->resolution = 0; r->ticks = 0; tu->qused++; tu->qtail++; } } tu->filter = params.filter; tu->ticks = params.ticks; err = 0; _end: if (copy_to_user(_params, &params, sizeof(params))) return -EFAULT; return err; } static int snd_timer_user_status(struct file *file, struct snd_timer_status __user *_status) { struct snd_timer_user *tu; struct snd_timer_status status; tu = file->private_data; if (!tu->timeri) return -EBADFD; memset(&status, 0, sizeof(status)); status.tstamp = tu->tstamp; status.resolution = snd_timer_resolution(tu->timeri); status.lost = tu->timeri->lost; status.overrun = tu->overrun; spin_lock_irq(&tu->qlock); status.queue = tu->qused; spin_unlock_irq(&tu->qlock); if (copy_to_user(_status, &status, sizeof(status))) return -EFAULT; return 0; } static int snd_timer_user_start(struct file *file) { int err; struct snd_timer_user *tu; tu = file->private_data; if (!tu->timeri) return -EBADFD; snd_timer_stop(tu->timeri); tu->timeri->lost = 0; tu->last_resolution = 0; return (err = snd_timer_start(tu->timeri, tu->ticks)) < 0 ? err : 0; } static int snd_timer_user_stop(struct file *file) { int err; struct snd_timer_user *tu; tu = file->private_data; if (!tu->timeri) return -EBADFD; return (err = snd_timer_stop(tu->timeri)) < 0 ? err : 0; } static int snd_timer_user_continue(struct file *file) { int err; struct snd_timer_user *tu; tu = file->private_data; if (!tu->timeri) return -EBADFD; /* start timer instead of continue if it's not used before */ if (!(tu->timeri->flags & SNDRV_TIMER_IFLG_PAUSED)) return snd_timer_user_start(file); tu->timeri->lost = 0; return (err = snd_timer_continue(tu->timeri)) < 0 ? err : 0; } static int snd_timer_user_pause(struct file *file) { int err; struct snd_timer_user *tu; tu = file->private_data; if (!tu->timeri) return -EBADFD; return (err = snd_timer_pause(tu->timeri)) < 0 ? err : 0; } enum { SNDRV_TIMER_IOCTL_START_OLD = _IO('T', 0x20), SNDRV_TIMER_IOCTL_STOP_OLD = _IO('T', 0x21), SNDRV_TIMER_IOCTL_CONTINUE_OLD = _IO('T', 0x22), SNDRV_TIMER_IOCTL_PAUSE_OLD = _IO('T', 0x23), }; static long __snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu; void __user *argp = (void __user *)arg; int __user *p = argp; tu = file->private_data; switch (cmd) { case SNDRV_TIMER_IOCTL_PVERSION: return put_user(SNDRV_TIMER_VERSION, p) ? -EFAULT : 0; case SNDRV_TIMER_IOCTL_NEXT_DEVICE: return snd_timer_user_next_device(argp); case SNDRV_TIMER_IOCTL_TREAD: { int xarg; if (tu->timeri) /* too late */ return -EBUSY; if (get_user(xarg, p)) return -EFAULT; tu->tread = xarg ? 1 : 0; return 0; } case SNDRV_TIMER_IOCTL_GINFO: return snd_timer_user_ginfo(file, argp); case SNDRV_TIMER_IOCTL_GPARAMS: return snd_timer_user_gparams(file, argp); case SNDRV_TIMER_IOCTL_GSTATUS: return snd_timer_user_gstatus(file, argp); case SNDRV_TIMER_IOCTL_SELECT: return snd_timer_user_tselect(file, argp); case SNDRV_TIMER_IOCTL_INFO: return snd_timer_user_info(file, argp); case SNDRV_TIMER_IOCTL_PARAMS: return snd_timer_user_params(file, argp); case SNDRV_TIMER_IOCTL_STATUS: return snd_timer_user_status(file, argp); case SNDRV_TIMER_IOCTL_START: case SNDRV_TIMER_IOCTL_START_OLD: return snd_timer_user_start(file); case SNDRV_TIMER_IOCTL_STOP: case SNDRV_TIMER_IOCTL_STOP_OLD: return snd_timer_user_stop(file); case SNDRV_TIMER_IOCTL_CONTINUE: case SNDRV_TIMER_IOCTL_CONTINUE_OLD: return snd_timer_user_continue(file); case SNDRV_TIMER_IOCTL_PAUSE: case SNDRV_TIMER_IOCTL_PAUSE_OLD: return snd_timer_user_pause(file); } return -ENOTTY; } static long snd_timer_user_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { struct snd_timer_user *tu = file->private_data; long ret; mutex_lock(&tu->ioctl_lock); ret = __snd_timer_user_ioctl(file, cmd, arg); mutex_unlock(&tu->ioctl_lock); return ret; } static int snd_timer_user_fasync(int fd, struct file * file, int on) { struct snd_timer_user *tu; tu = file->private_data; return fasync_helper(fd, file, on, &tu->fasync); } static ssize_t snd_timer_user_read(struct file *file, char __user *buffer, size_t count, loff_t *offset) { struct snd_timer_user *tu; long result = 0, unit; int qhead; int err = 0; tu = file->private_data; unit = tu->tread ? sizeof(struct snd_timer_tread) : sizeof(struct snd_timer_read); spin_lock_irq(&tu->qlock); while ((long)count - result >= unit) { while (!tu->qused) { wait_queue_t wait; if ((file->f_flags & O_NONBLOCK) != 0 || result > 0) { err = -EAGAIN; goto _error; } set_current_state(TASK_INTERRUPTIBLE); init_waitqueue_entry(&wait, current); add_wait_queue(&tu->qchange_sleep, &wait); spin_unlock_irq(&tu->qlock); schedule(); spin_lock_irq(&tu->qlock); remove_wait_queue(&tu->qchange_sleep, &wait); if (tu->disconnected) { err = -ENODEV; goto _error; } if (signal_pending(current)) { err = -ERESTARTSYS; goto _error; } } qhead = tu->qhead++; tu->qhead %= tu->queue_size; tu->qused--; spin_unlock_irq(&tu->qlock); mutex_lock(&tu->ioctl_lock); if (tu->tread) { if (copy_to_user(buffer, &tu->tqueue[qhead], sizeof(struct snd_timer_tread))) err = -EFAULT; } else { if (copy_to_user(buffer, &tu->queue[qhead], sizeof(struct snd_timer_read))) err = -EFAULT; } mutex_unlock(&tu->ioctl_lock); spin_lock_irq(&tu->qlock); if (err < 0) goto _error; result += unit; buffer += unit; } _error: spin_unlock_irq(&tu->qlock); return result > 0 ? result : err; } static unsigned int snd_timer_user_poll(struct file *file, poll_table * wait) { unsigned int mask; struct snd_timer_user *tu; tu = file->private_data; poll_wait(file, &tu->qchange_sleep, wait); mask = 0; if (tu->qused) mask |= POLLIN | POLLRDNORM; if (tu->disconnected) mask |= POLLERR; return mask; } #ifdef CONFIG_COMPAT #include "timer_compat.c" #else #define snd_timer_user_ioctl_compat NULL #endif static const struct file_operations snd_timer_f_ops = { .owner = THIS_MODULE, .read = snd_timer_user_read, .open = snd_timer_user_open, .release = snd_timer_user_release, .llseek = no_llseek, .poll = snd_timer_user_poll, .unlocked_ioctl = snd_timer_user_ioctl, .compat_ioctl = snd_timer_user_ioctl_compat, .fasync = snd_timer_user_fasync, }; /* unregister the system timer */ static void snd_timer_free_all(void) { struct snd_timer *timer, *n; list_for_each_entry_safe(timer, n, &snd_timer_list, device_list) snd_timer_free(timer); } static struct device timer_dev; /* * ENTRY functions */ static int __init alsa_timer_init(void) { int err; snd_device_initialize(&timer_dev, NULL); dev_set_name(&timer_dev, "timer"); #ifdef SNDRV_OSS_INFO_DEV_TIMERS snd_oss_info_register(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1, "system timer"); #endif err = snd_timer_register_system(); if (err < 0) { pr_err("ALSA: unable to register system timer (%i)\n", err); put_device(&timer_dev); return err; } err = snd_register_device(SNDRV_DEVICE_TYPE_TIMER, NULL, 0, &snd_timer_f_ops, NULL, &timer_dev); if (err < 0) { pr_err("ALSA: unable to register timer device (%i)\n", err); snd_timer_free_all(); put_device(&timer_dev); return err; } snd_timer_proc_init(); return 0; } static void __exit alsa_timer_exit(void) { snd_unregister_device(&timer_dev); snd_timer_free_all(); put_device(&timer_dev); snd_timer_proc_done(); #ifdef SNDRV_OSS_INFO_DEV_TIMERS snd_oss_info_unregister(SNDRV_OSS_INFO_DEV_TIMERS, SNDRV_CARDS - 1); #endif } module_init(alsa_timer_init) module_exit(alsa_timer_exit) EXPORT_SYMBOL(snd_timer_open); EXPORT_SYMBOL(snd_timer_close); EXPORT_SYMBOL(snd_timer_resolution); EXPORT_SYMBOL(snd_timer_start); EXPORT_SYMBOL(snd_timer_stop); EXPORT_SYMBOL(snd_timer_continue); EXPORT_SYMBOL(snd_timer_pause); EXPORT_SYMBOL(snd_timer_new); EXPORT_SYMBOL(snd_timer_notify); EXPORT_SYMBOL(snd_timer_global_new); EXPORT_SYMBOL(snd_timer_global_free); EXPORT_SYMBOL(snd_timer_global_register); EXPORT_SYMBOL(snd_timer_interrupt);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2527_0
crossvul-cpp_data_good_866_3
/* Written by Ricky Zhou <ricky@fedoraproject.org> * Fredrik Thulin <fredrik@yubico.com> implemented pam_modutil_drop_priv * * Copyright (c) 2011-2014 Yubico AB * Copyright (c) 2011 Ricky Zhou <ricky@fedoraproject.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifndef HAVE_PAM_MODUTIL_DROP_PRIV #include <unistd.h> #include <pwd.h> #include <grp.h> #include <errno.h> #include <string.h> #include <stdlib.h> #include "drop_privs.h" #include "util.h" #ifdef HAVE_SECURITY_PAM_APPL_H #include <security/pam_appl.h> #endif #ifdef HAVE_SECURITY_PAM_MODULES_H #include <security/pam_modules.h> #endif int pam_modutil_drop_priv(pam_handle_t *pamh, struct _ykpam_privs *privs, struct passwd *pw) { privs->saved_euid = geteuid(); privs->saved_egid = getegid(); if ((privs->saved_euid == pw->pw_uid) && (privs->saved_egid == pw->pw_gid)) { D (privs->debug_file, "Privilges already dropped, pretend it is all right"); return 0; } privs->saved_groups_length = getgroups(0, NULL); if (privs->saved_groups_length < 0) { D (privs->debug_file, "getgroups: %s", strerror(errno)); return -1; } if (privs->saved_groups_length > SAVED_GROUPS_MAX_LEN) { D (privs->debug_file, "too many groups, limiting."); privs->saved_groups_length = SAVED_GROUPS_MAX_LEN; } if (privs->saved_groups_length > 0) { if (getgroups(privs->saved_groups_length, privs->saved_groups) < 0) { D (privs->debug_file, "getgroups: %s", strerror(errno)); goto free_out; } } if (initgroups(pw->pw_name, pw->pw_gid) < 0) { D (privs->debug_file, "initgroups: %s", strerror(errno)); goto free_out; } if (setegid(pw->pw_gid) < 0) { D (privs->debug_file, "setegid: %s", strerror(errno)); goto free_out; } if (seteuid(pw->pw_uid) < 0) { D (privs->debug_file, "seteuid: %s", strerror(errno)); goto free_out; } return 0; free_out: return -1; } int pam_modutil_regain_priv(pam_handle_t *pamh, struct _ykpam_privs *privs) { if ((privs->saved_euid == geteuid()) && (privs->saved_egid == getegid())) { D (privs->debug_file, "Privilges already as requested, pretend it is all right"); return 0; } if (seteuid(privs->saved_euid) < 0) { D (privs->debug_file, "seteuid: %s", strerror(errno)); return -1; } if (setegid(privs->saved_egid) < 0) { D (privs->debug_file, "setegid: %s", strerror(errno)); return -1; } if (setgroups(privs->saved_groups_length, privs->saved_groups) < 0) { D (privs->debug_file, "setgroups: %s", strerror(errno)); return -1; } return 0; } #else // drop_privs.c:124: warning: ISO C forbids an empty translation unit [-Wpedantic] typedef int make_iso_compilers_happy; #endif // HAVE_PAM_MODUTIL_DROP_PRIV
./CrossVul/dataset_final_sorted/CWE-200/c/good_866_3
crossvul-cpp_data_bad_760_2
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * ROUTE - implementation of the IP router. * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Linus Torvalds, <Linus.Torvalds@helsinki.fi> * Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru> * * Fixes: * Alan Cox : Verify area fixes. * Alan Cox : cli() protects routing changes * Rui Oliveira : ICMP routing table updates * (rco@di.uminho.pt) Routing table insertion and update * Linus Torvalds : Rewrote bits to be sensible * Alan Cox : Added BSD route gw semantics * Alan Cox : Super /proc >4K * Alan Cox : MTU in route table * Alan Cox : MSS actually. Also added the window * clamper. * Sam Lantinga : Fixed route matching in rt_del() * Alan Cox : Routing cache support. * Alan Cox : Removed compatibility cruft. * Alan Cox : RTF_REJECT support. * Alan Cox : TCP irtt support. * Jonathan Naylor : Added Metric support. * Miquel van Smoorenburg : BSD API fixes. * Miquel van Smoorenburg : Metrics. * Alan Cox : Use __u32 properly * Alan Cox : Aligned routing errors more closely with BSD * our system is still very different. * Alan Cox : Faster /proc handling * Alexey Kuznetsov : Massive rework to support tree based routing, * routing caches and better behaviour. * * Olaf Erb : irtt wasn't being copied right. * Bjorn Ekwall : Kerneld route support. * Alan Cox : Multicast fixed (I hope) * Pavel Krauz : Limited broadcast fixed * Mike McLagan : Routing by source * Alexey Kuznetsov : End of old history. Split to fib.c and * route.c and rewritten from scratch. * Andi Kleen : Load-limit warning messages. * Vitaly E. Lavrov : Transparent proxy revived after year coma. * Vitaly E. Lavrov : Race condition in ip_route_input_slow. * Tobias Ringstrom : Uninitialized res.type in ip_route_output_slow. * Vladimir V. Ivanov : IP rule info (flowid) is really useful. * Marc Boucher : routing by fwmark * Robert Olsson : Added rt_cache statistics * Arnaldo C. Melo : Convert proc stuff to seq_file * Eric Dumazet : hashed spinlocks and rt_check_expire() fixes. * Ilia Sotnikov : Ignore TOS on PMTUD and Redirect * Ilia Sotnikov : Removed TOS from hash calculations * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #define pr_fmt(fmt) "IPv4: " fmt #include <linux/module.h> #include <linux/uaccess.h> #include <linux/bitops.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/errno.h> #include <linux/in.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/proc_fs.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/inetdevice.h> #include <linux/igmp.h> #include <linux/pkt_sched.h> #include <linux/mroute.h> #include <linux/netfilter_ipv4.h> #include <linux/random.h> #include <linux/rcupdate.h> #include <linux/times.h> #include <linux/slab.h> #include <linux/jhash.h> #include <net/dst.h> #include <net/dst_metadata.h> #include <net/net_namespace.h> #include <net/protocol.h> #include <net/ip.h> #include <net/route.h> #include <net/inetpeer.h> #include <net/sock.h> #include <net/ip_fib.h> #include <net/arp.h> #include <net/tcp.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/lwtunnel.h> #include <net/netevent.h> #include <net/rtnetlink.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #endif #include <net/secure_seq.h> #include <net/ip_tunnels.h> #include <net/l3mdev.h> #include "fib_lookup.h" #define RT_FL_TOS(oldflp4) \ ((oldflp4)->flowi4_tos & (IPTOS_RT_MASK | RTO_ONLINK)) #define RT_GC_TIMEOUT (300*HZ) static int ip_rt_max_size; static int ip_rt_redirect_number __read_mostly = 9; static int ip_rt_redirect_load __read_mostly = HZ / 50; static int ip_rt_redirect_silence __read_mostly = ((HZ / 50) << (9 + 1)); static int ip_rt_error_cost __read_mostly = HZ; static int ip_rt_error_burst __read_mostly = 5 * HZ; static int ip_rt_mtu_expires __read_mostly = 10 * 60 * HZ; static u32 ip_rt_min_pmtu __read_mostly = 512 + 20 + 20; static int ip_rt_min_advmss __read_mostly = 256; static int ip_rt_gc_timeout __read_mostly = RT_GC_TIMEOUT; /* * Interface to generic destination cache. */ static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie); static unsigned int ipv4_default_advmss(const struct dst_entry *dst); static unsigned int ipv4_mtu(const struct dst_entry *dst); static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst); static void ipv4_link_failure(struct sk_buff *skb); static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu); static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb); static void ipv4_dst_destroy(struct dst_entry *dst); static u32 *ipv4_cow_metrics(struct dst_entry *dst, unsigned long old) { WARN_ON(1); return NULL; } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr); static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr); static struct dst_ops ipv4_dst_ops = { .family = AF_INET, .check = ipv4_dst_check, .default_advmss = ipv4_default_advmss, .mtu = ipv4_mtu, .cow_metrics = ipv4_cow_metrics, .destroy = ipv4_dst_destroy, .negative_advice = ipv4_negative_advice, .link_failure = ipv4_link_failure, .update_pmtu = ip_rt_update_pmtu, .redirect = ip_do_redirect, .local_out = __ip_local_out, .neigh_lookup = ipv4_neigh_lookup, .confirm_neigh = ipv4_confirm_neigh, }; #define ECN_OR_COST(class) TC_PRIO_##class const __u8 ip_tos2prio[16] = { TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK) }; EXPORT_SYMBOL(ip_tos2prio); static DEFINE_PER_CPU(struct rt_cache_stat, rt_cache_stat); #define RT_CACHE_STAT_INC(field) raw_cpu_inc(rt_cache_stat.field) #ifdef CONFIG_PROC_FS static void *rt_cache_seq_start(struct seq_file *seq, loff_t *pos) { if (*pos) return NULL; return SEQ_START_TOKEN; } static void *rt_cache_seq_next(struct seq_file *seq, void *v, loff_t *pos) { ++*pos; return NULL; } static void rt_cache_seq_stop(struct seq_file *seq, void *v) { } static int rt_cache_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) seq_printf(seq, "%-127s\n", "Iface\tDestination\tGateway \tFlags\t\tRefCnt\tUse\t" "Metric\tSource\t\tMTU\tWindow\tIRTT\tTOS\tHHRef\t" "HHUptod\tSpecDst"); return 0; } static const struct seq_operations rt_cache_seq_ops = { .start = rt_cache_seq_start, .next = rt_cache_seq_next, .stop = rt_cache_seq_stop, .show = rt_cache_seq_show, }; static int rt_cache_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cache_seq_ops); } static const struct file_operations rt_cache_seq_fops = { .open = rt_cache_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void *rt_cpu_seq_start(struct seq_file *seq, loff_t *pos) { int cpu; if (*pos == 0) return SEQ_START_TOKEN; for (cpu = *pos-1; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void *rt_cpu_seq_next(struct seq_file *seq, void *v, loff_t *pos) { int cpu; for (cpu = *pos; cpu < nr_cpu_ids; ++cpu) { if (!cpu_possible(cpu)) continue; *pos = cpu+1; return &per_cpu(rt_cache_stat, cpu); } return NULL; } static void rt_cpu_seq_stop(struct seq_file *seq, void *v) { } static int rt_cpu_seq_show(struct seq_file *seq, void *v) { struct rt_cache_stat *st = v; if (v == SEQ_START_TOKEN) { seq_printf(seq, "entries in_hit in_slow_tot in_slow_mc in_no_route in_brd in_martian_dst in_martian_src out_hit out_slow_tot out_slow_mc gc_total gc_ignored gc_goal_miss gc_dst_overflow in_hlist_search out_hlist_search\n"); return 0; } seq_printf(seq,"%08x %08x %08x %08x %08x %08x %08x %08x " " %08x %08x %08x %08x %08x %08x %08x %08x %08x \n", dst_entries_get_slow(&ipv4_dst_ops), 0, /* st->in_hit */ st->in_slow_tot, st->in_slow_mc, st->in_no_route, st->in_brd, st->in_martian_dst, st->in_martian_src, 0, /* st->out_hit */ st->out_slow_tot, st->out_slow_mc, 0, /* st->gc_total */ 0, /* st->gc_ignored */ 0, /* st->gc_goal_miss */ 0, /* st->gc_dst_overflow */ 0, /* st->in_hlist_search */ 0 /* st->out_hlist_search */ ); return 0; } static const struct seq_operations rt_cpu_seq_ops = { .start = rt_cpu_seq_start, .next = rt_cpu_seq_next, .stop = rt_cpu_seq_stop, .show = rt_cpu_seq_show, }; static int rt_cpu_seq_open(struct inode *inode, struct file *file) { return seq_open(file, &rt_cpu_seq_ops); } static const struct file_operations rt_cpu_seq_fops = { .open = rt_cpu_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #ifdef CONFIG_IP_ROUTE_CLASSID static int rt_acct_proc_show(struct seq_file *m, void *v) { struct ip_rt_acct *dst, *src; unsigned int i, j; dst = kcalloc(256, sizeof(struct ip_rt_acct), GFP_KERNEL); if (!dst) return -ENOMEM; for_each_possible_cpu(i) { src = (struct ip_rt_acct *)per_cpu_ptr(ip_rt_acct, i); for (j = 0; j < 256; j++) { dst[j].o_bytes += src[j].o_bytes; dst[j].o_packets += src[j].o_packets; dst[j].i_bytes += src[j].i_bytes; dst[j].i_packets += src[j].i_packets; } } seq_write(m, dst, 256 * sizeof(struct ip_rt_acct)); kfree(dst); return 0; } #endif static int __net_init ip_rt_do_proc_init(struct net *net) { struct proc_dir_entry *pde; pde = proc_create("rt_cache", 0444, net->proc_net, &rt_cache_seq_fops); if (!pde) goto err1; pde = proc_create("rt_cache", 0444, net->proc_net_stat, &rt_cpu_seq_fops); if (!pde) goto err2; #ifdef CONFIG_IP_ROUTE_CLASSID pde = proc_create_single("rt_acct", 0, net->proc_net, rt_acct_proc_show); if (!pde) goto err3; #endif return 0; #ifdef CONFIG_IP_ROUTE_CLASSID err3: remove_proc_entry("rt_cache", net->proc_net_stat); #endif err2: remove_proc_entry("rt_cache", net->proc_net); err1: return -ENOMEM; } static void __net_exit ip_rt_do_proc_exit(struct net *net) { remove_proc_entry("rt_cache", net->proc_net_stat); remove_proc_entry("rt_cache", net->proc_net); #ifdef CONFIG_IP_ROUTE_CLASSID remove_proc_entry("rt_acct", net->proc_net); #endif } static struct pernet_operations ip_rt_proc_ops __net_initdata = { .init = ip_rt_do_proc_init, .exit = ip_rt_do_proc_exit, }; static int __init ip_rt_proc_init(void) { return register_pernet_subsys(&ip_rt_proc_ops); } #else static inline int ip_rt_proc_init(void) { return 0; } #endif /* CONFIG_PROC_FS */ static inline bool rt_is_expired(const struct rtable *rth) { return rth->rt_genid != rt_genid_ipv4(dev_net(rth->dst.dev)); } void rt_cache_flush(struct net *net) { rt_genid_bump_ipv4(net); } static struct neighbour *ipv4_neigh_lookup(const struct dst_entry *dst, struct sk_buff *skb, const void *daddr) { struct net_device *dev = dst->dev; const __be32 *pkey = daddr; const struct rtable *rt; struct neighbour *n; rt = (const struct rtable *) dst; if (rt->rt_gateway) pkey = (const __be32 *) &rt->rt_gateway; else if (skb) pkey = &ip_hdr(skb)->daddr; n = __ipv4_neigh_lookup(dev, *(__force u32 *)pkey); if (n) return n; return neigh_create(&arp_tbl, pkey, dev); } static void ipv4_confirm_neigh(const struct dst_entry *dst, const void *daddr) { struct net_device *dev = dst->dev; const __be32 *pkey = daddr; const struct rtable *rt; rt = (const struct rtable *)dst; if (rt->rt_gateway) pkey = (const __be32 *)&rt->rt_gateway; else if (!daddr || (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST | RTCF_LOCAL))) return; __ipv4_confirm_neigh(dev, *(__force u32 *)pkey); } #define IP_IDENTS_SZ 2048u static atomic_t *ip_idents __read_mostly; static u32 *ip_tstamps __read_mostly; /* In order to protect privacy, we add a perturbation to identifiers * if one generator is seldom used. This makes hard for an attacker * to infer how many packets were sent between two points in time. */ u32 ip_idents_reserve(u32 hash, int segs) { u32 *p_tstamp = ip_tstamps + hash % IP_IDENTS_SZ; atomic_t *p_id = ip_idents + hash % IP_IDENTS_SZ; u32 old = READ_ONCE(*p_tstamp); u32 now = (u32)jiffies; u32 new, delta = 0; if (old != now && cmpxchg(p_tstamp, old, now) == old) delta = prandom_u32_max(now - old); /* Do not use atomic_add_return() as it makes UBSAN unhappy */ do { old = (u32)atomic_read(p_id); new = old + delta + segs; } while (atomic_cmpxchg(p_id, old, new) != old); return new - segs; } EXPORT_SYMBOL(ip_idents_reserve); void __ip_select_ident(struct net *net, struct iphdr *iph, int segs) { static u32 ip_idents_hashrnd __read_mostly; u32 hash, id; net_get_random_once(&ip_idents_hashrnd, sizeof(ip_idents_hashrnd)); hash = jhash_3words((__force u32)iph->daddr, (__force u32)iph->saddr, iph->protocol ^ net_hash_mix(net), ip_idents_hashrnd); id = ip_idents_reserve(hash, segs); iph->id = htons(id); } EXPORT_SYMBOL(__ip_select_ident); static void __build_flow_key(const struct net *net, struct flowi4 *fl4, const struct sock *sk, const struct iphdr *iph, int oif, u8 tos, u8 prot, u32 mark, int flow_flags) { if (sk) { const struct inet_sock *inet = inet_sk(sk); oif = sk->sk_bound_dev_if; mark = sk->sk_mark; tos = RT_CONN_FLAGS(sk); prot = inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol; } flowi4_init_output(fl4, oif, mark, tos, RT_SCOPE_UNIVERSE, prot, flow_flags, iph->daddr, iph->saddr, 0, 0, sock_net_uid(net, sk)); } static void build_skb_flow_key(struct flowi4 *fl4, const struct sk_buff *skb, const struct sock *sk) { const struct net *net = dev_net(skb->dev); const struct iphdr *iph = ip_hdr(skb); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; __build_flow_key(net, fl4, sk, iph, oif, tos, prot, mark, 0); } static void build_sk_flow_key(struct flowi4 *fl4, const struct sock *sk) { const struct inet_sock *inet = inet_sk(sk); const struct ip_options_rcu *inet_opt; __be32 daddr = inet->inet_daddr; rcu_read_lock(); inet_opt = rcu_dereference(inet->inet_opt); if (inet_opt && inet_opt->opt.srr) daddr = inet_opt->opt.faddr; flowi4_init_output(fl4, sk->sk_bound_dev_if, sk->sk_mark, RT_CONN_FLAGS(sk), RT_SCOPE_UNIVERSE, inet->hdrincl ? IPPROTO_RAW : sk->sk_protocol, inet_sk_flowi_flags(sk), daddr, inet->inet_saddr, 0, 0, sk->sk_uid); rcu_read_unlock(); } static void ip_rt_build_flow_key(struct flowi4 *fl4, const struct sock *sk, const struct sk_buff *skb) { if (skb) build_skb_flow_key(fl4, skb, sk); else build_sk_flow_key(fl4, sk); } static DEFINE_SPINLOCK(fnhe_lock); static void fnhe_flush_routes(struct fib_nh_exception *fnhe) { struct rtable *rt; rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_input, NULL); dst_dev_put(&rt->dst); dst_release(&rt->dst); } rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) { RCU_INIT_POINTER(fnhe->fnhe_rth_output, NULL); dst_dev_put(&rt->dst); dst_release(&rt->dst); } } static struct fib_nh_exception *fnhe_oldest(struct fnhe_hash_bucket *hash) { struct fib_nh_exception *fnhe, *oldest; oldest = rcu_dereference(hash->chain); for (fnhe = rcu_dereference(oldest->fnhe_next); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (time_before(fnhe->fnhe_stamp, oldest->fnhe_stamp)) oldest = fnhe; } fnhe_flush_routes(oldest); return oldest; } static inline u32 fnhe_hashfun(__be32 daddr) { static u32 fnhe_hashrnd __read_mostly; u32 hval; net_get_random_once(&fnhe_hashrnd, sizeof(fnhe_hashrnd)); hval = jhash_1word((__force u32) daddr, fnhe_hashrnd); return hash_32(hval, FNHE_HASH_SHIFT); } static void fill_route_from_fnhe(struct rtable *rt, struct fib_nh_exception *fnhe) { rt->rt_pmtu = fnhe->fnhe_pmtu; rt->rt_mtu_locked = fnhe->fnhe_mtu_locked; rt->dst.expires = fnhe->fnhe_expires; if (fnhe->fnhe_gw) { rt->rt_flags |= RTCF_REDIRECTED; rt->rt_gateway = fnhe->fnhe_gw; rt->rt_uses_gateway = 1; } } static void update_or_create_fnhe(struct fib_nh *nh, __be32 daddr, __be32 gw, u32 pmtu, bool lock, unsigned long expires) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe; struct rtable *rt; u32 genid, hval; unsigned int i; int depth; genid = fnhe_genid(dev_net(nh->nh_dev)); hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = rcu_dereference(nh->nh_exceptions); if (!hash) { hash = kcalloc(FNHE_HASH_SIZE, sizeof(*hash), GFP_ATOMIC); if (!hash) goto out_unlock; rcu_assign_pointer(nh->nh_exceptions, hash); } hash += hval; depth = 0; for (fnhe = rcu_dereference(hash->chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) break; depth++; } if (fnhe) { if (fnhe->fnhe_genid != genid) fnhe->fnhe_genid = genid; if (gw) fnhe->fnhe_gw = gw; if (pmtu) { fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_mtu_locked = lock; } fnhe->fnhe_expires = max(1UL, expires); /* Update all cached dsts too */ rt = rcu_dereference(fnhe->fnhe_rth_input); if (rt) fill_route_from_fnhe(rt, fnhe); rt = rcu_dereference(fnhe->fnhe_rth_output); if (rt) fill_route_from_fnhe(rt, fnhe); } else { if (depth > FNHE_RECLAIM_DEPTH) fnhe = fnhe_oldest(hash); else { fnhe = kzalloc(sizeof(*fnhe), GFP_ATOMIC); if (!fnhe) goto out_unlock; fnhe->fnhe_next = hash->chain; rcu_assign_pointer(hash->chain, fnhe); } fnhe->fnhe_genid = genid; fnhe->fnhe_daddr = daddr; fnhe->fnhe_gw = gw; fnhe->fnhe_pmtu = pmtu; fnhe->fnhe_mtu_locked = lock; fnhe->fnhe_expires = max(1UL, expires); /* Exception created; mark the cached routes for the nexthop * stale, so anyone caching it rechecks if this exception * applies to them. */ rt = rcu_dereference(nh->nh_rth_input); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; for_each_possible_cpu(i) { struct rtable __rcu **prt; prt = per_cpu_ptr(nh->nh_pcpu_rth_output, i); rt = rcu_dereference(*prt); if (rt) rt->dst.obsolete = DST_OBSOLETE_KILL; } } fnhe->fnhe_stamp = jiffies; out_unlock: spin_unlock_bh(&fnhe_lock); } static void __ip_do_redirect(struct rtable *rt, struct sk_buff *skb, struct flowi4 *fl4, bool kill_route) { __be32 new_gw = icmp_hdr(skb)->un.gateway; __be32 old_gw = ip_hdr(skb)->saddr; struct net_device *dev = skb->dev; struct in_device *in_dev; struct fib_result res; struct neighbour *n; struct net *net; switch (icmp_hdr(skb)->code & 7) { case ICMP_REDIR_NET: case ICMP_REDIR_NETTOS: case ICMP_REDIR_HOST: case ICMP_REDIR_HOSTTOS: break; default: return; } if (rt->rt_gateway != old_gw) return; in_dev = __in_dev_get_rcu(dev); if (!in_dev) return; net = dev_net(dev); if (new_gw == old_gw || !IN_DEV_RX_REDIRECTS(in_dev) || ipv4_is_multicast(new_gw) || ipv4_is_lbcast(new_gw) || ipv4_is_zeronet(new_gw)) goto reject_redirect; if (!IN_DEV_SHARED_MEDIA(in_dev)) { if (!inet_addr_onlink(in_dev, new_gw, old_gw)) goto reject_redirect; if (IN_DEV_SEC_REDIRECTS(in_dev) && ip_fib_check_default(new_gw, dev)) goto reject_redirect; } else { if (inet_addr_type(net, new_gw) != RTN_UNICAST) goto reject_redirect; } n = __ipv4_neigh_lookup(rt->dst.dev, new_gw); if (!n) n = neigh_create(&arp_tbl, &new_gw, rt->dst.dev); if (!IS_ERR(n)) { if (!(n->nud_state & NUD_VALID)) { neigh_event_send(n, NULL); } else { if (fib_lookup(net, fl4, &res, 0) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, new_gw, 0, false, jiffies + ip_rt_gc_timeout); } if (kill_route) rt->dst.obsolete = DST_OBSOLETE_KILL; call_netevent_notifiers(NETEVENT_NEIGH_UPDATE, n); } neigh_release(n); } return; reject_redirect: #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) { const struct iphdr *iph = (const struct iphdr *) skb->data; __be32 daddr = iph->daddr; __be32 saddr = iph->saddr; net_info_ratelimited("Redirect from %pI4 on %s about %pI4 ignored\n" " Advised path = %pI4 -> %pI4\n", &old_gw, dev->name, &new_gw, &saddr, &daddr); } #endif ; } static void ip_do_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { struct rtable *rt; struct flowi4 fl4; const struct iphdr *iph = (const struct iphdr *) skb->data; struct net *net = dev_net(skb->dev); int oif = skb->dev->ifindex; u8 tos = RT_TOS(iph->tos); u8 prot = iph->protocol; u32 mark = skb->mark; rt = (struct rtable *) dst; __build_flow_key(net, &fl4, sk, iph, oif, tos, prot, mark, 0); __ip_do_redirect(rt, skb, &fl4, true); } static struct dst_entry *ipv4_negative_advice(struct dst_entry *dst) { struct rtable *rt = (struct rtable *)dst; struct dst_entry *ret = dst; if (rt) { if (dst->obsolete > 0) { ip_rt_put(rt); ret = NULL; } else if ((rt->rt_flags & RTCF_REDIRECTED) || rt->dst.expires) { ip_rt_put(rt); ret = NULL; } } return ret; } /* * Algorithm: * 1. The first ip_rt_redirect_number redirects are sent * with exponential backoff, then we stop sending them at all, * assuming that the host ignores our redirects. * 2. If we did not see packets requiring redirects * during ip_rt_redirect_silence, we assume that the host * forgot redirected route and start to send redirects again. * * This algorithm is much cheaper and more intelligent than dumb load limiting * in icmp.c. * * NOTE. Do not forget to inhibit load limiting for redirects (redundant) * and "frag. need" (breaks PMTU discovery) in icmp.c. */ void ip_rt_send_redirect(struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct in_device *in_dev; struct inet_peer *peer; struct net *net; int log_martians; int vif; rcu_read_lock(); in_dev = __in_dev_get_rcu(rt->dst.dev); if (!in_dev || !IN_DEV_TX_REDIRECTS(in_dev)) { rcu_read_unlock(); return; } log_martians = IN_DEV_LOG_MARTIANS(in_dev); vif = l3mdev_master_ifindex_rcu(rt->dst.dev); rcu_read_unlock(); net = dev_net(rt->dst.dev); peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, vif, 1); if (!peer) { icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, rt_nexthop(rt, ip_hdr(skb)->daddr)); return; } /* No redirected packets during ip_rt_redirect_silence; * reset the algorithm. */ if (time_after(jiffies, peer->rate_last + ip_rt_redirect_silence)) { peer->rate_tokens = 0; peer->n_redirects = 0; } /* Too many ignored redirects; do not send anything * set dst.rate_last to the last seen redirected packet. */ if (peer->n_redirects >= ip_rt_redirect_number) { peer->rate_last = jiffies; goto out_put_peer; } /* Check for load limit; set rate_last to the latest sent * redirect. */ if (peer->rate_tokens == 0 || time_after(jiffies, (peer->rate_last + (ip_rt_redirect_load << peer->rate_tokens)))) { __be32 gw = rt_nexthop(rt, ip_hdr(skb)->daddr); icmp_send(skb, ICMP_REDIRECT, ICMP_REDIR_HOST, gw); peer->rate_last = jiffies; ++peer->rate_tokens; ++peer->n_redirects; #ifdef CONFIG_IP_ROUTE_VERBOSE if (log_martians && peer->rate_tokens == ip_rt_redirect_number) net_warn_ratelimited("host %pI4/if%d ignores redirects for %pI4 to %pI4\n", &ip_hdr(skb)->saddr, inet_iif(skb), &ip_hdr(skb)->daddr, &gw); #endif } out_put_peer: inet_putpeer(peer); } static int ip_error(struct sk_buff *skb) { struct rtable *rt = skb_rtable(skb); struct net_device *dev = skb->dev; struct in_device *in_dev; struct inet_peer *peer; unsigned long now; struct net *net; bool send; int code; if (netif_is_l3_master(skb->dev)) { dev = __dev_get_by_index(dev_net(skb->dev), IPCB(skb)->iif); if (!dev) goto out; } in_dev = __in_dev_get_rcu(dev); /* IP on this device is disabled. */ if (!in_dev) goto out; net = dev_net(rt->dst.dev); if (!IN_DEV_FORWARD(in_dev)) { switch (rt->dst.error) { case EHOSTUNREACH: __IP_INC_STATS(net, IPSTATS_MIB_INADDRERRORS); break; case ENETUNREACH: __IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES); break; } goto out; } switch (rt->dst.error) { case EINVAL: default: goto out; case EHOSTUNREACH: code = ICMP_HOST_UNREACH; break; case ENETUNREACH: code = ICMP_NET_UNREACH; __IP_INC_STATS(net, IPSTATS_MIB_INNOROUTES); break; case EACCES: code = ICMP_PKT_FILTERED; break; } peer = inet_getpeer_v4(net->ipv4.peers, ip_hdr(skb)->saddr, l3mdev_master_ifindex(skb->dev), 1); send = true; if (peer) { now = jiffies; peer->rate_tokens += now - peer->rate_last; if (peer->rate_tokens > ip_rt_error_burst) peer->rate_tokens = ip_rt_error_burst; peer->rate_last = now; if (peer->rate_tokens >= ip_rt_error_cost) peer->rate_tokens -= ip_rt_error_cost; else send = false; inet_putpeer(peer); } if (send) icmp_send(skb, ICMP_DEST_UNREACH, code, 0); out: kfree_skb(skb); return 0; } static void __ip_rt_update_pmtu(struct rtable *rt, struct flowi4 *fl4, u32 mtu) { struct dst_entry *dst = &rt->dst; u32 old_mtu = ipv4_mtu(dst); struct fib_result res; bool lock = false; if (ip_mtu_locked(dst)) return; if (old_mtu < mtu) return; if (mtu < ip_rt_min_pmtu) { lock = true; mtu = min(old_mtu, ip_rt_min_pmtu); } if (rt->rt_pmtu == mtu && !lock && time_before(jiffies, dst->expires - ip_rt_mtu_expires / 2)) return; rcu_read_lock(); if (fib_lookup(dev_net(dst->dev), fl4, &res, 0) == 0) { struct fib_nh *nh = &FIB_RES_NH(res); update_or_create_fnhe(nh, fl4->daddr, 0, mtu, lock, jiffies + ip_rt_mtu_expires); } rcu_read_unlock(); } static void ip_rt_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { struct rtable *rt = (struct rtable *) dst; struct flowi4 fl4; ip_rt_build_flow_key(&fl4, sk, skb); __ip_rt_update_pmtu(rt, &fl4, mtu); } void ipv4_update_pmtu(struct sk_buff *skb, struct net *net, u32 mtu, int oif, u8 protocol) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; u32 mark = IP4_REPLY_MARK(net, skb->mark); __build_flow_key(net, &fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, mark, 0); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_update_pmtu); static void __ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(sock_net(sk), &fl4, sk, iph, 0, 0, 0, 0, 0); if (!fl4.flowi4_mark) fl4.flowi4_mark = IP4_REPLY_MARK(sock_net(sk), skb->mark); rt = __ip_route_output_key(sock_net(sk), &fl4); if (!IS_ERR(rt)) { __ip_rt_update_pmtu(rt, &fl4, mtu); ip_rt_put(rt); } } void ipv4_sk_update_pmtu(struct sk_buff *skb, struct sock *sk, u32 mtu) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; struct dst_entry *odst = NULL; bool new = false; struct net *net = sock_net(sk); bh_lock_sock(sk); if (!ip_sk_accept_pmtu(sk)) goto out; odst = sk_dst_get(sk); if (sock_owned_by_user(sk) || !odst) { __ipv4_sk_update_pmtu(skb, sk, mtu); goto out; } __build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0); rt = (struct rtable *)odst; if (odst->obsolete && !odst->ops->check(odst, 0)) { rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } __ip_rt_update_pmtu((struct rtable *) xfrm_dst_path(&rt->dst), &fl4, mtu); if (!dst_check(&rt->dst, 0)) { if (new) dst_release(&rt->dst); rt = ip_route_output_flow(sock_net(sk), &fl4, sk); if (IS_ERR(rt)) goto out; new = true; } if (new) sk_dst_set(sk, &rt->dst); out: bh_unlock_sock(sk); dst_release(odst); } EXPORT_SYMBOL_GPL(ipv4_sk_update_pmtu); void ipv4_redirect(struct sk_buff *skb, struct net *net, int oif, u8 protocol) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; __build_flow_key(net, &fl4, NULL, iph, oif, RT_TOS(iph->tos), protocol, 0, 0); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_redirect); void ipv4_sk_redirect(struct sk_buff *skb, struct sock *sk) { const struct iphdr *iph = (const struct iphdr *) skb->data; struct flowi4 fl4; struct rtable *rt; struct net *net = sock_net(sk); __build_flow_key(net, &fl4, sk, iph, 0, 0, 0, 0, 0); rt = __ip_route_output_key(net, &fl4); if (!IS_ERR(rt)) { __ip_do_redirect(rt, skb, &fl4, false); ip_rt_put(rt); } } EXPORT_SYMBOL_GPL(ipv4_sk_redirect); static struct dst_entry *ipv4_dst_check(struct dst_entry *dst, u32 cookie) { struct rtable *rt = (struct rtable *) dst; /* All IPV4 dsts are created with ->obsolete set to the value * DST_OBSOLETE_FORCE_CHK which forces validation calls down * into this function always. * * When a PMTU/redirect information update invalidates a route, * this is indicated by setting obsolete to DST_OBSOLETE_KILL or * DST_OBSOLETE_DEAD. */ if (dst->obsolete != DST_OBSOLETE_FORCE_CHK || rt_is_expired(rt)) return NULL; return dst; } static void ipv4_link_failure(struct sk_buff *skb) { struct rtable *rt; icmp_send(skb, ICMP_DEST_UNREACH, ICMP_HOST_UNREACH, 0); rt = skb_rtable(skb); if (rt) dst_set_expires(&rt->dst, 0); } static int ip_rt_bug(struct net *net, struct sock *sk, struct sk_buff *skb) { pr_debug("%s: %pI4 -> %pI4, %s\n", __func__, &ip_hdr(skb)->saddr, &ip_hdr(skb)->daddr, skb->dev ? skb->dev->name : "?"); kfree_skb(skb); WARN_ON(1); return 0; } /* We do not cache source address of outgoing interface, because it is used only by IP RR, TS and SRR options, so that it out of fast path. BTW remember: "addr" is allowed to be not aligned in IP options! */ void ip_rt_get_source(u8 *addr, struct sk_buff *skb, struct rtable *rt) { __be32 src; if (rt_is_output_route(rt)) src = ip_hdr(skb)->saddr; else { struct fib_result res; struct iphdr *iph = ip_hdr(skb); struct flowi4 fl4 = { .daddr = iph->daddr, .saddr = iph->saddr, .flowi4_tos = RT_TOS(iph->tos), .flowi4_oif = rt->dst.dev->ifindex, .flowi4_iif = skb->dev->ifindex, .flowi4_mark = skb->mark, }; rcu_read_lock(); if (fib_lookup(dev_net(rt->dst.dev), &fl4, &res, 0) == 0) src = FIB_RES_PREFSRC(dev_net(rt->dst.dev), res); else src = inet_select_addr(rt->dst.dev, rt_nexthop(rt, iph->daddr), RT_SCOPE_UNIVERSE); rcu_read_unlock(); } memcpy(addr, &src, 4); } #ifdef CONFIG_IP_ROUTE_CLASSID static void set_class_tag(struct rtable *rt, u32 tag) { if (!(rt->dst.tclassid & 0xFFFF)) rt->dst.tclassid |= tag & 0xFFFF; if (!(rt->dst.tclassid & 0xFFFF0000)) rt->dst.tclassid |= tag & 0xFFFF0000; } #endif static unsigned int ipv4_default_advmss(const struct dst_entry *dst) { unsigned int header_size = sizeof(struct tcphdr) + sizeof(struct iphdr); unsigned int advmss = max_t(unsigned int, ipv4_mtu(dst) - header_size, ip_rt_min_advmss); return min(advmss, IPV4_MAX_PMTU - header_size); } static unsigned int ipv4_mtu(const struct dst_entry *dst) { const struct rtable *rt = (const struct rtable *) dst; unsigned int mtu = rt->rt_pmtu; if (!mtu || time_after_eq(jiffies, rt->dst.expires)) mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; mtu = READ_ONCE(dst->dev->mtu); if (unlikely(ip_mtu_locked(dst))) { if (rt->rt_uses_gateway && mtu > 576) mtu = 576; } mtu = min_t(unsigned int, mtu, IP_MAX_MTU); return mtu - lwtunnel_headroom(dst->lwtstate, mtu); } static void ip_del_fnhe(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash; struct fib_nh_exception *fnhe, __rcu **fnhe_p; u32 hval = fnhe_hashfun(daddr); spin_lock_bh(&fnhe_lock); hash = rcu_dereference_protected(nh->nh_exceptions, lockdep_is_held(&fnhe_lock)); hash += hval; fnhe_p = &hash->chain; fnhe = rcu_dereference_protected(*fnhe_p, lockdep_is_held(&fnhe_lock)); while (fnhe) { if (fnhe->fnhe_daddr == daddr) { rcu_assign_pointer(*fnhe_p, rcu_dereference_protected( fnhe->fnhe_next, lockdep_is_held(&fnhe_lock))); /* set fnhe_daddr to 0 to ensure it won't bind with * new dsts in rt_bind_exception(). */ fnhe->fnhe_daddr = 0; fnhe_flush_routes(fnhe); kfree_rcu(fnhe, rcu); break; } fnhe_p = &fnhe->fnhe_next; fnhe = rcu_dereference_protected(fnhe->fnhe_next, lockdep_is_held(&fnhe_lock)); } spin_unlock_bh(&fnhe_lock); } static struct fib_nh_exception *find_exception(struct fib_nh *nh, __be32 daddr) { struct fnhe_hash_bucket *hash = rcu_dereference(nh->nh_exceptions); struct fib_nh_exception *fnhe; u32 hval; if (!hash) return NULL; hval = fnhe_hashfun(daddr); for (fnhe = rcu_dereference(hash[hval].chain); fnhe; fnhe = rcu_dereference(fnhe->fnhe_next)) { if (fnhe->fnhe_daddr == daddr) { if (fnhe->fnhe_expires && time_after(jiffies, fnhe->fnhe_expires)) { ip_del_fnhe(nh, daddr); break; } return fnhe; } } return NULL; } /* MTU selection: * 1. mtu on route is locked - use it * 2. mtu from nexthop exception * 3. mtu from egress device */ u32 ip_mtu_from_fib_result(struct fib_result *res, __be32 daddr) { struct fib_info *fi = res->fi; struct fib_nh *nh = &fi->fib_nh[res->nh_sel]; struct net_device *dev = nh->nh_dev; u32 mtu = 0; if (dev_net(dev)->ipv4.sysctl_ip_fwd_use_pmtu || fi->fib_metrics->metrics[RTAX_LOCK - 1] & (1 << RTAX_MTU)) mtu = fi->fib_mtu; if (likely(!mtu)) { struct fib_nh_exception *fnhe; fnhe = find_exception(nh, daddr); if (fnhe && !time_after_eq(jiffies, fnhe->fnhe_expires)) mtu = fnhe->fnhe_pmtu; } if (likely(!mtu)) mtu = min(READ_ONCE(dev->mtu), IP_MAX_MTU); return mtu - lwtunnel_headroom(nh->nh_lwtstate, mtu); } static bool rt_bind_exception(struct rtable *rt, struct fib_nh_exception *fnhe, __be32 daddr, const bool do_cache) { bool ret = false; spin_lock_bh(&fnhe_lock); if (daddr == fnhe->fnhe_daddr) { struct rtable __rcu **porig; struct rtable *orig; int genid = fnhe_genid(dev_net(rt->dst.dev)); if (rt_is_input_route(rt)) porig = &fnhe->fnhe_rth_input; else porig = &fnhe->fnhe_rth_output; orig = rcu_dereference(*porig); if (fnhe->fnhe_genid != genid) { fnhe->fnhe_genid = genid; fnhe->fnhe_gw = 0; fnhe->fnhe_pmtu = 0; fnhe->fnhe_expires = 0; fnhe->fnhe_mtu_locked = false; fnhe_flush_routes(fnhe); orig = NULL; } fill_route_from_fnhe(rt, fnhe); if (!rt->rt_gateway) rt->rt_gateway = daddr; if (do_cache) { dst_hold(&rt->dst); rcu_assign_pointer(*porig, rt); if (orig) { dst_dev_put(&orig->dst); dst_release(&orig->dst); } ret = true; } fnhe->fnhe_stamp = jiffies; } spin_unlock_bh(&fnhe_lock); return ret; } static bool rt_cache_route(struct fib_nh *nh, struct rtable *rt) { struct rtable *orig, *prev, **p; bool ret = true; if (rt_is_input_route(rt)) { p = (struct rtable **)&nh->nh_rth_input; } else { p = (struct rtable **)raw_cpu_ptr(nh->nh_pcpu_rth_output); } orig = *p; /* hold dst before doing cmpxchg() to avoid race condition * on this dst */ dst_hold(&rt->dst); prev = cmpxchg(p, orig, rt); if (prev == orig) { if (orig) { dst_dev_put(&orig->dst); dst_release(&orig->dst); } } else { dst_release(&rt->dst); ret = false; } return ret; } struct uncached_list { spinlock_t lock; struct list_head head; }; static DEFINE_PER_CPU_ALIGNED(struct uncached_list, rt_uncached_list); void rt_add_uncached_list(struct rtable *rt) { struct uncached_list *ul = raw_cpu_ptr(&rt_uncached_list); rt->rt_uncached_list = ul; spin_lock_bh(&ul->lock); list_add_tail(&rt->rt_uncached, &ul->head); spin_unlock_bh(&ul->lock); } void rt_del_uncached_list(struct rtable *rt) { if (!list_empty(&rt->rt_uncached)) { struct uncached_list *ul = rt->rt_uncached_list; spin_lock_bh(&ul->lock); list_del(&rt->rt_uncached); spin_unlock_bh(&ul->lock); } } static void ipv4_dst_destroy(struct dst_entry *dst) { struct rtable *rt = (struct rtable *)dst; ip_dst_metrics_put(dst); rt_del_uncached_list(rt); } void rt_flush_dev(struct net_device *dev) { struct net *net = dev_net(dev); struct rtable *rt; int cpu; for_each_possible_cpu(cpu) { struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu); spin_lock_bh(&ul->lock); list_for_each_entry(rt, &ul->head, rt_uncached) { if (rt->dst.dev != dev) continue; rt->dst.dev = net->loopback_dev; dev_hold(rt->dst.dev); dev_put(dev); } spin_unlock_bh(&ul->lock); } } static bool rt_cache_valid(const struct rtable *rt) { return rt && rt->dst.obsolete == DST_OBSOLETE_FORCE_CHK && !rt_is_expired(rt); } static void rt_set_nexthop(struct rtable *rt, __be32 daddr, const struct fib_result *res, struct fib_nh_exception *fnhe, struct fib_info *fi, u16 type, u32 itag, const bool do_cache) { bool cached = false; if (fi) { struct fib_nh *nh = &FIB_RES_NH(*res); if (nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK) { rt->rt_gateway = nh->nh_gw; rt->rt_uses_gateway = 1; } ip_dst_init_metrics(&rt->dst, fi->fib_metrics); #ifdef CONFIG_IP_ROUTE_CLASSID rt->dst.tclassid = nh->nh_tclassid; #endif rt->dst.lwtstate = lwtstate_get(nh->nh_lwtstate); if (unlikely(fnhe)) cached = rt_bind_exception(rt, fnhe, daddr, do_cache); else if (do_cache) cached = rt_cache_route(nh, rt); if (unlikely(!cached)) { /* Routes we intend to cache in nexthop exception or * FIB nexthop have the DST_NOCACHE bit clear. * However, if we are unsuccessful at storing this * route into the cache we really need to set it. */ if (!rt->rt_gateway) rt->rt_gateway = daddr; rt_add_uncached_list(rt); } } else rt_add_uncached_list(rt); #ifdef CONFIG_IP_ROUTE_CLASSID #ifdef CONFIG_IP_MULTIPLE_TABLES set_class_tag(rt, res->tclassid); #endif set_class_tag(rt, itag); #endif } struct rtable *rt_dst_alloc(struct net_device *dev, unsigned int flags, u16 type, bool nopolicy, bool noxfrm, bool will_cache) { struct rtable *rt; rt = dst_alloc(&ipv4_dst_ops, dev, 1, DST_OBSOLETE_FORCE_CHK, (will_cache ? 0 : DST_HOST) | (nopolicy ? DST_NOPOLICY : 0) | (noxfrm ? DST_NOXFRM : 0)); if (rt) { rt->rt_genid = rt_genid_ipv4(dev_net(dev)); rt->rt_flags = flags; rt->rt_type = type; rt->rt_is_input = 0; rt->rt_iif = 0; rt->rt_pmtu = 0; rt->rt_mtu_locked = 0; rt->rt_gateway = 0; rt->rt_uses_gateway = 0; INIT_LIST_HEAD(&rt->rt_uncached); rt->dst.output = ip_output; if (flags & RTCF_LOCAL) rt->dst.input = ip_local_deliver; } return rt; } EXPORT_SYMBOL(rt_dst_alloc); /* called in rcu_read_lock() section */ int ip_mc_validate_source(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct in_device *in_dev, u32 *itag) { int err; /* Primary sanity checks. */ if (!in_dev) return -EINVAL; if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr) || skb->protocol != htons(ETH_P_IP)) return -EINVAL; if (ipv4_is_loopback(saddr) && !IN_DEV_ROUTE_LOCALNET(in_dev)) return -EINVAL; if (ipv4_is_zeronet(saddr)) { if (!ipv4_is_local_multicast(daddr) && ip_hdr(skb)->protocol != IPPROTO_IGMP) return -EINVAL; } else { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, itag); if (err < 0) return err; } return 0; } /* called in rcu_read_lock() section */ static int ip_route_input_mc(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, int our) { struct in_device *in_dev = __in_dev_get_rcu(dev); unsigned int flags = RTCF_MULTICAST; struct rtable *rth; u32 itag = 0; int err; err = ip_mc_validate_source(skb, daddr, saddr, tos, dev, in_dev, &itag); if (err) return err; if (our) flags |= RTCF_LOCAL; rth = rt_dst_alloc(dev_net(dev)->loopback_dev, flags, RTN_MULTICAST, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, false); if (!rth) return -ENOBUFS; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->dst.output = ip_rt_bug; rth->rt_is_input= 1; #ifdef CONFIG_IP_MROUTE if (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) rth->dst.input = ip_mr_input; #endif RT_CACHE_STAT_INC(in_slow_mc); skb_dst_set(skb, &rth->dst); return 0; } static void ip_handle_martian_source(struct net_device *dev, struct in_device *in_dev, struct sk_buff *skb, __be32 daddr, __be32 saddr) { RT_CACHE_STAT_INC(in_martian_src); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev) && net_ratelimit()) { /* * RFC1812 recommendation, if source is martian, * the only hint is MAC header. */ pr_warn("martian source %pI4 from %pI4, on dev %s\n", &daddr, &saddr, dev->name); if (dev->hard_header_len && skb_mac_header_was_set(skb)) { print_hex_dump(KERN_WARNING, "ll header: ", DUMP_PREFIX_OFFSET, 16, 1, skb_mac_header(skb), dev->hard_header_len, false); } } #endif } /* called in rcu_read_lock() section */ static int __mkroute_input(struct sk_buff *skb, const struct fib_result *res, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos) { struct fib_nh_exception *fnhe; struct rtable *rth; int err; struct in_device *out_dev; bool do_cache; u32 itag = 0; /* get a working reference to the output device */ out_dev = __in_dev_get_rcu(FIB_RES_DEV(*res)); if (!out_dev) { net_crit_ratelimited("Bug in ip_route_input_slow(). Please report.\n"); return -EINVAL; } err = fib_validate_source(skb, saddr, daddr, tos, FIB_RES_OIF(*res), in_dev->dev, in_dev, &itag); if (err < 0) { ip_handle_martian_source(in_dev->dev, in_dev, skb, daddr, saddr); goto cleanup; } do_cache = res->fi && !itag; if (out_dev == in_dev && err && IN_DEV_TX_REDIRECTS(out_dev) && skb->protocol == htons(ETH_P_IP) && (IN_DEV_SHARED_MEDIA(out_dev) || inet_addr_onlink(out_dev, saddr, FIB_RES_GW(*res)))) IPCB(skb)->flags |= IPSKB_DOREDIRECT; if (skb->protocol != htons(ETH_P_IP)) { /* Not IP (i.e. ARP). Do not create route, if it is * invalid for proxy arp. DNAT routes are always valid. * * Proxy arp feature have been extended to allow, ARP * replies back to the same interface, to support * Private VLAN switch technologies. See arp.c. */ if (out_dev == in_dev && IN_DEV_PROXY_ARP_PVLAN(in_dev) == 0) { err = -EINVAL; goto cleanup; } } fnhe = find_exception(&FIB_RES_NH(*res), daddr); if (do_cache) { if (fnhe) rth = rcu_dereference(fnhe->fnhe_rth_input); else rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); goto out; } } rth = rt_dst_alloc(out_dev->dev, 0, res->type, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(out_dev, NOXFRM), do_cache); if (!rth) { err = -ENOBUFS; goto cleanup; } rth->rt_is_input = 1; RT_CACHE_STAT_INC(in_slow_tot); rth->dst.input = ip_forward; rt_set_nexthop(rth, daddr, res, fnhe, res->fi, res->type, itag, do_cache); lwtunnel_set_redirect(&rth->dst); skb_dst_set(skb, &rth->dst); out: err = 0; cleanup: return err; } #ifdef CONFIG_IP_ROUTE_MULTIPATH /* To make ICMP packets follow the right flow, the multipath hash is * calculated from the inner IP addresses. */ static void ip_multipath_l3_keys(const struct sk_buff *skb, struct flow_keys *hash_keys) { const struct iphdr *outer_iph = ip_hdr(skb); const struct iphdr *key_iph = outer_iph; const struct iphdr *inner_iph; const struct icmphdr *icmph; struct iphdr _inner_iph; struct icmphdr _icmph; if (likely(outer_iph->protocol != IPPROTO_ICMP)) goto out; if (unlikely((outer_iph->frag_off & htons(IP_OFFSET)) != 0)) goto out; icmph = skb_header_pointer(skb, outer_iph->ihl * 4, sizeof(_icmph), &_icmph); if (!icmph) goto out; if (icmph->type != ICMP_DEST_UNREACH && icmph->type != ICMP_REDIRECT && icmph->type != ICMP_TIME_EXCEEDED && icmph->type != ICMP_PARAMETERPROB) goto out; inner_iph = skb_header_pointer(skb, outer_iph->ihl * 4 + sizeof(_icmph), sizeof(_inner_iph), &_inner_iph); if (!inner_iph) goto out; key_iph = inner_iph; out: hash_keys->addrs.v4addrs.src = key_iph->saddr; hash_keys->addrs.v4addrs.dst = key_iph->daddr; } /* if skb is set it will be used and fl4 can be NULL */ int fib_multipath_hash(const struct net *net, const struct flowi4 *fl4, const struct sk_buff *skb, struct flow_keys *flkeys) { u32 multipath_hash = fl4 ? fl4->flowi4_multipath_hash : 0; struct flow_keys hash_keys; u32 mhash; switch (net->ipv4.sysctl_fib_multipath_hash_policy) { case 0: memset(&hash_keys, 0, sizeof(hash_keys)); hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; if (skb) { ip_multipath_l3_keys(skb, &hash_keys); } else { hash_keys.addrs.v4addrs.src = fl4->saddr; hash_keys.addrs.v4addrs.dst = fl4->daddr; } break; case 1: /* skb is currently provided only when forwarding */ if (skb) { unsigned int flag = FLOW_DISSECTOR_F_STOP_AT_ENCAP; struct flow_keys keys; /* short-circuit if we already have L4 hash present */ if (skb->l4_hash) return skb_get_hash_raw(skb) >> 1; memset(&hash_keys, 0, sizeof(hash_keys)); if (!flkeys) { skb_flow_dissect_flow_keys(skb, &keys, flag); flkeys = &keys; } hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; hash_keys.addrs.v4addrs.src = flkeys->addrs.v4addrs.src; hash_keys.addrs.v4addrs.dst = flkeys->addrs.v4addrs.dst; hash_keys.ports.src = flkeys->ports.src; hash_keys.ports.dst = flkeys->ports.dst; hash_keys.basic.ip_proto = flkeys->basic.ip_proto; } else { memset(&hash_keys, 0, sizeof(hash_keys)); hash_keys.control.addr_type = FLOW_DISSECTOR_KEY_IPV4_ADDRS; hash_keys.addrs.v4addrs.src = fl4->saddr; hash_keys.addrs.v4addrs.dst = fl4->daddr; hash_keys.ports.src = fl4->fl4_sport; hash_keys.ports.dst = fl4->fl4_dport; hash_keys.basic.ip_proto = fl4->flowi4_proto; } break; } mhash = flow_hash_from_keys(&hash_keys); if (multipath_hash) mhash = jhash_2words(mhash, multipath_hash, 0); return mhash >> 1; } #endif /* CONFIG_IP_ROUTE_MULTIPATH */ static int ip_mkroute_input(struct sk_buff *skb, struct fib_result *res, struct in_device *in_dev, __be32 daddr, __be32 saddr, u32 tos, struct flow_keys *hkeys) { #ifdef CONFIG_IP_ROUTE_MULTIPATH if (res->fi && res->fi->fib_nhs > 1) { int h = fib_multipath_hash(res->fi->fib_net, NULL, skb, hkeys); fib_select_multipath(res, h); } #endif /* create a routing cache entry */ return __mkroute_input(skb, res, in_dev, daddr, saddr, tos); } /* * NOTE. We drop all the packets that has local source * addresses, because every properly looped back packet * must have correct destination already attached by output routine. * * Such approach solves two big problems: * 1. Not simplex devices are handled properly. * 2. IP spoofing attempts are filtered with 100% of guarantee. * called with rcu_read_lock() */ static int ip_route_input_slow(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct fib_result *res) { struct in_device *in_dev = __in_dev_get_rcu(dev); struct flow_keys *flkeys = NULL, _flkeys; struct net *net = dev_net(dev); struct ip_tunnel_info *tun_info; int err = -EINVAL; unsigned int flags = 0; u32 itag = 0; struct rtable *rth; struct flowi4 fl4; bool do_cache; /* IP on this device is disabled. */ if (!in_dev) goto out; /* Check for the most weird martians, which can be not detected by fib_lookup. */ tun_info = skb_tunnel_info(skb); if (tun_info && !(tun_info->mode & IP_TUNNEL_INFO_TX)) fl4.flowi4_tun_key.tun_id = tun_info->key.tun_id; else fl4.flowi4_tun_key.tun_id = 0; skb_dst_drop(skb); if (ipv4_is_multicast(saddr) || ipv4_is_lbcast(saddr)) goto martian_source; res->fi = NULL; res->table = NULL; if (ipv4_is_lbcast(daddr) || (saddr == 0 && daddr == 0)) goto brd_input; /* Accept zero addresses only to limited broadcast; * I even do not know to fix it or not. Waiting for complains :-) */ if (ipv4_is_zeronet(saddr)) goto martian_source; if (ipv4_is_zeronet(daddr)) goto martian_destination; /* Following code try to avoid calling IN_DEV_NET_ROUTE_LOCALNET(), * and call it once if daddr or/and saddr are loopback addresses */ if (ipv4_is_loopback(daddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_destination; } else if (ipv4_is_loopback(saddr)) { if (!IN_DEV_NET_ROUTE_LOCALNET(in_dev, net)) goto martian_source; } /* * Now we are ready to route packet. */ fl4.flowi4_oif = 0; fl4.flowi4_iif = dev->ifindex; fl4.flowi4_mark = skb->mark; fl4.flowi4_tos = tos; fl4.flowi4_scope = RT_SCOPE_UNIVERSE; fl4.flowi4_flags = 0; fl4.daddr = daddr; fl4.saddr = saddr; fl4.flowi4_uid = sock_net_uid(net, NULL); if (fib4_rules_early_flow_dissect(net, skb, &fl4, &_flkeys)) { flkeys = &_flkeys; } else { fl4.flowi4_proto = 0; fl4.fl4_sport = 0; fl4.fl4_dport = 0; } err = fib_lookup(net, &fl4, res, 0); if (err != 0) { if (!IN_DEV_FORWARD(in_dev)) err = -EHOSTUNREACH; goto no_route; } if (res->type == RTN_BROADCAST) { if (IN_DEV_BFORWARD(in_dev)) goto make_route; goto brd_input; } if (res->type == RTN_LOCAL) { err = fib_validate_source(skb, saddr, daddr, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; goto local_input; } if (!IN_DEV_FORWARD(in_dev)) { err = -EHOSTUNREACH; goto no_route; } if (res->type != RTN_UNICAST) goto martian_destination; make_route: err = ip_mkroute_input(skb, res, in_dev, daddr, saddr, tos, flkeys); out: return err; brd_input: if (skb->protocol != htons(ETH_P_IP)) goto e_inval; if (!ipv4_is_zeronet(saddr)) { err = fib_validate_source(skb, saddr, 0, tos, 0, dev, in_dev, &itag); if (err < 0) goto martian_source; } flags |= RTCF_BROADCAST; res->type = RTN_BROADCAST; RT_CACHE_STAT_INC(in_brd); local_input: do_cache = false; if (res->fi) { if (!itag) { rth = rcu_dereference(FIB_RES_NH(*res).nh_rth_input); if (rt_cache_valid(rth)) { skb_dst_set_noref(skb, &rth->dst); err = 0; goto out; } do_cache = true; } } rth = rt_dst_alloc(l3mdev_master_dev_rcu(dev) ? : net->loopback_dev, flags | RTCF_LOCAL, res->type, IN_DEV_CONF_GET(in_dev, NOPOLICY), false, do_cache); if (!rth) goto e_nobufs; rth->dst.output= ip_rt_bug; #ifdef CONFIG_IP_ROUTE_CLASSID rth->dst.tclassid = itag; #endif rth->rt_is_input = 1; RT_CACHE_STAT_INC(in_slow_tot); if (res->type == RTN_UNREACHABLE) { rth->dst.input= ip_error; rth->dst.error= -err; rth->rt_flags &= ~RTCF_LOCAL; } if (do_cache) { struct fib_nh *nh = &FIB_RES_NH(*res); rth->dst.lwtstate = lwtstate_get(nh->nh_lwtstate); if (lwtunnel_input_redirect(rth->dst.lwtstate)) { WARN_ON(rth->dst.input == lwtunnel_input); rth->dst.lwtstate->orig_input = rth->dst.input; rth->dst.input = lwtunnel_input; } if (unlikely(!rt_cache_route(nh, rth))) rt_add_uncached_list(rth); } skb_dst_set(skb, &rth->dst); err = 0; goto out; no_route: RT_CACHE_STAT_INC(in_no_route); res->type = RTN_UNREACHABLE; res->fi = NULL; res->table = NULL; goto local_input; /* * Do not cache martian addresses: they should be logged (RFC1812) */ martian_destination: RT_CACHE_STAT_INC(in_martian_dst); #ifdef CONFIG_IP_ROUTE_VERBOSE if (IN_DEV_LOG_MARTIANS(in_dev)) net_warn_ratelimited("martian destination %pI4 from %pI4, dev %s\n", &daddr, &saddr, dev->name); #endif e_inval: err = -EINVAL; goto out; e_nobufs: err = -ENOBUFS; goto out; martian_source: ip_handle_martian_source(dev, in_dev, skb, daddr, saddr); goto out; } int ip_route_input_noref(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev) { struct fib_result res; int err; tos &= IPTOS_RT_MASK; rcu_read_lock(); err = ip_route_input_rcu(skb, daddr, saddr, tos, dev, &res); rcu_read_unlock(); return err; } EXPORT_SYMBOL(ip_route_input_noref); /* called with rcu_read_lock held */ int ip_route_input_rcu(struct sk_buff *skb, __be32 daddr, __be32 saddr, u8 tos, struct net_device *dev, struct fib_result *res) { /* Multicast recognition logic is moved from route cache to here. The problem was that too many Ethernet cards have broken/missing hardware multicast filters :-( As result the host on multicasting network acquires a lot of useless route cache entries, sort of SDR messages from all the world. Now we try to get rid of them. Really, provided software IP multicast filter is organized reasonably (at least, hashed), it does not result in a slowdown comparing with route cache reject entries. Note, that multicast routers are not affected, because route cache entry is created eventually. */ if (ipv4_is_multicast(daddr)) { struct in_device *in_dev = __in_dev_get_rcu(dev); int our = 0; int err = -EINVAL; if (!in_dev) return err; our = ip_check_mc_rcu(in_dev, daddr, saddr, ip_hdr(skb)->protocol); /* check l3 master if no match yet */ if (!our && netif_is_l3_slave(dev)) { struct in_device *l3_in_dev; l3_in_dev = __in_dev_get_rcu(skb->dev); if (l3_in_dev) our = ip_check_mc_rcu(l3_in_dev, daddr, saddr, ip_hdr(skb)->protocol); } if (our #ifdef CONFIG_IP_MROUTE || (!ipv4_is_local_multicast(daddr) && IN_DEV_MFORWARD(in_dev)) #endif ) { err = ip_route_input_mc(skb, daddr, saddr, tos, dev, our); } return err; } return ip_route_input_slow(skb, daddr, saddr, tos, dev, res); } /* called with rcu_read_lock() */ static struct rtable *__mkroute_output(const struct fib_result *res, const struct flowi4 *fl4, int orig_oif, struct net_device *dev_out, unsigned int flags) { struct fib_info *fi = res->fi; struct fib_nh_exception *fnhe; struct in_device *in_dev; u16 type = res->type; struct rtable *rth; bool do_cache; in_dev = __in_dev_get_rcu(dev_out); if (!in_dev) return ERR_PTR(-EINVAL); if (likely(!IN_DEV_ROUTE_LOCALNET(in_dev))) if (ipv4_is_loopback(fl4->saddr) && !(dev_out->flags & IFF_LOOPBACK) && !netif_is_l3_master(dev_out)) return ERR_PTR(-EINVAL); if (ipv4_is_lbcast(fl4->daddr)) type = RTN_BROADCAST; else if (ipv4_is_multicast(fl4->daddr)) type = RTN_MULTICAST; else if (ipv4_is_zeronet(fl4->daddr)) return ERR_PTR(-EINVAL); if (dev_out->flags & IFF_LOOPBACK) flags |= RTCF_LOCAL; do_cache = true; if (type == RTN_BROADCAST) { flags |= RTCF_BROADCAST | RTCF_LOCAL; fi = NULL; } else if (type == RTN_MULTICAST) { flags |= RTCF_MULTICAST | RTCF_LOCAL; if (!ip_check_mc_rcu(in_dev, fl4->daddr, fl4->saddr, fl4->flowi4_proto)) flags &= ~RTCF_LOCAL; else do_cache = false; /* If multicast route do not exist use * default one, but do not gateway in this case. * Yes, it is hack. */ if (fi && res->prefixlen < 4) fi = NULL; } else if ((type == RTN_LOCAL) && (orig_oif != 0) && (orig_oif != dev_out->ifindex)) { /* For local routes that require a particular output interface * we do not want to cache the result. Caching the result * causes incorrect behaviour when there are multiple source * addresses on the interface, the end result being that if the * intended recipient is waiting on that interface for the * packet he won't receive it because it will be delivered on * the loopback interface and the IP_PKTINFO ipi_ifindex will * be set to the loopback interface as well. */ do_cache = false; } fnhe = NULL; do_cache &= fi != NULL; if (fi) { struct rtable __rcu **prth; struct fib_nh *nh = &FIB_RES_NH(*res); fnhe = find_exception(nh, fl4->daddr); if (!do_cache) goto add; if (fnhe) { prth = &fnhe->fnhe_rth_output; } else { if (unlikely(fl4->flowi4_flags & FLOWI_FLAG_KNOWN_NH && !(nh->nh_gw && nh->nh_scope == RT_SCOPE_LINK))) { do_cache = false; goto add; } prth = raw_cpu_ptr(nh->nh_pcpu_rth_output); } rth = rcu_dereference(*prth); if (rt_cache_valid(rth) && dst_hold_safe(&rth->dst)) return rth; } add: rth = rt_dst_alloc(dev_out, flags, type, IN_DEV_CONF_GET(in_dev, NOPOLICY), IN_DEV_CONF_GET(in_dev, NOXFRM), do_cache); if (!rth) return ERR_PTR(-ENOBUFS); rth->rt_iif = orig_oif; RT_CACHE_STAT_INC(out_slow_tot); if (flags & (RTCF_BROADCAST | RTCF_MULTICAST)) { if (flags & RTCF_LOCAL && !(dev_out->flags & IFF_LOOPBACK)) { rth->dst.output = ip_mc_output; RT_CACHE_STAT_INC(out_slow_mc); } #ifdef CONFIG_IP_MROUTE if (type == RTN_MULTICAST) { if (IN_DEV_MFORWARD(in_dev) && !ipv4_is_local_multicast(fl4->daddr)) { rth->dst.input = ip_mr_input; rth->dst.output = ip_mc_output; } } #endif } rt_set_nexthop(rth, fl4->daddr, res, fnhe, fi, type, 0, do_cache); lwtunnel_set_redirect(&rth->dst); return rth; } /* * Major route resolver routine. */ struct rtable *ip_route_output_key_hash(struct net *net, struct flowi4 *fl4, const struct sk_buff *skb) { __u8 tos = RT_FL_TOS(fl4); struct fib_result res = { .type = RTN_UNSPEC, .fi = NULL, .table = NULL, .tclassid = 0, }; struct rtable *rth; fl4->flowi4_iif = LOOPBACK_IFINDEX; fl4->flowi4_tos = tos & IPTOS_RT_MASK; fl4->flowi4_scope = ((tos & RTO_ONLINK) ? RT_SCOPE_LINK : RT_SCOPE_UNIVERSE); rcu_read_lock(); rth = ip_route_output_key_hash_rcu(net, fl4, &res, skb); rcu_read_unlock(); return rth; } EXPORT_SYMBOL_GPL(ip_route_output_key_hash); struct rtable *ip_route_output_key_hash_rcu(struct net *net, struct flowi4 *fl4, struct fib_result *res, const struct sk_buff *skb) { struct net_device *dev_out = NULL; int orig_oif = fl4->flowi4_oif; unsigned int flags = 0; struct rtable *rth; int err = -ENETUNREACH; if (fl4->saddr) { rth = ERR_PTR(-EINVAL); if (ipv4_is_multicast(fl4->saddr) || ipv4_is_lbcast(fl4->saddr) || ipv4_is_zeronet(fl4->saddr)) goto out; /* I removed check for oif == dev_out->oif here. It was wrong for two reasons: 1. ip_dev_find(net, saddr) can return wrong iface, if saddr is assigned to multiple interfaces. 2. Moreover, we are allowed to send packets with saddr of another iface. --ANK */ if (fl4->flowi4_oif == 0 && (ipv4_is_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr))) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ dev_out = __ip_dev_find(net, fl4->saddr, false); if (!dev_out) goto out; /* Special hack: user can direct multicasts and limited broadcast via necessary interface without fiddling with IP_MULTICAST_IF or IP_PKTINFO. This hack is not just for fun, it allows vic,vat and friends to work. They bind socket to loopback, set ttl to zero and expect that it will work. From the viewpoint of routing cache they are broken, because we are not allowed to build multicast path with loopback source addr (look, routing cache cannot know, that ttl is zero, so that packet will not leave this host and route is valid). Luckily, this hack is good workaround. */ fl4->flowi4_oif = dev_out->ifindex; goto make_route; } if (!(fl4->flowi4_flags & FLOWI_FLAG_ANYSRC)) { /* It is equivalent to inet_addr_type(saddr) == RTN_LOCAL */ if (!__ip_dev_find(net, fl4->saddr, false)) goto out; } } if (fl4->flowi4_oif) { dev_out = dev_get_by_index_rcu(net, fl4->flowi4_oif); rth = ERR_PTR(-ENODEV); if (!dev_out) goto out; /* RACE: Check return value of inet_select_addr instead. */ if (!(dev_out->flags & IFF_UP) || !__in_dev_get_rcu(dev_out)) { rth = ERR_PTR(-ENETUNREACH); goto out; } if (ipv4_is_local_multicast(fl4->daddr) || ipv4_is_lbcast(fl4->daddr) || fl4->flowi4_proto == IPPROTO_IGMP) { if (!fl4->saddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); goto make_route; } if (!fl4->saddr) { if (ipv4_is_multicast(fl4->daddr)) fl4->saddr = inet_select_addr(dev_out, 0, fl4->flowi4_scope); else if (!fl4->daddr) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_HOST); } } if (!fl4->daddr) { fl4->daddr = fl4->saddr; if (!fl4->daddr) fl4->daddr = fl4->saddr = htonl(INADDR_LOOPBACK); dev_out = net->loopback_dev; fl4->flowi4_oif = LOOPBACK_IFINDEX; res->type = RTN_LOCAL; flags |= RTCF_LOCAL; goto make_route; } err = fib_lookup(net, fl4, res, 0); if (err) { res->fi = NULL; res->table = NULL; if (fl4->flowi4_oif && (ipv4_is_multicast(fl4->daddr) || !netif_index_is_l3_master(net, fl4->flowi4_oif))) { /* Apparently, routing tables are wrong. Assume, that the destination is on link. WHY? DW. Because we are allowed to send to iface even if it has NO routes and NO assigned addresses. When oif is specified, routing tables are looked up with only one purpose: to catch if destination is gatewayed, rather than direct. Moreover, if MSG_DONTROUTE is set, we send packet, ignoring both routing tables and ifaddr state. --ANK We could make it even if oif is unknown, likely IPv6, but we do not. */ if (fl4->saddr == 0) fl4->saddr = inet_select_addr(dev_out, 0, RT_SCOPE_LINK); res->type = RTN_UNICAST; goto make_route; } rth = ERR_PTR(err); goto out; } if (res->type == RTN_LOCAL) { if (!fl4->saddr) { if (res->fi->fib_prefsrc) fl4->saddr = res->fi->fib_prefsrc; else fl4->saddr = fl4->daddr; } /* L3 master device is the loopback for that domain */ dev_out = l3mdev_master_dev_rcu(FIB_RES_DEV(*res)) ? : net->loopback_dev; /* make sure orig_oif points to fib result device even * though packet rx/tx happens over loopback or l3mdev */ orig_oif = FIB_RES_OIF(*res); fl4->flowi4_oif = dev_out->ifindex; flags |= RTCF_LOCAL; goto make_route; } fib_select_path(net, res, fl4, skb); dev_out = FIB_RES_DEV(*res); fl4->flowi4_oif = dev_out->ifindex; make_route: rth = __mkroute_output(res, fl4, orig_oif, dev_out, flags); out: return rth; } static struct dst_entry *ipv4_blackhole_dst_check(struct dst_entry *dst, u32 cookie) { return NULL; } static unsigned int ipv4_blackhole_mtu(const struct dst_entry *dst) { unsigned int mtu = dst_metric_raw(dst, RTAX_MTU); return mtu ? : dst->dev->mtu; } static void ipv4_rt_blackhole_update_pmtu(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb, u32 mtu) { } static void ipv4_rt_blackhole_redirect(struct dst_entry *dst, struct sock *sk, struct sk_buff *skb) { } static u32 *ipv4_rt_blackhole_cow_metrics(struct dst_entry *dst, unsigned long old) { return NULL; } static struct dst_ops ipv4_dst_blackhole_ops = { .family = AF_INET, .check = ipv4_blackhole_dst_check, .mtu = ipv4_blackhole_mtu, .default_advmss = ipv4_default_advmss, .update_pmtu = ipv4_rt_blackhole_update_pmtu, .redirect = ipv4_rt_blackhole_redirect, .cow_metrics = ipv4_rt_blackhole_cow_metrics, .neigh_lookup = ipv4_neigh_lookup, }; struct dst_entry *ipv4_blackhole_route(struct net *net, struct dst_entry *dst_orig) { struct rtable *ort = (struct rtable *) dst_orig; struct rtable *rt; rt = dst_alloc(&ipv4_dst_blackhole_ops, NULL, 1, DST_OBSOLETE_DEAD, 0); if (rt) { struct dst_entry *new = &rt->dst; new->__use = 1; new->input = dst_discard; new->output = dst_discard_out; new->dev = net->loopback_dev; if (new->dev) dev_hold(new->dev); rt->rt_is_input = ort->rt_is_input; rt->rt_iif = ort->rt_iif; rt->rt_pmtu = ort->rt_pmtu; rt->rt_mtu_locked = ort->rt_mtu_locked; rt->rt_genid = rt_genid_ipv4(net); rt->rt_flags = ort->rt_flags; rt->rt_type = ort->rt_type; rt->rt_gateway = ort->rt_gateway; rt->rt_uses_gateway = ort->rt_uses_gateway; INIT_LIST_HEAD(&rt->rt_uncached); } dst_release(dst_orig); return rt ? &rt->dst : ERR_PTR(-ENOMEM); } struct rtable *ip_route_output_flow(struct net *net, struct flowi4 *flp4, const struct sock *sk) { struct rtable *rt = __ip_route_output_key(net, flp4); if (IS_ERR(rt)) return rt; if (flp4->flowi4_proto) rt = (struct rtable *)xfrm_lookup_route(net, &rt->dst, flowi4_to_flowi(flp4), sk, 0); return rt; } EXPORT_SYMBOL_GPL(ip_route_output_flow); /* called with rcu_read_lock held */ static int rt_fill_info(struct net *net, __be32 dst, __be32 src, struct rtable *rt, u32 table_id, struct flowi4 *fl4, struct sk_buff *skb, u32 portid, u32 seq) { struct rtmsg *r; struct nlmsghdr *nlh; unsigned long expires = 0; u32 error; u32 metrics[RTAX_MAX]; nlh = nlmsg_put(skb, portid, seq, RTM_NEWROUTE, sizeof(*r), 0); if (!nlh) return -EMSGSIZE; r = nlmsg_data(nlh); r->rtm_family = AF_INET; r->rtm_dst_len = 32; r->rtm_src_len = 0; r->rtm_tos = fl4->flowi4_tos; r->rtm_table = table_id < 256 ? table_id : RT_TABLE_COMPAT; if (nla_put_u32(skb, RTA_TABLE, table_id)) goto nla_put_failure; r->rtm_type = rt->rt_type; r->rtm_scope = RT_SCOPE_UNIVERSE; r->rtm_protocol = RTPROT_UNSPEC; r->rtm_flags = (rt->rt_flags & ~0xFFFF) | RTM_F_CLONED; if (rt->rt_flags & RTCF_NOTIFY) r->rtm_flags |= RTM_F_NOTIFY; if (IPCB(skb)->flags & IPSKB_DOREDIRECT) r->rtm_flags |= RTCF_DOREDIRECT; if (nla_put_in_addr(skb, RTA_DST, dst)) goto nla_put_failure; if (src) { r->rtm_src_len = 32; if (nla_put_in_addr(skb, RTA_SRC, src)) goto nla_put_failure; } if (rt->dst.dev && nla_put_u32(skb, RTA_OIF, rt->dst.dev->ifindex)) goto nla_put_failure; #ifdef CONFIG_IP_ROUTE_CLASSID if (rt->dst.tclassid && nla_put_u32(skb, RTA_FLOW, rt->dst.tclassid)) goto nla_put_failure; #endif if (!rt_is_input_route(rt) && fl4->saddr != src) { if (nla_put_in_addr(skb, RTA_PREFSRC, fl4->saddr)) goto nla_put_failure; } if (rt->rt_uses_gateway && nla_put_in_addr(skb, RTA_GATEWAY, rt->rt_gateway)) goto nla_put_failure; expires = rt->dst.expires; if (expires) { unsigned long now = jiffies; if (time_before(now, expires)) expires -= now; else expires = 0; } memcpy(metrics, dst_metrics_ptr(&rt->dst), sizeof(metrics)); if (rt->rt_pmtu && expires) metrics[RTAX_MTU - 1] = rt->rt_pmtu; if (rt->rt_mtu_locked && expires) metrics[RTAX_LOCK - 1] |= BIT(RTAX_MTU); if (rtnetlink_put_metrics(skb, metrics) < 0) goto nla_put_failure; if (fl4->flowi4_mark && nla_put_u32(skb, RTA_MARK, fl4->flowi4_mark)) goto nla_put_failure; if (!uid_eq(fl4->flowi4_uid, INVALID_UID) && nla_put_u32(skb, RTA_UID, from_kuid_munged(current_user_ns(), fl4->flowi4_uid))) goto nla_put_failure; error = rt->dst.error; if (rt_is_input_route(rt)) { #ifdef CONFIG_IP_MROUTE if (ipv4_is_multicast(dst) && !ipv4_is_local_multicast(dst) && IPV4_DEVCONF_ALL(net, MC_FORWARDING)) { int err = ipmr_get_route(net, skb, fl4->saddr, fl4->daddr, r, portid); if (err <= 0) { if (err == 0) return 0; goto nla_put_failure; } } else #endif if (nla_put_u32(skb, RTA_IIF, fl4->flowi4_iif)) goto nla_put_failure; } if (rtnl_put_cacheinfo(skb, &rt->dst, 0, expires, error) < 0) goto nla_put_failure; nlmsg_end(skb, nlh); return 0; nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static struct sk_buff *inet_rtm_getroute_build_skb(__be32 src, __be32 dst, u8 ip_proto, __be16 sport, __be16 dport) { struct sk_buff *skb; struct iphdr *iph; skb = alloc_skb(NLMSG_GOODSIZE, GFP_KERNEL); if (!skb) return NULL; /* Reserve room for dummy headers, this skb can pass * through good chunk of routing engine. */ skb_reset_mac_header(skb); skb_reset_network_header(skb); skb->protocol = htons(ETH_P_IP); iph = skb_put(skb, sizeof(struct iphdr)); iph->protocol = ip_proto; iph->saddr = src; iph->daddr = dst; iph->version = 0x4; iph->frag_off = 0; iph->ihl = 0x5; skb_set_transport_header(skb, skb->len); switch (iph->protocol) { case IPPROTO_UDP: { struct udphdr *udph; udph = skb_put_zero(skb, sizeof(struct udphdr)); udph->source = sport; udph->dest = dport; udph->len = sizeof(struct udphdr); udph->check = 0; break; } case IPPROTO_TCP: { struct tcphdr *tcph; tcph = skb_put_zero(skb, sizeof(struct tcphdr)); tcph->source = sport; tcph->dest = dport; tcph->doff = sizeof(struct tcphdr) / 4; tcph->rst = 1; tcph->check = ~tcp_v4_check(sizeof(struct tcphdr), src, dst, 0); break; } case IPPROTO_ICMP: { struct icmphdr *icmph; icmph = skb_put_zero(skb, sizeof(struct icmphdr)); icmph->type = ICMP_ECHO; icmph->code = 0; } } return skb; } static int inet_rtm_valid_getroute_req(struct sk_buff *skb, const struct nlmsghdr *nlh, struct nlattr **tb, struct netlink_ext_ack *extack) { struct rtmsg *rtm; int i, err; if (nlh->nlmsg_len < nlmsg_msg_size(sizeof(*rtm))) { NL_SET_ERR_MSG(extack, "ipv4: Invalid header for route get request"); return -EINVAL; } if (!netlink_strict_get_check(skb)) return nlmsg_parse(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); rtm = nlmsg_data(nlh); if ((rtm->rtm_src_len && rtm->rtm_src_len != 32) || (rtm->rtm_dst_len && rtm->rtm_dst_len != 32) || rtm->rtm_table || rtm->rtm_protocol || rtm->rtm_scope || rtm->rtm_type) { NL_SET_ERR_MSG(extack, "ipv4: Invalid values in header for route get request"); return -EINVAL; } if (rtm->rtm_flags & ~(RTM_F_NOTIFY | RTM_F_LOOKUP_TABLE | RTM_F_FIB_MATCH)) { NL_SET_ERR_MSG(extack, "ipv4: Unsupported rtm_flags for route get request"); return -EINVAL; } err = nlmsg_parse_strict(nlh, sizeof(*rtm), tb, RTA_MAX, rtm_ipv4_policy, extack); if (err) return err; if ((tb[RTA_SRC] && !rtm->rtm_src_len) || (tb[RTA_DST] && !rtm->rtm_dst_len)) { NL_SET_ERR_MSG(extack, "ipv4: rtm_src_len and rtm_dst_len must be 32 for IPv4"); return -EINVAL; } for (i = 0; i <= RTA_MAX; i++) { if (!tb[i]) continue; switch (i) { case RTA_IIF: case RTA_OIF: case RTA_SRC: case RTA_DST: case RTA_IP_PROTO: case RTA_SPORT: case RTA_DPORT: case RTA_MARK: case RTA_UID: break; default: NL_SET_ERR_MSG(extack, "ipv4: Unsupported attribute in route get request"); return -EINVAL; } } return 0; } static int inet_rtm_getroute(struct sk_buff *in_skb, struct nlmsghdr *nlh, struct netlink_ext_ack *extack) { struct net *net = sock_net(in_skb->sk); struct nlattr *tb[RTA_MAX+1]; u32 table_id = RT_TABLE_MAIN; __be16 sport = 0, dport = 0; struct fib_result res = {}; u8 ip_proto = IPPROTO_UDP; struct rtable *rt = NULL; struct sk_buff *skb; struct rtmsg *rtm; struct flowi4 fl4 = {}; __be32 dst = 0; __be32 src = 0; kuid_t uid; u32 iif; int err; int mark; err = inet_rtm_valid_getroute_req(in_skb, nlh, tb, extack); if (err < 0) return err; rtm = nlmsg_data(nlh); src = tb[RTA_SRC] ? nla_get_in_addr(tb[RTA_SRC]) : 0; dst = tb[RTA_DST] ? nla_get_in_addr(tb[RTA_DST]) : 0; iif = tb[RTA_IIF] ? nla_get_u32(tb[RTA_IIF]) : 0; mark = tb[RTA_MARK] ? nla_get_u32(tb[RTA_MARK]) : 0; if (tb[RTA_UID]) uid = make_kuid(current_user_ns(), nla_get_u32(tb[RTA_UID])); else uid = (iif ? INVALID_UID : current_uid()); if (tb[RTA_IP_PROTO]) { err = rtm_getroute_parse_ip_proto(tb[RTA_IP_PROTO], &ip_proto, AF_INET, extack); if (err) return err; } if (tb[RTA_SPORT]) sport = nla_get_be16(tb[RTA_SPORT]); if (tb[RTA_DPORT]) dport = nla_get_be16(tb[RTA_DPORT]); skb = inet_rtm_getroute_build_skb(src, dst, ip_proto, sport, dport); if (!skb) return -ENOBUFS; fl4.daddr = dst; fl4.saddr = src; fl4.flowi4_tos = rtm->rtm_tos; fl4.flowi4_oif = tb[RTA_OIF] ? nla_get_u32(tb[RTA_OIF]) : 0; fl4.flowi4_mark = mark; fl4.flowi4_uid = uid; if (sport) fl4.fl4_sport = sport; if (dport) fl4.fl4_dport = dport; fl4.flowi4_proto = ip_proto; rcu_read_lock(); if (iif) { struct net_device *dev; dev = dev_get_by_index_rcu(net, iif); if (!dev) { err = -ENODEV; goto errout_rcu; } fl4.flowi4_iif = iif; /* for rt_fill_info */ skb->dev = dev; skb->mark = mark; err = ip_route_input_rcu(skb, dst, src, rtm->rtm_tos, dev, &res); rt = skb_rtable(skb); if (err == 0 && rt->dst.error) err = -rt->dst.error; } else { fl4.flowi4_iif = LOOPBACK_IFINDEX; skb->dev = net->loopback_dev; rt = ip_route_output_key_hash_rcu(net, &fl4, &res, skb); err = 0; if (IS_ERR(rt)) err = PTR_ERR(rt); else skb_dst_set(skb, &rt->dst); } if (err) goto errout_rcu; if (rtm->rtm_flags & RTM_F_NOTIFY) rt->rt_flags |= RTCF_NOTIFY; if (rtm->rtm_flags & RTM_F_LOOKUP_TABLE) table_id = res.table ? res.table->tb_id : 0; /* reset skb for netlink reply msg */ skb_trim(skb, 0); skb_reset_network_header(skb); skb_reset_transport_header(skb); skb_reset_mac_header(skb); if (rtm->rtm_flags & RTM_F_FIB_MATCH) { if (!res.fi) { err = fib_props[res.type].error; if (!err) err = -EHOSTUNREACH; goto errout_rcu; } err = fib_dump_info(skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq, RTM_NEWROUTE, table_id, rt->rt_type, res.prefix, res.prefixlen, fl4.flowi4_tos, res.fi, 0); } else { err = rt_fill_info(net, dst, src, rt, table_id, &fl4, skb, NETLINK_CB(in_skb).portid, nlh->nlmsg_seq); } if (err < 0) goto errout_rcu; rcu_read_unlock(); err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).portid); errout_free: return err; errout_rcu: rcu_read_unlock(); kfree_skb(skb); goto errout_free; } void ip_rt_multicast_event(struct in_device *in_dev) { rt_cache_flush(dev_net(in_dev->dev)); } #ifdef CONFIG_SYSCTL static int ip_rt_gc_interval __read_mostly = 60 * HZ; static int ip_rt_gc_min_interval __read_mostly = HZ / 2; static int ip_rt_gc_elasticity __read_mostly = 8; static int ip_min_valid_pmtu __read_mostly = IPV4_MIN_MTU; static int ipv4_sysctl_rtcache_flush(struct ctl_table *__ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net *net = (struct net *)__ctl->extra1; if (write) { rt_cache_flush(net); fnhe_genid_bump(net); return 0; } return -EINVAL; } static struct ctl_table ipv4_route_table[] = { { .procname = "gc_thresh", .data = &ipv4_dst_ops.gc_thresh, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_size", .data = &ip_rt_max_size, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { /* Deprecated. Use gc_min_interval_ms */ .procname = "gc_min_interval", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_min_interval_ms", .data = &ip_rt_gc_min_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_ms_jiffies, }, { .procname = "gc_timeout", .data = &ip_rt_gc_timeout, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "gc_interval", .data = &ip_rt_gc_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "redirect_load", .data = &ip_rt_redirect_load, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_number", .data = &ip_rt_redirect_number, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "redirect_silence", .data = &ip_rt_redirect_silence, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_cost", .data = &ip_rt_error_cost, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "error_burst", .data = &ip_rt_error_burst, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "gc_elasticity", .data = &ip_rt_gc_elasticity, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mtu_expires", .data = &ip_rt_mtu_expires, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "min_pmtu", .data = &ip_rt_min_pmtu, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &ip_min_valid_pmtu, }, { .procname = "min_adv_mss", .data = &ip_rt_min_advmss, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { } }; static struct ctl_table ipv4_route_flush_table[] = { { .procname = "flush", .maxlen = sizeof(int), .mode = 0200, .proc_handler = ipv4_sysctl_rtcache_flush, }, { }, }; static __net_init int sysctl_route_net_init(struct net *net) { struct ctl_table *tbl; tbl = ipv4_route_flush_table; if (!net_eq(net, &init_net)) { tbl = kmemdup(tbl, sizeof(ipv4_route_flush_table), GFP_KERNEL); if (!tbl) goto err_dup; /* Don't export sysctls to unprivileged users */ if (net->user_ns != &init_user_ns) tbl[0].procname = NULL; } tbl[0].extra1 = net; net->ipv4.route_hdr = register_net_sysctl(net, "net/ipv4/route", tbl); if (!net->ipv4.route_hdr) goto err_reg; return 0; err_reg: if (tbl != ipv4_route_flush_table) kfree(tbl); err_dup: return -ENOMEM; } static __net_exit void sysctl_route_net_exit(struct net *net) { struct ctl_table *tbl; tbl = net->ipv4.route_hdr->ctl_table_arg; unregister_net_sysctl_table(net->ipv4.route_hdr); BUG_ON(tbl == ipv4_route_flush_table); kfree(tbl); } static __net_initdata struct pernet_operations sysctl_route_ops = { .init = sysctl_route_net_init, .exit = sysctl_route_net_exit, }; #endif static __net_init int rt_genid_init(struct net *net) { atomic_set(&net->ipv4.rt_genid, 0); atomic_set(&net->fnhe_genid, 0); atomic_set(&net->ipv4.dev_addr_genid, get_random_int()); return 0; } static __net_initdata struct pernet_operations rt_genid_ops = { .init = rt_genid_init, }; static int __net_init ipv4_inetpeer_init(struct net *net) { struct inet_peer_base *bp = kmalloc(sizeof(*bp), GFP_KERNEL); if (!bp) return -ENOMEM; inet_peer_base_init(bp); net->ipv4.peers = bp; return 0; } static void __net_exit ipv4_inetpeer_exit(struct net *net) { struct inet_peer_base *bp = net->ipv4.peers; net->ipv4.peers = NULL; inetpeer_invalidate_tree(bp); kfree(bp); } static __net_initdata struct pernet_operations ipv4_inetpeer_ops = { .init = ipv4_inetpeer_init, .exit = ipv4_inetpeer_exit, }; #ifdef CONFIG_IP_ROUTE_CLASSID struct ip_rt_acct __percpu *ip_rt_acct __read_mostly; #endif /* CONFIG_IP_ROUTE_CLASSID */ int __init ip_rt_init(void) { int cpu; ip_idents = kmalloc_array(IP_IDENTS_SZ, sizeof(*ip_idents), GFP_KERNEL); if (!ip_idents) panic("IP: failed to allocate ip_idents\n"); prandom_bytes(ip_idents, IP_IDENTS_SZ * sizeof(*ip_idents)); ip_tstamps = kcalloc(IP_IDENTS_SZ, sizeof(*ip_tstamps), GFP_KERNEL); if (!ip_tstamps) panic("IP: failed to allocate ip_tstamps\n"); for_each_possible_cpu(cpu) { struct uncached_list *ul = &per_cpu(rt_uncached_list, cpu); INIT_LIST_HEAD(&ul->head); spin_lock_init(&ul->lock); } #ifdef CONFIG_IP_ROUTE_CLASSID ip_rt_acct = __alloc_percpu(256 * sizeof(struct ip_rt_acct), __alignof__(struct ip_rt_acct)); if (!ip_rt_acct) panic("IP: failed to allocate ip_rt_acct\n"); #endif ipv4_dst_ops.kmem_cachep = kmem_cache_create("ip_dst_cache", sizeof(struct rtable), 0, SLAB_HWCACHE_ALIGN|SLAB_PANIC, NULL); ipv4_dst_blackhole_ops.kmem_cachep = ipv4_dst_ops.kmem_cachep; if (dst_entries_init(&ipv4_dst_ops) < 0) panic("IP: failed to allocate ipv4_dst_ops counter\n"); if (dst_entries_init(&ipv4_dst_blackhole_ops) < 0) panic("IP: failed to allocate ipv4_dst_blackhole_ops counter\n"); ipv4_dst_ops.gc_thresh = ~0; ip_rt_max_size = INT_MAX; devinet_init(); ip_fib_init(); if (ip_rt_proc_init()) pr_err("Unable to create route proc files\n"); #ifdef CONFIG_XFRM xfrm_init(); xfrm4_init(); #endif rtnl_register(PF_INET, RTM_GETROUTE, inet_rtm_getroute, NULL, RTNL_FLAG_DOIT_UNLOCKED); #ifdef CONFIG_SYSCTL register_pernet_subsys(&sysctl_route_ops); #endif register_pernet_subsys(&rt_genid_ops); register_pernet_subsys(&ipv4_inetpeer_ops); return 0; } #ifdef CONFIG_SYSCTL /* * We really need to sanitize the damn ipv4 init order, then all * this nonsense will go away. */ void __init ip_static_sysctl_init(void) { register_net_sysctl(&init_net, "net/ipv4/route", ipv4_route_table); } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/bad_760_2
crossvul-cpp_data_good_3568_10
/* -*- Mode: c; c-basic-offset: 2 -*- * * raptor_turtle_writer.c - Raptor Turtle Writer * * Copyright (C) 2006, Dave Robillard * Copyright (C) 2003-2008, David Beckett http://www.dajobe.org/ * Copyright (C) 2003-2005, University of Bristol, UK http://www.bristol.ac.uk/ * * This package is Free Software and part of Redland http://librdf.org/ * * It is licensed under the following three licenses as alternatives: * 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version * 2. GNU General Public License (GPL) V2 or any newer version * 3. Apache License, V2.0 or any newer version * * You may not use this file except in compliance with at least one of * the above three licenses. * * See LICENSE.html or LICENSE.txt at the top of this package for the * complete terms and further detail along with the license texts for * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively. * * */ #ifdef HAVE_CONFIG_H #include <raptor_config.h> #endif #ifdef WIN32 #include <win32_raptor_config.h> #endif #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #ifdef HAVE_ERRNO_H #include <errno.h> #endif #ifdef HAVE_STDLIB_H #include <stdlib.h> #endif #ifdef HAVE_LIMITS_H #include <limits.h> #endif #include <math.h> /* Raptor includes */ #include "raptor2.h" #include "raptor_internal.h" #ifndef STANDALONE typedef enum { TURTLE_WRITER_AUTO_INDENT = 1, } raptor_turtle_writer_flags; #define TURTLE_WRITER_AUTO_INDENT(turtle_writer) ((turtle_writer->flags & TURTLE_WRITER_AUTO_INDENT) != 0) struct raptor_turtle_writer_s { raptor_world* world; int depth; raptor_uri* base_uri; int my_nstack; raptor_namespace_stack *nstack; int nstack_depth; /* outputting to this iostream */ raptor_iostream *iostr; /* Turtle Writer flags - bits defined in enum raptor_turtle_writer_flags */ int flags; /* indentation per level if formatting */ int indent; raptor_uri* xsd_boolean_uri; raptor_uri* xsd_decimal_uri; raptor_uri* xsd_double_uri; raptor_uri* xsd_integer_uri; }; /* 16 spaces */ #define SPACES_BUFFER_SIZE sizeof(spaces_buffer) static const unsigned char spaces_buffer[] = { ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ' }; void raptor_turtle_writer_increase_indent(raptor_turtle_writer *turtle_writer) { turtle_writer->depth += turtle_writer->indent; } void raptor_turtle_writer_decrease_indent(raptor_turtle_writer *turtle_writer) { turtle_writer->depth -= turtle_writer->indent; } void raptor_turtle_writer_newline(raptor_turtle_writer *turtle_writer) { int num_spaces; raptor_iostream_write_byte('\n', turtle_writer->iostr); if(!TURTLE_WRITER_AUTO_INDENT(turtle_writer)) return; num_spaces = turtle_writer->depth * turtle_writer->indent; while(num_spaces > 0) { int count; count = (num_spaces > RAPTOR_GOOD_CAST(int, SPACES_BUFFER_SIZE)) ? RAPTOR_GOOD_CAST(int, SPACES_BUFFER_SIZE) : num_spaces; raptor_iostream_counted_string_write(spaces_buffer, count, turtle_writer->iostr); num_spaces -= count; } return; } /** * raptor_new_turtle_writer: * @world: raptor_world object * @base_uri: Base URI for the writer (or NULL) * @write_base_uri: non-0 to write '@base' directive to output * @nstack: Namespace stack for the writer to start with (or NULL) * @iostr: I/O stream to write to * * Constructor - Create a new Turtle Writer writing Turtle to a raptor_iostream * * Return value: a new #raptor_turtle_writer object or NULL on failure **/ raptor_turtle_writer* raptor_new_turtle_writer(raptor_world* world, raptor_uri* base_uri, int write_base_uri, raptor_namespace_stack *nstack, raptor_iostream* iostr) { raptor_turtle_writer* turtle_writer; RAPTOR_CHECK_CONSTRUCTOR_WORLD(world); if(!nstack || !iostr) return NULL; raptor_world_open(world); turtle_writer = RAPTOR_CALLOC(raptor_turtle_writer*, 1, sizeof(*turtle_writer)); if(!turtle_writer) return NULL; turtle_writer->world = world; turtle_writer->nstack_depth = 0; turtle_writer->nstack = nstack; if(!turtle_writer->nstack) { turtle_writer->nstack = raptor_new_namespaces(world, 1); turtle_writer->my_nstack = 1; } turtle_writer->iostr = iostr; turtle_writer->flags = 0; turtle_writer->indent = 2; turtle_writer->base_uri = NULL; /* Ensure any initial base URI is not written relative */ if(base_uri && write_base_uri) raptor_turtle_writer_base(turtle_writer, base_uri); turtle_writer->base_uri = base_uri; turtle_writer->xsd_boolean_uri = raptor_new_uri(world, (const unsigned char*)"http://www.w3.org/2001/XMLSchema#boolean"); turtle_writer->xsd_decimal_uri = raptor_new_uri(world, (const unsigned char*)"http://www.w3.org/2001/XMLSchema#decimal"); turtle_writer->xsd_double_uri = raptor_new_uri(world, (const unsigned char*)"http://www.w3.org/2001/XMLSchema#double"); turtle_writer->xsd_integer_uri = raptor_new_uri(world, (const unsigned char*)"http://www.w3.org/2001/XMLSchema#integer"); return turtle_writer; } /** * raptor_free_turtle_writer: * @turtle_writer: Turtle writer object * * Destructor - Free Turtle Writer * **/ void raptor_free_turtle_writer(raptor_turtle_writer* turtle_writer) { if(!turtle_writer) return; if(turtle_writer->nstack && turtle_writer->my_nstack) raptor_free_namespaces(turtle_writer->nstack); if(turtle_writer->xsd_boolean_uri) raptor_free_uri(turtle_writer->xsd_boolean_uri); if(turtle_writer->xsd_decimal_uri) raptor_free_uri(turtle_writer->xsd_decimal_uri); if(turtle_writer->xsd_double_uri) raptor_free_uri(turtle_writer->xsd_double_uri); if(turtle_writer->xsd_integer_uri) raptor_free_uri(turtle_writer->xsd_integer_uri); RAPTOR_FREE(raptor_turtle_writer, turtle_writer); } static int raptor_turtle_writer_contains_newline(const unsigned char *s) { size_t i = 0; for( ; i < strlen((char*)s); i++) if(s[i] == '\n') return 1; return 0; } /** * raptor_turtle_writer_raw: * @turtle_writer: Turtle writer object * @s: raw string to write * * Write a raw string to the Turtle writer verbatim. * **/ void raptor_turtle_writer_raw(raptor_turtle_writer* turtle_writer, const unsigned char *s) { raptor_iostream_string_write(s, turtle_writer->iostr); } /** * raptor_turtle_writer_raw_counted: * @turtle_writer: Turtle writer object * @s: raw string to write * @len: length of string * * Write a counted string to the Turtle writer verbatim. * **/ void raptor_turtle_writer_raw_counted(raptor_turtle_writer* turtle_writer, const unsigned char *s, unsigned int len) { raptor_iostream_counted_string_write(s, len, turtle_writer->iostr); } /** * raptor_turtle_writer_namespace_prefix: * @turtle_writer: Turtle writer object * @ns: Namespace to write prefix declaration for * * Write a namespace prefix declaration (@prefix) * * Must only be used at the beginning of a document. */ void raptor_turtle_writer_namespace_prefix(raptor_turtle_writer* turtle_writer, raptor_namespace* ns) { raptor_iostream_string_write("@prefix ", turtle_writer->iostr); if(ns->prefix) raptor_iostream_string_write(raptor_namespace_get_prefix(ns), turtle_writer->iostr); raptor_iostream_counted_string_write(": ", 2, turtle_writer->iostr); raptor_turtle_writer_reference(turtle_writer, raptor_namespace_get_uri(ns)); raptor_iostream_counted_string_write(" .\n", 3, turtle_writer->iostr); } /** * raptor_turtle_writer_base: * @turtle_writer: Turtle writer object * @base_uri: New base URI or NULL * * Write a base URI directive (@base) to set the in-scope base URI */ void raptor_turtle_writer_base(raptor_turtle_writer* turtle_writer, raptor_uri* base_uri) { if(base_uri) { raptor_iostream_counted_string_write("@base ", 6, turtle_writer->iostr); raptor_turtle_writer_reference(turtle_writer, base_uri); raptor_iostream_counted_string_write(" .\n", 3, turtle_writer->iostr); } } /** * raptor_turtle_writer_reference: * @turtle_writer: Turtle writer object * @uri: URI to write * * Write a URI to the Turtle writer. * **/ void raptor_turtle_writer_reference(raptor_turtle_writer* turtle_writer, raptor_uri* uri) { unsigned char* uri_str; size_t length; uri_str = raptor_uri_to_relative_counted_uri_string(turtle_writer->base_uri, uri, &length); raptor_iostream_write_byte('<', turtle_writer->iostr); if(uri_str) raptor_string_ntriples_write(uri_str, length, '>', turtle_writer->iostr); raptor_iostream_write_byte('>', turtle_writer->iostr); RAPTOR_FREE(char*, uri_str); } /** * raptor_turtle_writer_qname: * @turtle_writer: Turtle writer object * @qname: qname to write * * Write a QName to the Turtle writer. * **/ void raptor_turtle_writer_qname(raptor_turtle_writer* turtle_writer, raptor_qname* qname) { raptor_iostream* iostr = turtle_writer->iostr; if(qname->nspace && qname->nspace->prefix_length > 0) raptor_iostream_counted_string_write(qname->nspace->prefix, qname->nspace->prefix_length, iostr); raptor_iostream_write_byte(':', iostr); raptor_iostream_counted_string_write(qname->local_name, qname->local_name_length, iostr); return; } /** * raptor_string_python_write: * @string: UTF-8 string to write * @len: length of UTF-8 string * @delim: Terminating delimiter character for string (such as " or >) * or \0 for no escaping. * @flags: flags 0=N-Triples mode, 1=Turtle (allow raw UTF-8), 2=Turtle long string (allow raw UTF-8), 3=JSON * @iostr: #raptor_iostream to write to * * Write a UTF-8 string using Python-style escapes (N-Triples, Turtle, JSON) to an iostream. * * Return value: non-0 on failure such as bad UTF-8 encoding. **/ int raptor_string_python_write(const unsigned char *string, size_t len, const char delim, int flags, raptor_iostream *iostr) { unsigned char c; int unichar_len; raptor_unichar unichar; if(flags < 0 || flags > 3) return 1; for(; (c=*string); string++, len--) { if((delim && c == delim && (delim == '\'' || delim == '"')) || c == '\\') { raptor_iostream_write_byte('\\', iostr); raptor_iostream_write_byte(c, iostr); continue; } if(delim && c == delim) { raptor_iostream_counted_string_write("\\u", 2, iostr); raptor_iostream_hexadecimal_write(c, 4, iostr); continue; } if(flags != 2) { /* N-Triples, Turtle or JSON */ /* Note: NTriples is ASCII */ if(c == 0x09) { raptor_iostream_counted_string_write("\\t", 2, iostr); continue; } else if((flags == 3) && c == 0x08) { /* JSON has \b for backspace */ raptor_iostream_counted_string_write("\\b", 2, iostr); continue; } else if(c == 0x0a) { raptor_iostream_counted_string_write("\\n", 2, iostr); continue; } else if((flags == 3) && c == 0x0b) { /* JSON has \f for formfeed */ raptor_iostream_counted_string_write("\\f", 2, iostr); continue; } else if(c == 0x0d) { raptor_iostream_counted_string_write("\\r", 2, iostr); continue; } else if(c < 0x20|| c == 0x7f) { raptor_iostream_counted_string_write("\\u", 2, iostr); raptor_iostream_hexadecimal_write(c, 4, iostr); continue; } else if(c < 0x80) { raptor_iostream_write_byte(c, iostr); continue; } } else if(c < 0x80) { /* Turtle long string has no escapes except delim */ raptor_iostream_write_byte(c, iostr); continue; } /* It is unicode */ unichar_len = raptor_unicode_utf8_string_get_char(string, len, NULL); if(unichar_len < 0 || RAPTOR_GOOD_CAST(size_t, unichar_len) > len) /* UTF-8 encoding had an error or ended in the middle of a string */ return 1; if(flags >= 1 && flags <= 3) { /* Turtle and JSON are UTF-8 - no need to escape */ raptor_iostream_counted_string_write(string, unichar_len, iostr); } else { unichar_len = raptor_unicode_utf8_string_get_char(string, len, &unichar); if(unichar_len < 0) return 1; if(unichar < 0x10000) { raptor_iostream_counted_string_write("\\u", 2, iostr); raptor_iostream_hexadecimal_write(RAPTOR_GOOD_CAST(unsigned int, unichar), 4, iostr); } else { raptor_iostream_counted_string_write("\\U", 2, iostr); raptor_iostream_hexadecimal_write(RAPTOR_GOOD_CAST(unsigned int, unichar), 8, iostr); } } unichar_len--; /* since loop does len-- */ string += unichar_len; len -= unichar_len; } return 0; } /** * raptor_turtle_writer_quoted_counted_string: * @turtle_writer: Turtle writer object * @s: string to write * @len: string length * * Write a Turtle escaped-string inside double quotes to the writer. * * Return value: non-0 on failure **/ int raptor_turtle_writer_quoted_counted_string(raptor_turtle_writer* turtle_writer, const unsigned char *s, size_t len) { const unsigned char *quotes = (const unsigned char *)"\"\"\"\""; const unsigned char *q; size_t q_len; int flags; int rc = 0; if(!s) return 1; /* Turtle """longstring""" (2) or "string" (1) */ flags = raptor_turtle_writer_contains_newline(s) ? 2 : 1; q = (flags == 2) ? quotes : quotes + 2; q_len = (q == quotes) ? 3 : 1; raptor_iostream_counted_string_write(q, q_len, turtle_writer->iostr); rc = raptor_string_python_write(s, strlen((const char*)s), '"', flags, turtle_writer->iostr); raptor_iostream_counted_string_write(q, q_len, turtle_writer->iostr); return rc; } /** * raptor_turtle_writer_literal: * @turtle_writer: Turtle writer object * @nstack: Namespace stack for making a QName for datatype URI * @s: literal string to write (SHARED) * @lang: language tag (may be NULL) * @datatype: datatype URI (may be NULL) * * Write a literal (possibly with lang and datatype) to the Turtle writer. * * Return value: non-0 on failure **/ int raptor_turtle_writer_literal(raptor_turtle_writer* turtle_writer, raptor_namespace_stack *nstack, const unsigned char* s, const unsigned char* lang, raptor_uri* datatype) { /* DBL_MAX = 309 decimal digits */ #define INT_MAX_LEN 309 /* DBL_EPSILON = 52 digits */ #define FRAC_MAX_LEN 52 char* endptr = (char *)s; int written = 0; /* typed literal special cases */ if(datatype) { /* integer */ if(raptor_uri_equals(datatype, turtle_writer->xsd_integer_uri)) { /* FIXME. Work around that gcc < 4.5 cannot disable warn_unused_result */ long gcc_is_stupid = strtol((const char*)s, &endptr, 10); if(endptr != (char*)s && !*endptr) { raptor_iostream_string_write(s, turtle_writer->iostr); /* More gcc madness to 'use' the variable I didn't want */ written = 1 + 0 * (int)gcc_is_stupid; } else { raptor_log_error(turtle_writer->world, RAPTOR_LOG_LEVEL_ERROR, NULL, "Illegal value for xsd:integer literal."); } /* double, decimal */ } else if(raptor_uri_equals(datatype, turtle_writer->xsd_double_uri) || raptor_uri_equals(datatype, turtle_writer->xsd_decimal_uri)) { /* FIXME. Work around that gcc < 4.5 cannot disable warn_unused_result */ double gcc_is_doubly_stupid = strtod((const char*)s, &endptr); if(endptr != (char*)s && !*endptr) { raptor_iostream_string_write(s, turtle_writer->iostr); /* More gcc madness to 'use' the variable I didn't want */ written = 1 + 0 * (int)gcc_is_doubly_stupid; } else { raptor_log_error(turtle_writer->world, RAPTOR_LOG_LEVEL_ERROR, NULL, "Illegal value for xsd:double or xsd:decimal literal."); } /* boolean */ } else if(raptor_uri_equals(datatype, turtle_writer->xsd_boolean_uri)) { if(!strcmp((const char*)s, "0") || !strcmp((const char*)s, "false")) { raptor_iostream_string_write("false", turtle_writer->iostr); written = 1; } else if(!strcmp((const char*)s, "1") || !strcmp((const char*)s, "true")) { raptor_iostream_string_write("true", turtle_writer->iostr); written = 1; } else { raptor_log_error(turtle_writer->world, RAPTOR_LOG_LEVEL_ERROR, NULL, "Illegal value for xsd:boolean literal."); } } } if(written) return 0; if(raptor_turtle_writer_quoted_counted_string(turtle_writer, s, strlen((const char*)s))) return 1; /* typed literal, not a special case */ if(datatype) { raptor_qname* qname; raptor_iostream_string_write("^^", turtle_writer->iostr); qname = raptor_new_qname_from_namespace_uri(nstack, datatype, 10); if(qname) { raptor_turtle_writer_qname(turtle_writer, qname); raptor_free_qname(qname); } else raptor_turtle_writer_reference(turtle_writer, datatype); } else if(lang) { /* literal with language tag */ raptor_iostream_write_byte('@', turtle_writer->iostr); raptor_iostream_string_write(lang, turtle_writer->iostr); } return 0; } /** * raptor_turtle_writer_comment: * @turtle_writer: Turtle writer object * @s: comment string to write * * Write a Turtle comment to the Turtle writer. * **/ void raptor_turtle_writer_comment(raptor_turtle_writer* turtle_writer, const unsigned char *string) { unsigned char c; size_t len = strlen((const char*)string); raptor_iostream_counted_string_write((const unsigned char*)"# ", 2, turtle_writer->iostr); for(; (c=*string); string++, len--) { if(c == '\n') { raptor_turtle_writer_newline(turtle_writer); raptor_iostream_counted_string_write((const unsigned char*)"# ", 2, turtle_writer->iostr); } else if(c != '\r') { /* skip carriage returns (windows... *sigh*) */ raptor_iostream_write_byte(c, turtle_writer->iostr); } } raptor_turtle_writer_newline(turtle_writer); } /** * raptor_turtle_writer_set_option: * @turtle_writer: #raptor_turtle_writer turtle_writer object * @option: option to set from enumerated #raptor_option values * @value: integer option value (0 or larger) * * Set turtle_writer options with integer values. * * The allowed options are available via * raptor_world_get_option_description() * * Return value: non 0 on failure or if the option is unknown **/ int raptor_turtle_writer_set_option(raptor_turtle_writer *turtle_writer, raptor_option option, int value) { if(value < 0 || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: if(value) turtle_writer->flags |= TURTLE_WRITER_AUTO_INDENT; else turtle_writer->flags &= ~TURTLE_WRITER_AUTO_INDENT; break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: turtle_writer->indent = value; break; case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: break; /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: return -1; break; } return 0; } /** * raptor_turtle_writer_set_option_string: * @turtle_writer: #raptor_turtle_writer turtle_writer object * @option: option to set from enumerated #raptor_option values * @value: option value * * Set turtle_writer options with string values. * * The allowed options are available via * raptor_world_get_option_description(). * If the option type is integer, the value is interpreted as an * integer. * * Return value: non 0 on failure or if the option is unknown **/ int raptor_turtle_writer_set_option_string(raptor_turtle_writer *turtle_writer, raptor_option option, const unsigned char *value) { if(!value || !raptor_option_is_valid_for_area(option, RAPTOR_OPTION_AREA_TURTLE_WRITER)) return 1; if(raptor_option_value_is_numeric(option)) return raptor_turtle_writer_set_option(turtle_writer, option, atoi((const char*)value)); return 1; } /** * raptor_turtle_writer_get_option: * @turtle_writer: #raptor_turtle_writer serializer object * @option: option to get value * * Get various turtle_writer options. * * The allowed options are available via raptor_options_enumerate(). * * Note: no option value is negative * * Return value: option value or < 0 for an illegal option **/ int raptor_turtle_writer_get_option(raptor_turtle_writer *turtle_writer, raptor_option option) { int result = -1; switch(option) { case RAPTOR_OPTION_WRITER_AUTO_INDENT: result = TURTLE_WRITER_AUTO_INDENT(turtle_writer); break; case RAPTOR_OPTION_WRITER_INDENT_WIDTH: result = turtle_writer->indent; break; /* writer options */ case RAPTOR_OPTION_WRITER_AUTO_EMPTY: case RAPTOR_OPTION_WRITER_XML_VERSION: case RAPTOR_OPTION_WRITER_XML_DECLARATION: /* parser options */ case RAPTOR_OPTION_SCANNING: case RAPTOR_OPTION_ALLOW_NON_NS_ATTRIBUTES: case RAPTOR_OPTION_ALLOW_OTHER_PARSETYPES: case RAPTOR_OPTION_ALLOW_BAGID: case RAPTOR_OPTION_ALLOW_RDF_TYPE_RDF_LIST: case RAPTOR_OPTION_NORMALIZE_LANGUAGE: case RAPTOR_OPTION_NON_NFC_FATAL: case RAPTOR_OPTION_WARN_OTHER_PARSETYPES: case RAPTOR_OPTION_CHECK_RDF_ID: case RAPTOR_OPTION_HTML_TAG_SOUP: case RAPTOR_OPTION_MICROFORMATS: case RAPTOR_OPTION_HTML_LINK: case RAPTOR_OPTION_WWW_TIMEOUT: case RAPTOR_OPTION_STRICT: /* Shared */ case RAPTOR_OPTION_NO_NET: case RAPTOR_OPTION_NO_FILE: case RAPTOR_OPTION_LOAD_EXTERNAL_ENTITIES: /* XML writer options */ case RAPTOR_OPTION_RELATIVE_URIS: /* DOT serializer options */ case RAPTOR_OPTION_RESOURCE_BORDER: case RAPTOR_OPTION_LITERAL_BORDER: case RAPTOR_OPTION_BNODE_BORDER: case RAPTOR_OPTION_RESOURCE_FILL: case RAPTOR_OPTION_LITERAL_FILL: case RAPTOR_OPTION_BNODE_FILL: /* JSON serializer options */ case RAPTOR_OPTION_JSON_CALLBACK: case RAPTOR_OPTION_JSON_EXTRA_DATA: case RAPTOR_OPTION_RSS_TRIPLES: case RAPTOR_OPTION_ATOM_ENTRY_URI: case RAPTOR_OPTION_PREFIX_ELEMENTS: /* Turtle serializer option */ case RAPTOR_OPTION_WRITE_BASE_URI: /* WWW option */ case RAPTOR_OPTION_WWW_HTTP_CACHE_CONTROL: case RAPTOR_OPTION_WWW_HTTP_USER_AGENT: case RAPTOR_OPTION_WWW_CERT_FILENAME: case RAPTOR_OPTION_WWW_CERT_TYPE: case RAPTOR_OPTION_WWW_CERT_PASSPHRASE: case RAPTOR_OPTION_WWW_SSL_VERIFY_PEER: case RAPTOR_OPTION_WWW_SSL_VERIFY_HOST: default: break; } return result; } /** * raptor_turtle_writer_get_option_string: * @turtle_writer: #raptor_turtle_writer serializer object * @option: option to get value * * Get turtle_writer options with string values. * * The allowed options are available via raptor_options_enumerate(). * * Return value: option value or NULL for an illegal option or no value **/ const unsigned char * raptor_turtle_writer_get_option_string(raptor_turtle_writer *turtle_writer, raptor_option option) { return NULL; } /** * raptor_turtle_writer_bnodeid: * @turtle_writer: Turtle writer object * @bnodeid: blank node ID to write * @len: length of @bnodeid * * Write a blank node ID with leading _: to the Turtle writer. * **/ void raptor_turtle_writer_bnodeid(raptor_turtle_writer* turtle_writer, const unsigned char *bnodeid, size_t len) { raptor_bnodeid_ntriples_write(bnodeid, len, turtle_writer->iostr); } #endif #ifdef STANDALONE /* one more prototype */ int main(int argc, char *argv[]); const unsigned char *base_uri_string = (const unsigned char*)"http://example.org/base#"; const unsigned char* longstr = (const unsigned char*)"it's quoted\nand has newlines, \"s <> and\n\ttabbing"; #define OUT_BYTES_COUNT 149 int main(int argc, char *argv[]) { raptor_world *world; const char *program = raptor_basename(argv[0]); raptor_iostream *iostr; raptor_namespace_stack *nstack; raptor_namespace* ex_ns; raptor_turtle_writer* turtle_writer; raptor_uri* base_uri; raptor_qname* el_name; unsigned long count; raptor_uri* datatype; /* for raptor_new_iostream_to_string */ void *string = NULL; size_t string_len = 0; world = raptor_new_world(); if(!world || raptor_world_open(world)) exit(1); iostr = raptor_new_iostream_to_string(world, &string, &string_len, NULL); if(!iostr) { fprintf(stderr, "%s: Failed to create iostream to string\n", program); exit(1); } nstack = raptor_new_namespaces(world, 1); base_uri = raptor_new_uri(world, base_uri_string); turtle_writer = raptor_new_turtle_writer(world, base_uri, 1, nstack, iostr); if(!turtle_writer) { fprintf(stderr, "%s: Failed to create turtle_writer to iostream\n", program); exit(1); } raptor_turtle_writer_set_option(turtle_writer, RAPTOR_OPTION_WRITER_AUTO_INDENT, 1); ex_ns = raptor_new_namespace(nstack, (const unsigned char*)"ex", (const unsigned char*)"http://example.org/ns#", 0); raptor_turtle_writer_namespace_prefix(turtle_writer, ex_ns); raptor_turtle_writer_reference(turtle_writer, base_uri); raptor_turtle_writer_increase_indent(turtle_writer); raptor_turtle_writer_newline(turtle_writer); raptor_turtle_writer_raw(turtle_writer, (const unsigned char*)"ex:foo "); raptor_turtle_writer_quoted_counted_string(turtle_writer, longstr, strlen((const char*)longstr)); raptor_turtle_writer_raw_counted(turtle_writer, (const unsigned char*)" ;", 2); raptor_turtle_writer_newline(turtle_writer); el_name = raptor_new_qname_from_namespace_local_name(world, ex_ns, (const unsigned char*)"bar", NULL); raptor_turtle_writer_qname(turtle_writer, el_name); raptor_free_qname(el_name); raptor_turtle_writer_raw_counted(turtle_writer, (const unsigned char*)" ", 1); datatype = raptor_new_uri(world, (const unsigned char*)"http://www.w3.org/2001/XMLSchema#decimal"); raptor_turtle_writer_literal(turtle_writer, nstack, (const unsigned char*)"10.0", NULL, datatype); raptor_free_uri(datatype); raptor_turtle_writer_newline(turtle_writer); raptor_turtle_writer_decrease_indent(turtle_writer); raptor_turtle_writer_raw_counted(turtle_writer, (const unsigned char*)".", 1); raptor_turtle_writer_newline(turtle_writer); raptor_free_turtle_writer(turtle_writer); raptor_free_namespace(ex_ns); raptor_free_namespaces(nstack); raptor_free_uri(base_uri); count = raptor_iostream_tell(iostr); #if defined(RAPTOR_DEBUG) && RAPTOR_DEBUG > 1 fprintf(stderr, "%s: Freeing iostream\n", program); #endif raptor_free_iostream(iostr); if(count != OUT_BYTES_COUNT) { fprintf(stderr, "%s: I/O stream wrote %d bytes, expected %d\n", program, (int)count, (int)OUT_BYTES_COUNT); fputs("[[", stderr); (void)fwrite(string, 1, string_len, stderr); fputs("]]\n", stderr); return 1; } if(!string) { fprintf(stderr, "%s: I/O stream failed to create a string\n", program); return 1; } string_len = strlen((const char*)string); if(string_len != count) { fprintf(stderr, "%s: I/O stream created a string length %d, expected %d\n", program, (int)string_len, (int)count); return 1; } #if defined(RAPTOR_DEBUG) && RAPTOR_DEBUG > 1 fprintf(stderr, "%s: Made Turtle string of %d bytes\n", program, (int)string_len); fputs("[[", stderr); (void)fwrite(string, 1, string_len, stderr); fputs("]]\n", stderr); #endif raptor_free_memory(string); raptor_free_world(world); /* keep gcc -Wall happy */ return(0); } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/good_3568_10
crossvul-cpp_data_good_3833_0
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2000-2001 Qualcomm Incorporated Copyright (C) 2009-2010 Gustavo F. Padovan <gustavo@padovan.org> Copyright (C) 2010 Google Inc. Copyright (C) 2011 ProFUSION Embedded Systems Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth L2CAP sockets. */ #include <linux/export.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/l2cap.h> #include <net/bluetooth/smp.h> static const struct proto_ops l2cap_sock_ops; static void l2cap_sock_init(struct sock *sk, struct sock *parent); static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio); static int l2cap_sock_bind(struct socket *sock, struct sockaddr *addr, int alen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid && la.l2_psm) return -EINVAL; lock_sock(sk); if (sk->sk_state != BT_OPEN) { err = -EBADFD; goto done; } if (la.l2_psm) { __u16 psm = __le16_to_cpu(la.l2_psm); /* PSM must be odd and lsb of upper byte must be 0 */ if ((psm & 0x0101) != 0x0001) { err = -EINVAL; goto done; } /* Restrict usage of well-known PSMs */ if (psm < 0x1001 && !capable(CAP_NET_BIND_SERVICE)) { err = -EACCES; goto done; } } if (la.l2_cid) err = l2cap_add_scid(chan, __le16_to_cpu(la.l2_cid)); else err = l2cap_add_psm(chan, &la.l2_bdaddr, la.l2_psm); if (err < 0) goto done; if (__le16_to_cpu(la.l2_psm) == L2CAP_PSM_SDP || __le16_to_cpu(la.l2_psm) == L2CAP_PSM_RFCOMM) chan->sec_level = BT_SECURITY_SDP; bacpy(&bt_sk(sk)->src, &la.l2_bdaddr); chan->state = BT_BOUND; sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } static int l2cap_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct sockaddr_l2 la; int len, err = 0; BT_DBG("sk %p", sk); if (!addr || alen < sizeof(addr->sa_family) || addr->sa_family != AF_BLUETOOTH) return -EINVAL; memset(&la, 0, sizeof(la)); len = min_t(unsigned int, sizeof(la), alen); memcpy(&la, addr, len); if (la.l2_cid && la.l2_psm) return -EINVAL; err = l2cap_chan_connect(chan, la.l2_psm, __le16_to_cpu(la.l2_cid), &la.l2_bdaddr, la.l2_bdaddr_type); if (err) return err; lock_sock(sk); err = bt_sock_wait_state(sk, BT_CONNECTED, sock_sndtimeo(sk, flags & O_NONBLOCK)); release_sock(sk); return err; } static int l2cap_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; int err = 0; BT_DBG("sk %p backlog %d", sk, backlog); lock_sock(sk); if (sk->sk_state != BT_BOUND) { err = -EBADFD; goto done; } if (sk->sk_type != SOCK_SEQPACKET && sk->sk_type != SOCK_STREAM) { err = -EINVAL; goto done; } switch (chan->mode) { case L2CAP_MODE_BASIC: break; case L2CAP_MODE_ERTM: case L2CAP_MODE_STREAMING: if (!disable_ertm) break; /* fall through */ default: err = -ENOTSUPP; goto done; } sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; chan->state = BT_LISTEN; sk->sk_state = BT_LISTEN; done: release_sock(sk); return err; } static int l2cap_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock_nested(sk, SINGLE_DEPTH_NESTING); timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); BT_DBG("sk %p timeo %ld", sk, timeo); /* Wait for an incoming connection. (wake-one). */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (1) { set_current_state(TASK_INTERRUPTIBLE); if (sk->sk_state != BT_LISTEN) { err = -EBADFD; break; } nsk = bt_accept_dequeue(sk, newsock); if (nsk) break; if (!timeo) { err = -EAGAIN; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); } __set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; BT_DBG("new socket %p", nsk); done: release_sock(sk); return err; } static int l2cap_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_l2 *la = (struct sockaddr_l2 *) addr; struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; BT_DBG("sock %p, sk %p", sock, sk); memset(la, 0, sizeof(struct sockaddr_l2)); addr->sa_family = AF_BLUETOOTH; *len = sizeof(struct sockaddr_l2); if (peer) { la->l2_psm = chan->psm; bacpy(&la->l2_bdaddr, &bt_sk(sk)->dst); la->l2_cid = cpu_to_le16(chan->dcid); } else { la->l2_psm = chan->sport; bacpy(&la->l2_bdaddr, &bt_sk(sk)->src); la->l2_cid = cpu_to_le16(chan->scid); } return 0; } static int l2cap_sock_getsockopt_old(struct socket *sock, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct l2cap_options opts; struct l2cap_conninfo cinfo; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case L2CAP_OPTIONS: memset(&opts, 0, sizeof(opts)); opts.imtu = chan->imtu; opts.omtu = chan->omtu; opts.flush_to = chan->flush_to; opts.mode = chan->mode; opts.fcs = chan->fcs; opts.max_tx = chan->max_tx; opts.txwin_size = chan->tx_win; len = min_t(unsigned int, len, sizeof(opts)); if (copy_to_user(optval, (char *) &opts, len)) err = -EFAULT; break; case L2CAP_LM: switch (chan->sec_level) { case BT_SECURITY_LOW: opt = L2CAP_LM_AUTH; break; case BT_SECURITY_MEDIUM: opt = L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT; break; case BT_SECURITY_HIGH: opt = L2CAP_LM_AUTH | L2CAP_LM_ENCRYPT | L2CAP_LM_SECURE; break; default: opt = 0; break; } if (test_bit(FLAG_ROLE_SWITCH, &chan->flags)) opt |= L2CAP_LM_MASTER; if (test_bit(FLAG_FORCE_RELIABLE, &chan->flags)) opt |= L2CAP_LM_RELIABLE; if (put_user(opt, (u32 __user *) optval)) err = -EFAULT; break; case L2CAP_CONNINFO: if (sk->sk_state != BT_CONNECTED && !(sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags))) { err = -ENOTCONN; break; } memset(&cinfo, 0, sizeof(cinfo)); cinfo.hci_handle = chan->conn->hcon->handle; memcpy(cinfo.dev_class, chan->conn->hcon->dev_class, 3); len = min_t(unsigned int, len, sizeof(cinfo)); if (copy_to_user(optval, (char *) &cinfo, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct bt_security sec; struct bt_power pwr; int len, err = 0; BT_DBG("sk %p", sk); if (level == SOL_L2CAP) return l2cap_sock_getsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && chan->chan_type != L2CAP_CHAN_RAW) { err = -EINVAL; break; } memset(&sec, 0, sizeof(sec)); if (chan->conn) sec.level = chan->conn->hcon->sec_level; else sec.level = chan->sec_level; if (sk->sk_state == BT_CONNECTED) sec.key_size = chan->conn->hcon->enc_key_size; len = min_t(unsigned int, len, sizeof(sec)); if (copy_to_user(optval, (char *) &sec, len)) err = -EFAULT; break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (put_user(test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags), (u32 __user *) optval)) err = -EFAULT; break; case BT_FLUSHABLE: if (put_user(test_bit(FLAG_FLUSHABLE, &chan->flags), (u32 __user *) optval)) err = -EFAULT; break; case BT_POWER: if (sk->sk_type != SOCK_SEQPACKET && sk->sk_type != SOCK_STREAM && sk->sk_type != SOCK_RAW) { err = -EINVAL; break; } pwr.force_active = test_bit(FLAG_FORCE_ACTIVE, &chan->flags); len = min_t(unsigned int, len, sizeof(pwr)); if (copy_to_user(optval, (char *) &pwr, len)) err = -EFAULT; break; case BT_CHANNEL_POLICY: if (!enable_hs) { err = -ENOPROTOOPT; break; } if (put_user(chan->chan_policy, (u32 __user *) optval)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static bool l2cap_valid_mtu(struct l2cap_chan *chan, u16 mtu) { switch (chan->scid) { case L2CAP_CID_LE_DATA: if (mtu < L2CAP_LE_MIN_MTU) return false; break; default: if (mtu < L2CAP_DEFAULT_MIN_MTU) return false; } return true; } static int l2cap_sock_setsockopt_old(struct socket *sock, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct l2cap_options opts; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); lock_sock(sk); switch (optname) { case L2CAP_OPTIONS: if (sk->sk_state == BT_CONNECTED) { err = -EINVAL; break; } opts.imtu = chan->imtu; opts.omtu = chan->omtu; opts.flush_to = chan->flush_to; opts.mode = chan->mode; opts.fcs = chan->fcs; opts.max_tx = chan->max_tx; opts.txwin_size = chan->tx_win; len = min_t(unsigned int, sizeof(opts), optlen); if (copy_from_user((char *) &opts, optval, len)) { err = -EFAULT; break; } if (opts.txwin_size > L2CAP_DEFAULT_EXT_WINDOW) { err = -EINVAL; break; } if (!l2cap_valid_mtu(chan, opts.imtu)) { err = -EINVAL; break; } chan->mode = opts.mode; switch (chan->mode) { case L2CAP_MODE_BASIC: clear_bit(CONF_STATE2_DEVICE, &chan->conf_state); break; case L2CAP_MODE_ERTM: case L2CAP_MODE_STREAMING: if (!disable_ertm) break; /* fall through */ default: err = -EINVAL; break; } chan->imtu = opts.imtu; chan->omtu = opts.omtu; chan->fcs = opts.fcs; chan->max_tx = opts.max_tx; chan->tx_win = opts.txwin_size; break; case L2CAP_LM: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt & L2CAP_LM_AUTH) chan->sec_level = BT_SECURITY_LOW; if (opt & L2CAP_LM_ENCRYPT) chan->sec_level = BT_SECURITY_MEDIUM; if (opt & L2CAP_LM_SECURE) chan->sec_level = BT_SECURITY_HIGH; if (opt & L2CAP_LM_MASTER) set_bit(FLAG_ROLE_SWITCH, &chan->flags); else clear_bit(FLAG_ROLE_SWITCH, &chan->flags); if (opt & L2CAP_LM_RELIABLE) set_bit(FLAG_FORCE_RELIABLE, &chan->flags); else clear_bit(FLAG_FORCE_RELIABLE, &chan->flags); break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; struct bt_security sec; struct bt_power pwr; struct l2cap_conn *conn; int len, err = 0; u32 opt; BT_DBG("sk %p", sk); if (level == SOL_L2CAP) return l2cap_sock_setsockopt_old(sock, optname, optval, optlen); if (level != SOL_BLUETOOTH) return -ENOPROTOOPT; lock_sock(sk); switch (optname) { case BT_SECURITY: if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && chan->chan_type != L2CAP_CHAN_RAW) { err = -EINVAL; break; } sec.level = BT_SECURITY_LOW; len = min_t(unsigned int, sizeof(sec), optlen); if (copy_from_user((char *) &sec, optval, len)) { err = -EFAULT; break; } if (sec.level < BT_SECURITY_LOW || sec.level > BT_SECURITY_HIGH) { err = -EINVAL; break; } chan->sec_level = sec.level; if (!chan->conn) break; conn = chan->conn; /*change security for LE channels */ if (chan->scid == L2CAP_CID_LE_DATA) { if (!conn->hcon->out) { err = -EINVAL; break; } if (smp_conn_security(conn, sec.level)) break; sk->sk_state = BT_CONFIG; chan->state = BT_CONFIG; /* or for ACL link */ } else if ((sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) || sk->sk_state == BT_CONNECTED) { if (!l2cap_chan_check_security(chan)) set_bit(BT_SK_SUSPEND, &bt_sk(sk)->flags); else sk->sk_state_change(sk); } else { err = -EINVAL; } break; case BT_DEFER_SETUP: if (sk->sk_state != BT_BOUND && sk->sk_state != BT_LISTEN) { err = -EINVAL; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt) set_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); else clear_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags); break; case BT_FLUSHABLE: if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt > BT_FLUSHABLE_ON) { err = -EINVAL; break; } if (opt == BT_FLUSHABLE_OFF) { struct l2cap_conn *conn = chan->conn; /* proceed further only when we have l2cap_conn and No Flush support in the LM */ if (!conn || !lmp_no_flush_capable(conn->hcon->hdev)) { err = -EINVAL; break; } } if (opt) set_bit(FLAG_FLUSHABLE, &chan->flags); else clear_bit(FLAG_FLUSHABLE, &chan->flags); break; case BT_POWER: if (chan->chan_type != L2CAP_CHAN_CONN_ORIENTED && chan->chan_type != L2CAP_CHAN_RAW) { err = -EINVAL; break; } pwr.force_active = BT_POWER_FORCE_ACTIVE_ON; len = min_t(unsigned int, sizeof(pwr), optlen); if (copy_from_user((char *) &pwr, optval, len)) { err = -EFAULT; break; } if (pwr.force_active) set_bit(FLAG_FORCE_ACTIVE, &chan->flags); else clear_bit(FLAG_FORCE_ACTIVE, &chan->flags); break; case BT_CHANNEL_POLICY: if (!enable_hs) { err = -ENOPROTOOPT; break; } if (get_user(opt, (u32 __user *) optval)) { err = -EFAULT; break; } if (opt > BT_CHANNEL_POLICY_AMP_PREFERRED) { err = -EINVAL; break; } if (chan->mode != L2CAP_MODE_ERTM && chan->mode != L2CAP_MODE_STREAMING) { err = -EOPNOTSUPP; break; } chan->chan_policy = (u8) opt; break; default: err = -ENOPROTOOPT; break; } release_sock(sk); return err; } static int l2cap_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct l2cap_chan *chan = l2cap_pi(sk)->chan; int err; BT_DBG("sock %p, sk %p", sock, sk); err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; if (sk->sk_state != BT_CONNECTED) return -ENOTCONN; l2cap_chan_lock(chan); err = l2cap_chan_send(chan, msg, len, sk->sk_priority); l2cap_chan_unlock(chan); return err; } static int l2cap_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct l2cap_pinfo *pi = l2cap_pi(sk); int err; lock_sock(sk); if (sk->sk_state == BT_CONNECT2 && test_bit(BT_SK_DEFER_SETUP, &bt_sk(sk)->flags)) { sk->sk_state = BT_CONFIG; pi->chan->state = BT_CONFIG; __l2cap_connect_rsp_defer(pi->chan); release_sock(sk); return 0; } release_sock(sk); if (sock->type == SOCK_STREAM) err = bt_sock_stream_recvmsg(iocb, sock, msg, len, flags); else err = bt_sock_recvmsg(iocb, sock, msg, len, flags); if (pi->chan->mode != L2CAP_MODE_ERTM) return err; /* Attempt to put pending rx data in the socket buffer */ lock_sock(sk); if (!test_bit(CONN_LOCAL_BUSY, &pi->chan->conn_state)) goto done; if (pi->rx_busy_skb) { if (!sock_queue_rcv_skb(sk, pi->rx_busy_skb)) pi->rx_busy_skb = NULL; else goto done; } /* Restore data flow when half of the receive buffer is * available. This avoids resending large numbers of * frames. */ if (atomic_read(&sk->sk_rmem_alloc) <= sk->sk_rcvbuf >> 1) l2cap_chan_busy(pi->chan, 0); done: release_sock(sk); return err; } /* Kill socket (only if zapped and orphan) * Must be called on unlocked socket. */ static void l2cap_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; BT_DBG("sk %p state %s", sk, state_to_string(sk->sk_state)); /* Kill poor orphan */ l2cap_chan_destroy(l2cap_pi(sk)->chan); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } static int l2cap_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct l2cap_chan *chan; struct l2cap_conn *conn; int err = 0; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; chan = l2cap_pi(sk)->chan; conn = chan->conn; if (conn) mutex_lock(&conn->chan_lock); l2cap_chan_lock(chan); lock_sock(sk); if (!sk->sk_shutdown) { if (chan->mode == L2CAP_MODE_ERTM) err = __l2cap_wait_ack(sk); sk->sk_shutdown = SHUTDOWN_MASK; release_sock(sk); l2cap_chan_close(chan, 0); lock_sock(sk); if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) err = bt_sock_wait_state(sk, BT_CLOSED, sk->sk_lingertime); } if (!err && sk->sk_err) err = -sk->sk_err; release_sock(sk); l2cap_chan_unlock(chan); if (conn) mutex_unlock(&conn->chan_lock); return err; } static int l2cap_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err; BT_DBG("sock %p, sk %p", sock, sk); if (!sk) return 0; err = l2cap_sock_shutdown(sock, 2); sock_orphan(sk); l2cap_sock_kill(sk); return err; } static void l2cap_sock_cleanup_listen(struct sock *parent) { struct sock *sk; BT_DBG("parent %p", parent); /* Close not yet accepted channels */ while ((sk = bt_accept_dequeue(parent, NULL))) { struct l2cap_chan *chan = l2cap_pi(sk)->chan; l2cap_chan_lock(chan); __clear_chan_timer(chan); l2cap_chan_close(chan, ECONNRESET); l2cap_chan_unlock(chan); l2cap_sock_kill(sk); } } static struct l2cap_chan *l2cap_sock_new_connection_cb(struct l2cap_chan *chan) { struct sock *sk, *parent = chan->data; /* Check for backlog size */ if (sk_acceptq_is_full(parent)) { BT_DBG("backlog full %d", parent->sk_ack_backlog); return NULL; } sk = l2cap_sock_alloc(sock_net(parent), NULL, BTPROTO_L2CAP, GFP_ATOMIC); if (!sk) return NULL; bt_sock_reclassify_lock(sk, BTPROTO_L2CAP); l2cap_sock_init(sk, parent); return l2cap_pi(sk)->chan; } static int l2cap_sock_recv_cb(struct l2cap_chan *chan, struct sk_buff *skb) { int err; struct sock *sk = chan->data; struct l2cap_pinfo *pi = l2cap_pi(sk); lock_sock(sk); if (pi->rx_busy_skb) { err = -ENOMEM; goto done; } err = sock_queue_rcv_skb(sk, skb); /* For ERTM, handle one skb that doesn't fit into the recv * buffer. This is important to do because the data frames * have already been acked, so the skb cannot be discarded. * * Notify the l2cap core that the buffer is full, so the * LOCAL_BUSY state is entered and no more frames are * acked and reassembled until there is buffer space * available. */ if (err < 0 && pi->chan->mode == L2CAP_MODE_ERTM) { pi->rx_busy_skb = skb; l2cap_chan_busy(pi->chan, 1); err = 0; } done: release_sock(sk); return err; } static void l2cap_sock_close_cb(struct l2cap_chan *chan) { struct sock *sk = chan->data; l2cap_sock_kill(sk); } static void l2cap_sock_teardown_cb(struct l2cap_chan *chan, int err) { struct sock *sk = chan->data; struct sock *parent; lock_sock(sk); parent = bt_sk(sk)->parent; sock_set_flag(sk, SOCK_ZAPPED); switch (chan->state) { case BT_OPEN: case BT_BOUND: case BT_CLOSED: break; case BT_LISTEN: l2cap_sock_cleanup_listen(sk); sk->sk_state = BT_CLOSED; chan->state = BT_CLOSED; break; default: sk->sk_state = BT_CLOSED; chan->state = BT_CLOSED; sk->sk_err = err; if (parent) { bt_accept_unlink(sk); parent->sk_data_ready(parent, 0); } else { sk->sk_state_change(sk); } break; } release_sock(sk); } static void l2cap_sock_state_change_cb(struct l2cap_chan *chan, int state) { struct sock *sk = chan->data; sk->sk_state = state; } static struct sk_buff *l2cap_sock_alloc_skb_cb(struct l2cap_chan *chan, unsigned long len, int nb) { struct sk_buff *skb; int err; l2cap_chan_unlock(chan); skb = bt_skb_send_alloc(chan->sk, len, nb, &err); l2cap_chan_lock(chan); if (!skb) return ERR_PTR(err); return skb; } static void l2cap_sock_ready_cb(struct l2cap_chan *chan) { struct sock *sk = chan->data; struct sock *parent; lock_sock(sk); parent = bt_sk(sk)->parent; BT_DBG("sk %p, parent %p", sk, parent); sk->sk_state = BT_CONNECTED; sk->sk_state_change(sk); if (parent) parent->sk_data_ready(parent, 0); release_sock(sk); } static struct l2cap_ops l2cap_chan_ops = { .name = "L2CAP Socket Interface", .new_connection = l2cap_sock_new_connection_cb, .recv = l2cap_sock_recv_cb, .close = l2cap_sock_close_cb, .teardown = l2cap_sock_teardown_cb, .state_change = l2cap_sock_state_change_cb, .ready = l2cap_sock_ready_cb, .alloc_skb = l2cap_sock_alloc_skb_cb, }; static void l2cap_sock_destruct(struct sock *sk) { BT_DBG("sk %p", sk); l2cap_chan_put(l2cap_pi(sk)->chan); if (l2cap_pi(sk)->rx_busy_skb) { kfree_skb(l2cap_pi(sk)->rx_busy_skb); l2cap_pi(sk)->rx_busy_skb = NULL; } skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); } static void l2cap_sock_init(struct sock *sk, struct sock *parent) { struct l2cap_pinfo *pi = l2cap_pi(sk); struct l2cap_chan *chan = pi->chan; BT_DBG("sk %p", sk); if (parent) { struct l2cap_chan *pchan = l2cap_pi(parent)->chan; sk->sk_type = parent->sk_type; bt_sk(sk)->flags = bt_sk(parent)->flags; chan->chan_type = pchan->chan_type; chan->imtu = pchan->imtu; chan->omtu = pchan->omtu; chan->conf_state = pchan->conf_state; chan->mode = pchan->mode; chan->fcs = pchan->fcs; chan->max_tx = pchan->max_tx; chan->tx_win = pchan->tx_win; chan->tx_win_max = pchan->tx_win_max; chan->sec_level = pchan->sec_level; chan->flags = pchan->flags; security_sk_clone(parent, sk); } else { switch (sk->sk_type) { case SOCK_RAW: chan->chan_type = L2CAP_CHAN_RAW; break; case SOCK_DGRAM: chan->chan_type = L2CAP_CHAN_CONN_LESS; break; case SOCK_SEQPACKET: case SOCK_STREAM: chan->chan_type = L2CAP_CHAN_CONN_ORIENTED; break; } chan->imtu = L2CAP_DEFAULT_MTU; chan->omtu = 0; if (!disable_ertm && sk->sk_type == SOCK_STREAM) { chan->mode = L2CAP_MODE_ERTM; set_bit(CONF_STATE2_DEVICE, &chan->conf_state); } else { chan->mode = L2CAP_MODE_BASIC; } l2cap_chan_set_defaults(chan); } /* Default config options */ chan->flush_to = L2CAP_DEFAULT_FLUSH_TO; chan->data = sk; chan->ops = &l2cap_chan_ops; } static struct proto l2cap_proto = { .name = "L2CAP", .owner = THIS_MODULE, .obj_size = sizeof(struct l2cap_pinfo) }; static struct sock *l2cap_sock_alloc(struct net *net, struct socket *sock, int proto, gfp_t prio) { struct sock *sk; struct l2cap_chan *chan; sk = sk_alloc(net, PF_BLUETOOTH, prio, &l2cap_proto); if (!sk) return NULL; sock_init_data(sock, sk); INIT_LIST_HEAD(&bt_sk(sk)->accept_q); sk->sk_destruct = l2cap_sock_destruct; sk->sk_sndtimeo = L2CAP_CONN_TIMEOUT; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = BT_OPEN; chan = l2cap_chan_create(); if (!chan) { sk_free(sk); return NULL; } l2cap_chan_hold(chan); chan->sk = sk; l2cap_pi(sk)->chan = chan; return sk; } static int l2cap_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); sock->state = SS_UNCONNECTED; if (sock->type != SOCK_SEQPACKET && sock->type != SOCK_STREAM && sock->type != SOCK_DGRAM && sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; if (sock->type == SOCK_RAW && !kern && !capable(CAP_NET_RAW)) return -EPERM; sock->ops = &l2cap_sock_ops; sk = l2cap_sock_alloc(net, sock, protocol, GFP_ATOMIC); if (!sk) return -ENOMEM; l2cap_sock_init(sk, NULL); return 0; } static const struct proto_ops l2cap_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = l2cap_sock_release, .bind = l2cap_sock_bind, .connect = l2cap_sock_connect, .listen = l2cap_sock_listen, .accept = l2cap_sock_accept, .getname = l2cap_sock_getname, .sendmsg = l2cap_sock_sendmsg, .recvmsg = l2cap_sock_recvmsg, .poll = bt_sock_poll, .ioctl = bt_sock_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = l2cap_sock_shutdown, .setsockopt = l2cap_sock_setsockopt, .getsockopt = l2cap_sock_getsockopt }; static const struct net_proto_family l2cap_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = l2cap_sock_create, }; int __init l2cap_init_sockets(void) { int err; err = proto_register(&l2cap_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_L2CAP, &l2cap_sock_family_ops); if (err < 0) goto error; BT_INFO("L2CAP socket layer initialized"); return 0; error: BT_ERR("L2CAP socket registration failed"); proto_unregister(&l2cap_proto); return err; } void l2cap_cleanup_sockets(void) { if (bt_sock_unregister(BTPROTO_L2CAP) < 0) BT_ERR("L2CAP socket unregistration failed"); proto_unregister(&l2cap_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3833_0
crossvul-cpp_data_bad_2575_0
/* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % JJJJJ PPPP EEEEE GGGG % % J P P E G % % J PPPP EEE G GG % % J J P E G G % % JJJ P EEEEE GGG % % % % % % Read/Write JPEG Image Format % % % % Software Design % % Cristy % % July 1992 % % % % % % Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization % % dedicated to making software imaging solutions freely available. % % % % You may not use this file except in compliance with the License. You may % % obtain a copy of the License at % % % % https://www.imagemagick.org/script/license.php % % % % Unless required by applicable law or agreed to in writing, software % % distributed under the License is distributed on an "AS IS" BASIS, % % WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. % % See the License for the specific language governing permissions and % % limitations under the License. % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % This software is based in part on the work of the Independent JPEG Group. % See ftp://ftp.uu.net/graphics/jpeg/jpegsrc.v6b.tar.gz for copyright and % licensing restrictions. Blob support contributed by Glenn Randers-Pehrson. % % */ /* Include declarations. */ #include "magick/studio.h" #include "magick/artifact.h" #include "magick/attribute.h" #include "magick/blob.h" #include "magick/blob-private.h" #include "magick/cache.h" #include "magick/color.h" #include "magick/colormap-private.h" #include "magick/color-private.h" #include "magick/colormap.h" #include "magick/colorspace.h" #include "magick/colorspace-private.h" #include "magick/constitute.h" #include "magick/exception.h" #include "magick/exception-private.h" #include "magick/geometry.h" #include "magick/image.h" #include "magick/image-private.h" #include "magick/list.h" #include "magick/log.h" #include "magick/magick.h" #include "magick/memory_.h" #include "magick/module.h" #include "magick/monitor.h" #include "magick/monitor-private.h" #include "magick/option.h" #include "magick/option-private.h" #include "magick/pixel-accessor.h" #include "magick/profile.h" #include "magick/property.h" #include "magick/quantum-private.h" #include "magick/resource_.h" #include "magick/semaphore.h" #include "magick/splay-tree.h" #include "magick/static.h" #include "magick/string_.h" #include "magick/string-private.h" #include "magick/token.h" #include "magick/utility.h" #include "magick/xml-tree.h" #include <setjmp.h> #if defined(MAGICKCORE_JPEG_DELEGATE) #define JPEG_INTERNAL_OPTIONS #if defined(__MINGW32__) || defined(__MINGW64__) # define XMD_H 1 /* Avoid conflicting typedef for INT32 */ #endif #undef HAVE_STDLIB_H #include "jpeglib.h" #include "jerror.h" #endif /* Define declarations. */ #define ICC_MARKER (JPEG_APP0+2) #define ICC_PROFILE "ICC_PROFILE" #define IPTC_MARKER (JPEG_APP0+13) #define XML_MARKER (JPEG_APP0+1) #define MaxBufferExtent 16384 /* Typedef declarations. */ #if defined(MAGICKCORE_JPEG_DELEGATE) typedef struct _DestinationManager { struct jpeg_destination_mgr manager; Image *image; JOCTET *buffer; } DestinationManager; typedef struct _ErrorManager { Image *image; MagickBooleanType finished; StringInfo *profile; jmp_buf error_recovery; } ErrorManager; typedef struct _SourceManager { struct jpeg_source_mgr manager; Image *image; JOCTET *buffer; boolean start_of_blob; } SourceManager; #endif typedef struct _QuantizationTable { char *slot, *description; size_t width, height; double divisor; unsigned int *levels; } QuantizationTable; /* Forward declarations. */ #if defined(MAGICKCORE_JPEG_DELEGATE) static MagickBooleanType WriteJPEGImage(const ImageInfo *,Image *); #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % I s J P E G % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % IsJPEG() returns MagickTrue if the image format type, identified by the % magick string, is JPEG. % % The format of the IsJPEG method is: % % MagickBooleanType IsJPEG(const unsigned char *magick,const size_t length) % % A description of each parameter follows: % % o magick: compare image format pattern against these bytes. % % o length: Specifies the length of the magick string. % */ static MagickBooleanType IsJPEG(const unsigned char *magick,const size_t length) { if (length < 3) return(MagickFalse); if (memcmp(magick,"\377\330\377",3) == 0) return(MagickTrue); return(MagickFalse); } #if defined(MAGICKCORE_JPEG_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e a d J P E G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % ReadJPEGImage() reads a JPEG image file and returns it. It allocates % the memory necessary for the new Image structure and returns a pointer to % the new image. % % The format of the ReadJPEGImage method is: % % Image *ReadJPEGImage(const ImageInfo *image_info, % ExceptionInfo *exception) % % A description of each parameter follows: % % o image_info: the image info. % % o exception: return any errors or warnings in this structure. % */ static boolean FillInputBuffer(j_decompress_ptr cinfo) { SourceManager *source; source=(SourceManager *) cinfo->src; source->manager.bytes_in_buffer=(size_t) ReadBlob(source->image, MaxBufferExtent,source->buffer); if (source->manager.bytes_in_buffer == 0) { if (source->start_of_blob != FALSE) ERREXIT(cinfo,JERR_INPUT_EMPTY); WARNMS(cinfo,JWRN_JPEG_EOF); source->buffer[0]=(JOCTET) 0xff; source->buffer[1]=(JOCTET) JPEG_EOI; source->manager.bytes_in_buffer=2; } source->manager.next_input_byte=source->buffer; source->start_of_blob=FALSE; return(TRUE); } static int GetCharacter(j_decompress_ptr jpeg_info) { if (jpeg_info->src->bytes_in_buffer == 0) (void) (*jpeg_info->src->fill_input_buffer)(jpeg_info); jpeg_info->src->bytes_in_buffer--; return((int) GETJOCTET(*jpeg_info->src->next_input_byte++)); } static void InitializeSource(j_decompress_ptr cinfo) { SourceManager *source; source=(SourceManager *) cinfo->src; source->start_of_blob=TRUE; } static MagickBooleanType IsITUFaxImage(const Image *image) { const StringInfo *profile; const unsigned char *datum; profile=GetImageProfile(image,"8bim"); if (profile == (const StringInfo *) NULL) return(MagickFalse); if (GetStringInfoLength(profile) < 5) return(MagickFalse); datum=GetStringInfoDatum(profile); if ((datum[0] == 0x47) && (datum[1] == 0x33) && (datum[2] == 0x46) && (datum[3] == 0x41) && (datum[4] == 0x58)) return(MagickTrue); return(MagickFalse); } static void JPEGErrorHandler(j_common_ptr jpeg_info) { char message[JMSG_LENGTH_MAX]; ErrorManager *error_manager; Image *image; *message='\0'; error_manager=(ErrorManager *) jpeg_info->client_data; image=error_manager->image; (jpeg_info->err->format_message)(jpeg_info,message); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "[%s] JPEG Trace: \"%s\"",image->filename,message); if (error_manager->finished != MagickFalse) (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageWarning,(char *) message,"`%s'",image->filename); else (void) ThrowMagickException(&image->exception,GetMagickModule(), CorruptImageError,(char *) message,"`%s'",image->filename); longjmp(error_manager->error_recovery,1); } static MagickBooleanType JPEGWarningHandler(j_common_ptr jpeg_info,int level) { #define JPEGExcessiveWarnings 1000 char message[JMSG_LENGTH_MAX]; ErrorManager *error_manager; Image *image; *message='\0'; error_manager=(ErrorManager *) jpeg_info->client_data; image=error_manager->image; if (level < 0) { /* Process warning message. */ (jpeg_info->err->format_message)(jpeg_info,message); if (jpeg_info->err->num_warnings++ < JPEGExcessiveWarnings) ThrowBinaryException(CorruptImageWarning,(char *) message, image->filename); } else if ((image->debug != MagickFalse) && (level >= jpeg_info->err->trace_level)) { /* Process trace message. */ (jpeg_info->err->format_message)(jpeg_info,message); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "[%s] JPEG Trace: \"%s\"",image->filename,message); } return(MagickTrue); } static boolean ReadComment(j_decompress_ptr jpeg_info) { ErrorManager *error_manager; Image *image; register unsigned char *p; register ssize_t i; size_t length; StringInfo *comment; /* Determine length of comment. */ error_manager=(ErrorManager *) jpeg_info->client_data; image=error_manager->image; length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=GetCharacter(jpeg_info); if (length <= 2) return(TRUE); length-=2; comment=BlobToStringInfo((const void *) NULL,length); if (comment == (StringInfo *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } /* Read comment. */ error_manager->profile=comment; p=GetStringInfoDatum(comment); for (i=0; i < (ssize_t) GetStringInfoLength(comment); i++) *p++=(unsigned char) GetCharacter(jpeg_info); *p='\0'; error_manager->profile=NULL; p=GetStringInfoDatum(comment); (void) SetImageProperty(image,"comment",(const char *) p); comment=DestroyStringInfo(comment); return(TRUE); } static boolean ReadICCProfile(j_decompress_ptr jpeg_info) { char magick[12]; ErrorManager *error_manager; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *icc_profile, *profile; /* Read color profile. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) (void) GetCharacter(jpeg_info); return(TRUE); } for (i=0; i < 12; i++) magick[i]=(char) GetCharacter(jpeg_info); if (LocaleCompare(magick,ICC_PROFILE) != 0) { /* Not a ICC profile, return. */ for (i=0; i < (ssize_t) (length-12); i++) (void) GetCharacter(jpeg_info); return(TRUE); } (void) GetCharacter(jpeg_info); /* id */ (void) GetCharacter(jpeg_info); /* markers */ length-=14; error_manager=(ErrorManager *) jpeg_info->client_data; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=(ssize_t) GetStringInfoLength(profile)-1; i >= 0; i--) *p++=(unsigned char) GetCharacter(jpeg_info); error_manager->profile=NULL; icc_profile=(StringInfo *) GetImageProfile(image,"icc"); if (icc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(icc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"icc",profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: ICC, %.20g bytes",(double) length); return(TRUE); } static boolean ReadIPTCProfile(j_decompress_ptr jpeg_info) { char magick[MaxTextExtent]; ErrorManager *error_manager; Image *image; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *iptc_profile, *profile; /* Determine length of binary data stored here. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); length-=2; if (length <= 14) { while (length-- > 0) (void) GetCharacter(jpeg_info); return(TRUE); } /* Validate that this was written as a Photoshop resource format slug. */ for (i=0; i < 10; i++) magick[i]=(char) GetCharacter(jpeg_info); magick[10]='\0'; length-=10; if (length <= 10) return(TRUE); if (LocaleCompare(magick,"Photoshop ") != 0) { /* Not a IPTC profile, return. */ for (i=0; i < (ssize_t) length; i++) (void) GetCharacter(jpeg_info); return(TRUE); } /* Remove the version number. */ for (i=0; i < 4; i++) (void) GetCharacter(jpeg_info); if (length <= 11) return(TRUE); length-=4; error_manager=(ErrorManager *) jpeg_info->client_data; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) *p++=(unsigned char) GetCharacter(jpeg_info); error_manager->profile=NULL; iptc_profile=(StringInfo *) GetImageProfile(image,"8bim"); if (iptc_profile != (StringInfo *) NULL) { ConcatenateStringInfo(iptc_profile,profile); profile=DestroyStringInfo(profile); } else { status=SetImageProfile(image,"8bim",profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: iptc, %.20g bytes",(double) length); return(TRUE); } static boolean ReadProfile(j_decompress_ptr jpeg_info) { char name[MaxTextExtent]; const StringInfo *previous_profile; ErrorManager *error_manager; Image *image; int marker; MagickBooleanType status; register ssize_t i; register unsigned char *p; size_t length; StringInfo *profile; /* Read generic profile. */ length=(size_t) ((size_t) GetCharacter(jpeg_info) << 8); length+=(size_t) GetCharacter(jpeg_info); if (length <= 2) return(TRUE); length-=2; marker=jpeg_info->unread_marker-JPEG_APP0; (void) FormatLocaleString(name,MaxTextExtent,"APP%d",marker); error_manager=(ErrorManager *) jpeg_info->client_data; image=error_manager->image; profile=BlobToStringInfo((const void *) NULL,length); if (profile == (StringInfo *) NULL) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } error_manager->profile=profile; p=GetStringInfoDatum(profile); for (i=0; i < (ssize_t) GetStringInfoLength(profile); i++) *p++=(unsigned char) GetCharacter(jpeg_info); error_manager->profile=NULL; if (marker == 1) { p=GetStringInfoDatum(profile); if ((length > 4) && (LocaleNCompare((char *) p,"exif",4) == 0)) (void) CopyMagickString(name,"exif",MaxTextExtent); if ((length > 5) && (LocaleNCompare((char *) p,"http:",5) == 0)) { ssize_t j; /* Extract namespace from XMP profile. */ p=GetStringInfoDatum(profile); for (j=0; j < (ssize_t) GetStringInfoLength(profile); j++) { if (*p == '\0') break; p++; } if (j < (ssize_t) GetStringInfoLength(profile)) (void) DestroyStringInfo(SplitStringInfo(profile,(size_t) (j+1))); (void) CopyMagickString(name,"xmp",MaxTextExtent); } } previous_profile=GetImageProfile(image,name); if (previous_profile != (const StringInfo *) NULL) { size_t length; length=GetStringInfoLength(profile); SetStringInfoLength(profile,GetStringInfoLength(profile)+ GetStringInfoLength(previous_profile)); (void) memmove(GetStringInfoDatum(profile)+ GetStringInfoLength(previous_profile),GetStringInfoDatum(profile), length); (void) memcpy(GetStringInfoDatum(profile), GetStringInfoDatum(previous_profile), GetStringInfoLength(previous_profile)); } status=SetImageProfile(image,name,profile); profile=DestroyStringInfo(profile); if (status == MagickFalse) { (void) ThrowMagickException(&image->exception,GetMagickModule(), ResourceLimitError,"MemoryAllocationFailed","`%s'",image->filename); return(FALSE); } if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Profile: %s, %.20g bytes",name,(double) length); return(TRUE); } static void SkipInputData(j_decompress_ptr cinfo,long number_bytes) { SourceManager *source; if (number_bytes <= 0) return; source=(SourceManager *) cinfo->src; while (number_bytes > (long) source->manager.bytes_in_buffer) { number_bytes-=(long) source->manager.bytes_in_buffer; (void) FillInputBuffer(cinfo); } source->manager.next_input_byte+=number_bytes; source->manager.bytes_in_buffer-=number_bytes; } static void TerminateSource(j_decompress_ptr cinfo) { (void) cinfo; } static void JPEGSourceManager(j_decompress_ptr cinfo,Image *image) { SourceManager *source; cinfo->src=(struct jpeg_source_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo,JPOOL_IMAGE,sizeof(SourceManager)); source=(SourceManager *) cinfo->src; source->buffer=(JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo,JPOOL_IMAGE,MaxBufferExtent*sizeof(JOCTET)); source=(SourceManager *) cinfo->src; source->manager.init_source=InitializeSource; source->manager.fill_input_buffer=FillInputBuffer; source->manager.skip_input_data=SkipInputData; source->manager.resync_to_restart=jpeg_resync_to_restart; source->manager.term_source=TerminateSource; source->manager.bytes_in_buffer=0; source->manager.next_input_byte=NULL; source->image=image; } static void JPEGSetImageQuality(struct jpeg_decompress_struct *jpeg_info, Image *image) { image->quality=UndefinedCompressionQuality; #if defined(D_PROGRESSIVE_SUPPORTED) if (image->compression == LosslessJPEGCompression) { image->quality=100; (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Quality: 100 (lossless)"); } else #endif { ssize_t j, qvalue, sum; register ssize_t i; /* Determine the JPEG compression quality from the quantization tables. */ sum=0; for (i=0; i < NUM_QUANT_TBLS; i++) { if (jpeg_info->quant_tbl_ptrs[i] != NULL) for (j=0; j < DCTSIZE2; j++) sum+=jpeg_info->quant_tbl_ptrs[i]->quantval[j]; } if ((jpeg_info->quant_tbl_ptrs[0] != NULL) && (jpeg_info->quant_tbl_ptrs[1] != NULL)) { ssize_t hash[101] = { 1020, 1015, 932, 848, 780, 735, 702, 679, 660, 645, 632, 623, 613, 607, 600, 594, 589, 585, 581, 571, 555, 542, 529, 514, 494, 474, 457, 439, 424, 410, 397, 386, 373, 364, 351, 341, 334, 324, 317, 309, 299, 294, 287, 279, 274, 267, 262, 257, 251, 247, 243, 237, 232, 227, 222, 217, 213, 207, 202, 198, 192, 188, 183, 177, 173, 168, 163, 157, 153, 148, 143, 139, 132, 128, 125, 119, 115, 108, 104, 99, 94, 90, 84, 79, 74, 70, 64, 59, 55, 49, 45, 40, 34, 30, 25, 20, 15, 11, 6, 4, 0 }, sums[101] = { 32640, 32635, 32266, 31495, 30665, 29804, 29146, 28599, 28104, 27670, 27225, 26725, 26210, 25716, 25240, 24789, 24373, 23946, 23572, 22846, 21801, 20842, 19949, 19121, 18386, 17651, 16998, 16349, 15800, 15247, 14783, 14321, 13859, 13535, 13081, 12702, 12423, 12056, 11779, 11513, 11135, 10955, 10676, 10392, 10208, 9928, 9747, 9564, 9369, 9193, 9017, 8822, 8639, 8458, 8270, 8084, 7896, 7710, 7527, 7347, 7156, 6977, 6788, 6607, 6422, 6236, 6054, 5867, 5684, 5495, 5305, 5128, 4945, 4751, 4638, 4442, 4248, 4065, 3888, 3698, 3509, 3326, 3139, 2957, 2775, 2586, 2405, 2216, 2037, 1846, 1666, 1483, 1297, 1109, 927, 735, 554, 375, 201, 128, 0 }; qvalue=(ssize_t) (jpeg_info->quant_tbl_ptrs[0]->quantval[2]+ jpeg_info->quant_tbl_ptrs[0]->quantval[53]+ jpeg_info->quant_tbl_ptrs[1]->quantval[0]+ jpeg_info->quant_tbl_ptrs[1]->quantval[DCTSIZE2-1]); for (i=0; i < 100; i++) { if ((qvalue < hash[i]) && (sum < sums[i])) continue; if (((qvalue <= hash[i]) && (sum <= sums[i])) || (i >= 50)) image->quality=(size_t) i+1; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Quality: %.20g (%s)",(double) i+1,(qvalue <= hash[i]) && (sum <= sums[i]) ? "exact" : "approximate"); break; } } else if (jpeg_info->quant_tbl_ptrs[0] != NULL) { ssize_t hash[101] = { 510, 505, 422, 380, 355, 338, 326, 318, 311, 305, 300, 297, 293, 291, 288, 286, 284, 283, 281, 280, 279, 278, 277, 273, 262, 251, 243, 233, 225, 218, 211, 205, 198, 193, 186, 181, 177, 172, 168, 164, 158, 156, 152, 148, 145, 142, 139, 136, 133, 131, 129, 126, 123, 120, 118, 115, 113, 110, 107, 105, 102, 100, 97, 94, 92, 89, 87, 83, 81, 79, 76, 74, 70, 68, 66, 63, 61, 57, 55, 52, 50, 48, 44, 42, 39, 37, 34, 31, 29, 26, 24, 21, 18, 16, 13, 11, 8, 6, 3, 2, 0 }, sums[101] = { 16320, 16315, 15946, 15277, 14655, 14073, 13623, 13230, 12859, 12560, 12240, 11861, 11456, 11081, 10714, 10360, 10027, 9679, 9368, 9056, 8680, 8331, 7995, 7668, 7376, 7084, 6823, 6562, 6345, 6125, 5939, 5756, 5571, 5421, 5240, 5086, 4976, 4829, 4719, 4616, 4463, 4393, 4280, 4166, 4092, 3980, 3909, 3835, 3755, 3688, 3621, 3541, 3467, 3396, 3323, 3247, 3170, 3096, 3021, 2952, 2874, 2804, 2727, 2657, 2583, 2509, 2437, 2362, 2290, 2211, 2136, 2068, 1996, 1915, 1858, 1773, 1692, 1620, 1552, 1477, 1398, 1326, 1251, 1179, 1109, 1031, 961, 884, 814, 736, 667, 592, 518, 441, 369, 292, 221, 151, 86, 64, 0 }; qvalue=(ssize_t) (jpeg_info->quant_tbl_ptrs[0]->quantval[2]+ jpeg_info->quant_tbl_ptrs[0]->quantval[53]); for (i=0; i < 100; i++) { if ((qvalue < hash[i]) && (sum < sums[i])) continue; if (((qvalue <= hash[i]) && (sum <= sums[i])) || (i >= 50)) image->quality=(size_t) i+1; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Quality: %.20g (%s)",(double) i+1,(qvalue <= hash[i]) && (sum <= sums[i]) ? "exact" : "approximate"); break; } } } } static void JPEGSetImageSamplingFactor(struct jpeg_decompress_struct *jpeg_info, Image *image) { char sampling_factor[MaxTextExtent]; switch (jpeg_info->out_color_space) { case JCS_CMYK: { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: CMYK"); (void) FormatLocaleString(sampling_factor,MaxTextExtent, "%dx%d,%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor, jpeg_info->comp_info[0].v_samp_factor, jpeg_info->comp_info[1].h_samp_factor, jpeg_info->comp_info[1].v_samp_factor, jpeg_info->comp_info[2].h_samp_factor, jpeg_info->comp_info[2].v_samp_factor, jpeg_info->comp_info[3].h_samp_factor, jpeg_info->comp_info[3].v_samp_factor); break; } case JCS_GRAYSCALE: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: GRAYSCALE"); (void) FormatLocaleString(sampling_factor,MaxTextExtent,"%dx%d", jpeg_info->comp_info[0].h_samp_factor, jpeg_info->comp_info[0].v_samp_factor); break; } case JCS_RGB: { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: RGB"); (void) FormatLocaleString(sampling_factor,MaxTextExtent, "%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor, jpeg_info->comp_info[0].v_samp_factor, jpeg_info->comp_info[1].h_samp_factor, jpeg_info->comp_info[1].v_samp_factor, jpeg_info->comp_info[2].h_samp_factor, jpeg_info->comp_info[2].v_samp_factor); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d", jpeg_info->out_color_space); (void) FormatLocaleString(sampling_factor,MaxTextExtent, "%dx%d,%dx%d,%dx%d,%dx%d",jpeg_info->comp_info[0].h_samp_factor, jpeg_info->comp_info[0].v_samp_factor, jpeg_info->comp_info[1].h_samp_factor, jpeg_info->comp_info[1].v_samp_factor, jpeg_info->comp_info[2].h_samp_factor, jpeg_info->comp_info[2].v_samp_factor, jpeg_info->comp_info[3].h_samp_factor, jpeg_info->comp_info[3].v_samp_factor); break; } } (void) SetImageProperty(image,"jpeg:sampling-factor",sampling_factor); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Sampling Factors: %s", sampling_factor); } static Image *ReadJPEGImage(const ImageInfo *image_info, ExceptionInfo *exception) { char value[MaxTextExtent]; const char *option; ErrorManager error_manager; Image *image; IndexPacket index; JSAMPLE *volatile jpeg_pixels; JSAMPROW scanline[1]; MagickBooleanType debug, status; MagickSizeType number_pixels; MemoryInfo *memory_info; register ssize_t i; struct jpeg_decompress_struct jpeg_info; struct jpeg_error_mgr jpeg_error; register JSAMPLE *p; size_t units; ssize_t y; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); if (image_info->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s", image_info->filename); assert(exception != (ExceptionInfo *) NULL); assert(exception->signature == MagickSignature); debug=IsEventLogging(); (void) debug; image=AcquireImage(image_info); status=OpenBlob(image_info,image,ReadBinaryBlobMode,exception); if (status == MagickFalse) { image=DestroyImageList(image); return((Image *) NULL); } /* Verify that file size large enough to contain a JPEG datastream. */ if (GetBlobSize(image) < 107) ThrowReaderException(CorruptImageError,"InsufficientImageDataInFile"); /* Initialize JPEG parameters. */ (void) ResetMagickMemory(&error_manager,0,sizeof(error_manager)); (void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info)); (void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error)); jpeg_info.err=jpeg_std_error(&jpeg_error); jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler; jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler; memory_info=(MemoryInfo *) NULL; error_manager.image=image; if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_decompress(&jpeg_info); if (error_manager.profile != (StringInfo *) NULL) error_manager.profile=DestroyStringInfo(error_manager.profile); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); InheritException(exception,&image->exception); return(DestroyImage(image)); } jpeg_info.client_data=(void *) &error_manager; jpeg_create_decompress(&jpeg_info); JPEGSourceManager(&jpeg_info,image); jpeg_set_marker_processor(&jpeg_info,JPEG_COM,ReadComment); option=GetImageOption(image_info,"profile:skip"); if (IsOptionMember("ICC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,ICC_MARKER,ReadICCProfile); if (IsOptionMember("IPTC",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,IPTC_MARKER,ReadIPTCProfile); for (i=1; i < 16; i++) if ((i != 2) && (i != 13) && (i != 14)) if (IsOptionMember("APP",option) == MagickFalse) jpeg_set_marker_processor(&jpeg_info,(int) (JPEG_APP0+i),ReadProfile); i=(ssize_t) jpeg_read_header(&jpeg_info,TRUE); if ((image_info->colorspace == YCbCrColorspace) || (image_info->colorspace == Rec601YCbCrColorspace) || (image_info->colorspace == Rec709YCbCrColorspace)) jpeg_info.out_color_space=JCS_YCbCr; /* Set image resolution. */ units=0; if ((jpeg_info.saw_JFIF_marker != 0) && (jpeg_info.X_density != 1) && (jpeg_info.Y_density != 1)) { image->x_resolution=(double) jpeg_info.X_density; image->y_resolution=(double) jpeg_info.Y_density; units=(size_t) jpeg_info.density_unit; } if (units == 1) image->units=PixelsPerInchResolution; if (units == 2) image->units=PixelsPerCentimeterResolution; number_pixels=(MagickSizeType) image->columns*image->rows; option=GetImageOption(image_info,"jpeg:size"); if ((option != (const char *) NULL) && (jpeg_info.out_color_space != JCS_YCbCr)) { double scale_factor; GeometryInfo geometry_info; MagickStatusType flags; /* Scale the image. */ flags=ParseGeometry(option,&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; jpeg_calc_output_dimensions(&jpeg_info); image->magick_columns=jpeg_info.output_width; image->magick_rows=jpeg_info.output_height; scale_factor=1.0; if (geometry_info.rho != 0.0) scale_factor=jpeg_info.output_width/geometry_info.rho; if ((geometry_info.sigma != 0.0) && (scale_factor > (jpeg_info.output_height/geometry_info.sigma))) scale_factor=jpeg_info.output_height/geometry_info.sigma; jpeg_info.scale_num=1U; jpeg_info.scale_denom=(unsigned int) scale_factor; jpeg_calc_output_dimensions(&jpeg_info); if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Scale factor: %.20g",(double) scale_factor); } #if (JPEG_LIB_VERSION >= 61) && defined(D_PROGRESSIVE_SUPPORTED) #if defined(D_LOSSLESS_SUPPORTED) image->interlace=jpeg_info.process == JPROC_PROGRESSIVE ? JPEGInterlace : NoInterlace; image->compression=jpeg_info.process == JPROC_LOSSLESS ? LosslessJPEGCompression : JPEGCompression; if (jpeg_info.data_precision > 8) (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "12-bit JPEG not supported. Reducing pixel data to 8 bits","`%s'", image->filename); if (jpeg_info.data_precision == 16) jpeg_info.data_precision=12; #else image->interlace=jpeg_info.progressive_mode != 0 ? JPEGInterlace : NoInterlace; image->compression=JPEGCompression; #endif #else image->compression=JPEGCompression; image->interlace=JPEGInterlace; #endif option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) { /* Let the JPEG library quantize for us. */ jpeg_info.quantize_colors=TRUE; jpeg_info.desired_number_of_colors=(int) StringToUnsignedLong(option); } option=GetImageOption(image_info,"jpeg:block-smoothing"); if (option != (const char *) NULL) jpeg_info.do_block_smoothing=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; jpeg_info.dct_method=JDCT_FLOAT; option=GetImageOption(image_info,"jpeg:dct-method"); if (option != (const char *) NULL) switch (*option) { case 'D': case 'd': { if (LocaleCompare(option,"default") == 0) jpeg_info.dct_method=JDCT_DEFAULT; break; } case 'F': case 'f': { if (LocaleCompare(option,"fastest") == 0) jpeg_info.dct_method=JDCT_FASTEST; if (LocaleCompare(option,"float") == 0) jpeg_info.dct_method=JDCT_FLOAT; break; } case 'I': case 'i': { if (LocaleCompare(option,"ifast") == 0) jpeg_info.dct_method=JDCT_IFAST; if (LocaleCompare(option,"islow") == 0) jpeg_info.dct_method=JDCT_ISLOW; break; } } option=GetImageOption(image_info,"jpeg:fancy-upsampling"); if (option != (const char *) NULL) jpeg_info.do_fancy_upsampling=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; (void) jpeg_start_decompress(&jpeg_info); image->columns=jpeg_info.output_width; image->rows=jpeg_info.output_height; image->depth=(size_t) jpeg_info.data_precision; switch (jpeg_info.out_color_space) { case JCS_RGB: default: { (void) SetImageColorspace(image,sRGBColorspace); break; } case JCS_GRAYSCALE: { (void) SetImageColorspace(image,GRAYColorspace); break; } case JCS_YCbCr: { (void) SetImageColorspace(image,YCbCrColorspace); break; } case JCS_CMYK: { (void) SetImageColorspace(image,CMYKColorspace); break; } } if (IsITUFaxImage(image) != MagickFalse) { (void) SetImageColorspace(image,LabColorspace); jpeg_info.out_color_space=JCS_YCbCr; } option=GetImageOption(image_info,"jpeg:colors"); if (option != (const char *) NULL) if (AcquireImageColormap(image,StringToUnsignedLong(option)) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components == 1) && (jpeg_info.quantize_colors == 0)) { size_t colors; colors=(size_t) GetQuantumRange(image->depth)+1; if (AcquireImageColormap(image,colors) == MagickFalse) { InheritException(exception,&image->exception); return(DestroyImageList(image)); } } if (image->debug != MagickFalse) { if (image->interlace != NoInterlace) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: progressive"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: nonprogressive"); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Data precision: %d", (int) jpeg_info.data_precision); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Geometry: %dx%d", (int) jpeg_info.output_width,(int) jpeg_info.output_height); } JPEGSetImageQuality(&jpeg_info,image); JPEGSetImageSamplingFactor(&jpeg_info,image); (void) FormatLocaleString(value,MaxTextExtent,"%.20g",(double) jpeg_info.out_color_space); (void) SetImageProperty(image,"jpeg:colorspace",value); if (image_info->ping != MagickFalse) { jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } status=SetImageExtent(image,image->columns,image->rows); if (status == MagickFalse) { jpeg_destroy_decompress(&jpeg_info); InheritException(exception,&image->exception); return(DestroyImageList(image)); } if ((jpeg_info.output_components != 1) && (jpeg_info.output_components != 3) && (jpeg_info.output_components != 4)) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(CorruptImageError,"ImageTypeNotSupported"); } memory_info=AcquireVirtualMemory((size_t) image->columns, jpeg_info.output_components*sizeof(*jpeg_pixels)); if (memory_info == (MemoryInfo *) NULL) { jpeg_destroy_decompress(&jpeg_info); ThrowReaderException(ResourceLimitError,"MemoryAllocationFailed"); } jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info); /* Convert JPEG pixels to pixel packets. */ if (setjmp(error_manager.error_recovery) != 0) { if (memory_info != (MemoryInfo *) NULL) memory_info=RelinquishVirtualMemory(memory_info); jpeg_destroy_decompress(&jpeg_info); (void) CloseBlob(image); number_pixels=(MagickSizeType) image->columns*image->rows; if (number_pixels != 0) return(GetFirstImageInList(image)); return(DestroyImage(image)); } if (jpeg_info.quantize_colors != 0) { image->colors=(size_t) jpeg_info.actual_number_of_colors; if (jpeg_info.out_color_space == JCS_GRAYSCALE) for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=image->colormap[i].red; image->colormap[i].blue=image->colormap[i].red; image->colormap[i].opacity=OpaqueOpacity; } else for (i=0; i < (ssize_t) image->colors; i++) { image->colormap[i].red=ScaleCharToQuantum(jpeg_info.colormap[0][i]); image->colormap[i].green=ScaleCharToQuantum(jpeg_info.colormap[1][i]); image->colormap[i].blue=ScaleCharToQuantum(jpeg_info.colormap[2][i]); image->colormap[i].opacity=OpaqueOpacity; } } scanline[0]=(JSAMPROW) jpeg_pixels; for (y=0; y < (ssize_t) image->rows; y++) { register IndexPacket *magick_restrict indexes; register ssize_t x; register PixelPacket *magick_restrict q; if (jpeg_read_scanlines(&jpeg_info,scanline,1) != 1) { (void) ThrowMagickException(exception,GetMagickModule(), CorruptImageWarning,"SkipToSyncByte","`%s'",image->filename); continue; } p=jpeg_pixels; q=QueueAuthenticPixels(image,0,y,image->columns,1,exception); if (q == (PixelPacket *) NULL) break; indexes=GetAuthenticIndexQueue(image); if (jpeg_info.data_precision > 8) { unsigned short scale; scale=65535/(unsigned short) GetQuantumRange((size_t) jpeg_info.data_precision); if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { size_t pixel; pixel=(size_t) (scale*GETJSAMPLE(*p)); index=ConstrainColormapIndex(image,pixel); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelGreen(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlue(q,ScaleShortToQuantum((unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelMagenta(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelYellow(q,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelBlack(indexes+x,QuantumRange-ScaleShortToQuantum( (unsigned short) (scale*GETJSAMPLE(*p++)))); SetPixelOpacity(q,OpaqueOpacity); q++; } } else if (jpeg_info.output_components == 1) for (x=0; x < (ssize_t) image->columns; x++) { index=ConstrainColormapIndex(image,(size_t) GETJSAMPLE(*p)); SetPixelIndex(indexes+x,index); SetPixelRGBO(q,image->colormap+(ssize_t) index); p++; q++; } else if (image->colorspace != CMYKColorspace) for (x=0; x < (ssize_t) image->columns; x++) { SetPixelRed(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelGreen(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlue(q,ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } else for (x=0; x < (ssize_t) image->columns; x++) { SetPixelCyan(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelMagenta(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelYellow(q,QuantumRange-ScaleCharToQuantum((unsigned char) GETJSAMPLE(*p++))); SetPixelBlack(indexes+x,QuantumRange-ScaleCharToQuantum( (unsigned char) GETJSAMPLE(*p++))); SetPixelOpacity(q,OpaqueOpacity); q++; } if (SyncAuthenticPixels(image,exception) == MagickFalse) break; status=SetImageProgress(image,LoadImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) { jpeg_abort_decompress(&jpeg_info); break; } } if (status != MagickFalse) { error_manager.finished=MagickTrue; if (setjmp(error_manager.error_recovery) == 0) (void) jpeg_finish_decompress(&jpeg_info); } /* Free jpeg resources. */ jpeg_destroy_decompress(&jpeg_info); memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(GetFirstImageInList(image)); } #endif /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % R e g i s t e r J P E G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % RegisterJPEGImage() adds properties for the JPEG image format to % the list of supported formats. The properties include the image format % tag, a method to read and/or write the format, whether the format % supports the saving of more than one frame to the same file or blob, % whether the format supports native in-memory I/O, and a brief % description of the format. % % The format of the RegisterJPEGImage method is: % % size_t RegisterJPEGImage(void) % */ ModuleExport size_t RegisterJPEGImage(void) { char version[MaxTextExtent]; MagickInfo *entry; static const char description[] = "Joint Photographic Experts Group JFIF format"; *version='\0'; #if defined(JPEG_LIB_VERSION) (void) FormatLocaleString(version,MaxTextExtent,"%d",JPEG_LIB_VERSION); #endif entry=SetMagickInfo("JPE"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->magick=(IsImageFormatHandler *) IsJPEG; entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("JPS"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); entry=SetMagickInfo("PJPEG"); #if (JPEG_LIB_VERSION < 80) && !defined(LIBJPEG_TURBO_VERSION) entry->thread_support=NoThreadSupport; #endif #if defined(MAGICKCORE_JPEG_DELEGATE) entry->decoder=(DecodeImageHandler *) ReadJPEGImage; entry->encoder=(EncodeImageHandler *) WriteJPEGImage; #endif entry->adjoin=MagickFalse; entry->seekable_stream=MagickTrue; entry->description=ConstantString(description); if (*version != '\0') entry->version=ConstantString(version); entry->mime_type=ConstantString("image/jpeg"); entry->module=ConstantString("JPEG"); (void) RegisterMagickInfo(entry); return(MagickImageCoderSignature); } /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % U n r e g i s t e r J P E G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % UnregisterJPEGImage() removes format registrations made by the % JPEG module from the list of supported formats. % % The format of the UnregisterJPEGImage method is: % % UnregisterJPEGImage(void) % */ ModuleExport void UnregisterJPEGImage(void) { (void) UnregisterMagickInfo("PJPG"); (void) UnregisterMagickInfo("JPS"); (void) UnregisterMagickInfo("JPG"); (void) UnregisterMagickInfo("JPG"); (void) UnregisterMagickInfo("JPEG"); (void) UnregisterMagickInfo("JPE"); } #if defined(MAGICKCORE_JPEG_DELEGATE) /* %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % % % % % % W r i t e J P E G I m a g e % % % % % % % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% % % WriteJPEGImage() writes a JPEG image file and returns it. It % allocates the memory necessary for the new Image structure and returns a % pointer to the new image. % % The format of the WriteJPEGImage method is: % % MagickBooleanType WriteJPEGImage(const ImageInfo *image_info, % Image *image) % % A description of each parameter follows: % % o image_info: the image info. % % o jpeg_image: The image. % % */ static QuantizationTable *DestroyQuantizationTable(QuantizationTable *table) { assert(table != (QuantizationTable *) NULL); if (table->slot != (char *) NULL) table->slot=DestroyString(table->slot); if (table->description != (char *) NULL) table->description=DestroyString(table->description); if (table->levels != (unsigned int *) NULL) table->levels=(unsigned int *) RelinquishMagickMemory(table->levels); table=(QuantizationTable *) RelinquishMagickMemory(table); return(table); } static boolean EmptyOutputBuffer(j_compress_ptr cinfo) { DestinationManager *destination; destination=(DestinationManager *) cinfo->dest; destination->manager.free_in_buffer=(size_t) WriteBlob(destination->image, MaxBufferExtent,destination->buffer); if (destination->manager.free_in_buffer != MaxBufferExtent) ERREXIT(cinfo,JERR_FILE_WRITE); destination->manager.next_output_byte=destination->buffer; return(TRUE); } static QuantizationTable *GetQuantizationTable(const char *filename, const char *slot,ExceptionInfo *exception) { char *p, *xml; const char *attribute, *content; double value; register ssize_t i; QuantizationTable *table; size_t length; ssize_t j; XMLTreeInfo *description, *levels, *quantization_tables, *table_iterator; (void) LogMagickEvent(ConfigureEvent,GetMagickModule(), "Loading quantization tables \"%s\" ...",filename); table=(QuantizationTable *) NULL; xml=FileToString(filename,~0UL,exception); if (xml == (char *) NULL) return(table); quantization_tables=NewXMLTree(xml,exception); if (quantization_tables == (XMLTreeInfo *) NULL) { xml=DestroyString(xml); return(table); } for (table_iterator=GetXMLTreeChild(quantization_tables,"table"); table_iterator != (XMLTreeInfo *) NULL; table_iterator=GetNextXMLTreeTag(table_iterator)) { attribute=GetXMLTreeAttribute(table_iterator,"slot"); if ((attribute != (char *) NULL) && (LocaleCompare(slot,attribute) == 0)) break; attribute=GetXMLTreeAttribute(table_iterator,"alias"); if ((attribute != (char *) NULL) && (LocaleCompare(slot,attribute) == 0)) break; } if (table_iterator == (XMLTreeInfo *) NULL) { xml=DestroyString(xml); return(table); } description=GetXMLTreeChild(table_iterator,"description"); if (description == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement","<description>, slot \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); xml=DestroyString(xml); return(table); } levels=GetXMLTreeChild(table_iterator,"levels"); if (levels == (XMLTreeInfo *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingElement","<levels>, slot \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); xml=DestroyString(xml); return(table); } table=(QuantizationTable *) AcquireMagickMemory(sizeof(*table)); if (table == (QuantizationTable *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAcquireQuantizationTable"); table->slot=(char *) NULL; table->description=(char *) NULL; table->levels=(unsigned int *) NULL; attribute=GetXMLTreeAttribute(table_iterator,"slot"); if (attribute != (char *) NULL) table->slot=ConstantString(attribute); content=GetXMLTreeContent(description); if (content != (char *) NULL) table->description=ConstantString(content); attribute=GetXMLTreeAttribute(levels,"width"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute","<levels width>, slot \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } table->width=StringToUnsignedLong(attribute); if (table->width == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute","<levels width>, table \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } attribute=GetXMLTreeAttribute(levels,"height"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute","<levels height>, table \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } table->height=StringToUnsignedLong(attribute); if (table->height == 0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute","<levels height>, table \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } attribute=GetXMLTreeAttribute(levels,"divisor"); if (attribute == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingAttribute","<levels divisor>, table \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } table->divisor=InterpretLocaleValue(attribute,(char **) NULL); if (table->divisor == 0.0) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidAttribute","<levels divisor>, table \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } content=GetXMLTreeContent(levels); if (content == (char *) NULL) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlMissingContent","<levels>, table \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } length=(size_t) table->width*table->height; if (length < 64) length=64; table->levels=(unsigned int *) AcquireQuantumMemory(length, sizeof(*table->levels)); if (table->levels == (unsigned int *) NULL) ThrowFatalException(ResourceLimitFatalError, "UnableToAcquireQuantizationTable"); for (i=0; i < (ssize_t) (table->width*table->height); i++) { table->levels[i]=(unsigned int) (InterpretLocaleValue(content,&p)/ table->divisor+0.5); while (isspace((int) ((unsigned char) *p)) != 0) p++; if (*p == ',') p++; content=p; } value=InterpretLocaleValue(content,&p); (void) value; if (p != content) { (void) ThrowMagickException(exception,GetMagickModule(),OptionError, "XmlInvalidContent","<level> too many values, table \"%s\"",slot); quantization_tables=DestroyXMLTree(quantization_tables); table=DestroyQuantizationTable(table); xml=DestroyString(xml); return(table); } for (j=i; j < 64; j++) table->levels[j]=table->levels[j-1]; quantization_tables=DestroyXMLTree(quantization_tables); xml=DestroyString(xml); return(table); } static void InitializeDestination(j_compress_ptr cinfo) { DestinationManager *destination; destination=(DestinationManager *) cinfo->dest; destination->buffer=(JOCTET *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo,JPOOL_IMAGE,MaxBufferExtent*sizeof(JOCTET)); destination->manager.next_output_byte=destination->buffer; destination->manager.free_in_buffer=MaxBufferExtent; } static void TerminateDestination(j_compress_ptr cinfo) { DestinationManager *destination; destination=(DestinationManager *) cinfo->dest; if ((MaxBufferExtent-(int) destination->manager.free_in_buffer) > 0) { ssize_t count; count=WriteBlob(destination->image,MaxBufferExtent- destination->manager.free_in_buffer,destination->buffer); if (count != (ssize_t) (MaxBufferExtent-destination->manager.free_in_buffer)) ERREXIT(cinfo,JERR_FILE_WRITE); } } static void WriteProfile(j_compress_ptr jpeg_info,Image *image) { const char *name; const StringInfo *profile; MagickBooleanType iptc; register ssize_t i; size_t length, tag_length; StringInfo *custom_profile; /* Save image profile as a APP marker. */ iptc=MagickFalse; custom_profile=AcquireStringInfo(65535L); ResetImageProfileIterator(image); for (name=GetNextImageProfile(image); name != (const char *) NULL; ) { register unsigned char *p; profile=GetImageProfile(image,name); p=GetStringInfoDatum(custom_profile); if (LocaleCompare(name,"EXIF") == 0) { length=GetStringInfoLength(profile); if (length > 65533L) { (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderWarning,"ExifProfileSizeExceedsLimit","`%s'", image->filename); length=65533L; } jpeg_write_marker(jpeg_info,XML_MARKER,GetStringInfoDatum(profile), (unsigned int) length); } if (LocaleCompare(name,"ICC") == 0) { register unsigned char *p; tag_length=strlen(ICC_PROFILE); p=GetStringInfoDatum(custom_profile); (void) CopyMagickMemory(p,ICC_PROFILE,tag_length); p[tag_length]='\0'; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65519L) { length=MagickMin(GetStringInfoLength(profile)-i,65519L); p[12]=(unsigned char) ((i/65519L)+1); p[13]=(unsigned char) (GetStringInfoLength(profile)/65519L+1); (void) CopyMagickMemory(p+tag_length+3,GetStringInfoDatum(profile)+i, length); jpeg_write_marker(jpeg_info,ICC_MARKER,GetStringInfoDatum( custom_profile),(unsigned int) (length+tag_length+3)); } } if (((LocaleCompare(name,"IPTC") == 0) || (LocaleCompare(name,"8BIM") == 0)) && (iptc == MagickFalse)) { size_t roundup; iptc=MagickTrue; for (i=0; i < (ssize_t) GetStringInfoLength(profile); i+=65500L) { length=MagickMin(GetStringInfoLength(profile)-i,65500L); roundup=(size_t) (length & 0x01); if (LocaleNCompare((char *) GetStringInfoDatum(profile),"8BIM",4) == 0) { (void) memcpy(p,"Photoshop 3.0 ",14); tag_length=14; } else { (void) CopyMagickMemory(p,"Photoshop 3.0 8BIM\04\04\0\0\0\0",24); tag_length=26; p[24]=(unsigned char) (length >> 8); p[25]=(unsigned char) (length & 0xff); } p[13]=0x00; (void) memcpy(p+tag_length,GetStringInfoDatum(profile)+i,length); if (roundup != 0) p[length+tag_length]='\0'; jpeg_write_marker(jpeg_info,IPTC_MARKER,GetStringInfoDatum( custom_profile),(unsigned int) (length+tag_length+roundup)); } } if (LocaleCompare(name,"XMP") == 0) { StringInfo *xmp_profile; /* Add namespace to XMP profile. */ xmp_profile=StringToStringInfo("http://ns.adobe.com/xap/1.0/ "); if (xmp_profile != (StringInfo *) NULL) { if (profile != (StringInfo *) NULL) ConcatenateStringInfo(xmp_profile,profile); GetStringInfoDatum(xmp_profile)[28]='\0'; for (i=0; i < (ssize_t) GetStringInfoLength(xmp_profile); i+=65533L) { length=MagickMin(GetStringInfoLength(xmp_profile)-i,65533L); jpeg_write_marker(jpeg_info,XML_MARKER, GetStringInfoDatum(xmp_profile)+i,(unsigned int) length); } xmp_profile=DestroyStringInfo(xmp_profile); } } (void) LogMagickEvent(CoderEvent,GetMagickModule(), "%s profile: %.20g bytes",name,(double) GetStringInfoLength(profile)); name=GetNextImageProfile(image); } custom_profile=DestroyStringInfo(custom_profile); } static void JPEGDestinationManager(j_compress_ptr cinfo,Image * image) { DestinationManager *destination; cinfo->dest=(struct jpeg_destination_mgr *) (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo,JPOOL_IMAGE,sizeof(DestinationManager)); destination=(DestinationManager *) cinfo->dest; destination->manager.init_destination=InitializeDestination; destination->manager.empty_output_buffer=EmptyOutputBuffer; destination->manager.term_destination=TerminateDestination; destination->image=image; } static char **SamplingFactorToList(const char *text) { char **textlist; register char *q; register const char *p; register ssize_t i; if (text == (char *) NULL) return((char **) NULL); /* Convert string to an ASCII list. */ textlist=(char **) AcquireQuantumMemory((size_t) MAX_COMPONENTS, sizeof(*textlist)); if (textlist == (char **) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToConvertText"); p=text; for (i=0; i < (ssize_t) MAX_COMPONENTS; i++) { for (q=(char *) p; *q != '\0'; q++) if (*q == ',') break; textlist[i]=(char *) AcquireQuantumMemory((size_t) (q-p)+MaxTextExtent, sizeof(*textlist[i])); if (textlist[i] == (char *) NULL) ThrowFatalException(ResourceLimitFatalError,"UnableToConvertText"); (void) CopyMagickString(textlist[i],p,(size_t) (q-p+1)); if (*q == '\r') q++; if (*q == '\0') break; p=q+1; } for (i++; i < (ssize_t) MAX_COMPONENTS; i++) textlist[i]=ConstantString("1x1"); return(textlist); } static MagickBooleanType WriteJPEGImage(const ImageInfo *image_info, Image *image) { const char *option, *sampling_factor, *value; ErrorManager error_manager; ExceptionInfo *exception; Image *volatile volatile_image; int colorspace, quality; JSAMPLE *volatile jpeg_pixels; JSAMPROW scanline[1]; MagickBooleanType status; MemoryInfo *memory_info; register JSAMPLE *q; register ssize_t i; ssize_t y; struct jpeg_compress_struct jpeg_info; struct jpeg_error_mgr jpeg_error; unsigned short scale; /* Open image file. */ assert(image_info != (const ImageInfo *) NULL); assert(image_info->signature == MagickSignature); assert(image != (Image *) NULL); assert(image->signature == MagickSignature); if (image->debug != MagickFalse) (void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",image->filename); exception=(&image->exception); if ((LocaleCompare(image_info->magick,"JPS") == 0) && (image->next != (Image *) NULL)) image=AppendImages(image,MagickFalse,exception); status=OpenBlob(image_info,image,WriteBinaryBlobMode,exception); if (status == MagickFalse) return(status); /* Initialize JPEG parameters. */ (void) ResetMagickMemory(&error_manager,0,sizeof(error_manager)); (void) ResetMagickMemory(&jpeg_info,0,sizeof(jpeg_info)); (void) ResetMagickMemory(&jpeg_error,0,sizeof(jpeg_error)); volatile_image=image; jpeg_info.client_data=(void *) volatile_image; jpeg_info.err=jpeg_std_error(&jpeg_error); jpeg_info.err->emit_message=(void (*)(j_common_ptr,int)) JPEGWarningHandler; jpeg_info.err->error_exit=(void (*)(j_common_ptr)) JPEGErrorHandler; error_manager.image=volatile_image; memory_info=(MemoryInfo *) NULL; if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_compress(&jpeg_info); (void) CloseBlob(volatile_image); return(MagickFalse); } jpeg_info.client_data=(void *) &error_manager; jpeg_create_compress(&jpeg_info); JPEGDestinationManager(&jpeg_info,image); if ((image->columns != (unsigned int) image->columns) || (image->rows != (unsigned int) image->rows)) ThrowWriterException(ImageError,"WidthOrHeightExceedsLimit"); jpeg_info.image_width=(unsigned int) image->columns; jpeg_info.image_height=(unsigned int) image->rows; jpeg_info.input_components=3; jpeg_info.data_precision=8; jpeg_info.in_color_space=JCS_RGB; switch (image->colorspace) { case CMYKColorspace: { jpeg_info.input_components=4; jpeg_info.in_color_space=JCS_CMYK; break; } case YCbCrColorspace: case Rec601YCbCrColorspace: case Rec709YCbCrColorspace: { jpeg_info.in_color_space=JCS_YCbCr; break; } case GRAYColorspace: case Rec601LumaColorspace: case Rec709LumaColorspace: { if (image_info->type == TrueColorType) break; jpeg_info.input_components=1; jpeg_info.in_color_space=JCS_GRAYSCALE; break; } default: { (void) TransformImageColorspace(image,sRGBColorspace); if (image_info->type == TrueColorType) break; if (SetImageGray(image,&image->exception) != MagickFalse) { jpeg_info.input_components=1; jpeg_info.in_color_space=JCS_GRAYSCALE; } break; } } jpeg_set_defaults(&jpeg_info); if (jpeg_info.in_color_space == JCS_CMYK) jpeg_set_colorspace(&jpeg_info,JCS_YCCK); if ((jpeg_info.data_precision != 12) && (image->depth <= 8)) jpeg_info.data_precision=8; else jpeg_info.data_precision=BITS_IN_JSAMPLE; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image resolution: %.20g,%.20g",image->x_resolution,image->y_resolution); if ((image->x_resolution != 0.0) && (image->y_resolution != 0.0)) { /* Set image resolution. */ jpeg_info.write_JFIF_header=TRUE; jpeg_info.X_density=(UINT16) image->x_resolution; jpeg_info.Y_density=(UINT16) image->y_resolution; /* Set image resolution units. */ if (image->units == PixelsPerInchResolution) jpeg_info.density_unit=(UINT8) 1; if (image->units == PixelsPerCentimeterResolution) jpeg_info.density_unit=(UINT8) 2; } jpeg_info.dct_method=JDCT_FLOAT; option=GetImageOption(image_info,"jpeg:dct-method"); if (option != (const char *) NULL) switch (*option) { case 'D': case 'd': { if (LocaleCompare(option,"default") == 0) jpeg_info.dct_method=JDCT_DEFAULT; break; } case 'F': case 'f': { if (LocaleCompare(option,"fastest") == 0) jpeg_info.dct_method=JDCT_FASTEST; if (LocaleCompare(option,"float") == 0) jpeg_info.dct_method=JDCT_FLOAT; break; } case 'I': case 'i': { if (LocaleCompare(option,"ifast") == 0) jpeg_info.dct_method=JDCT_IFAST; if (LocaleCompare(option,"islow") == 0) jpeg_info.dct_method=JDCT_ISLOW; break; } } option=GetImageOption(image_info,"jpeg:optimize-coding"); if (option != (const char *) NULL) jpeg_info.optimize_coding=IsStringTrue(option) != MagickFalse ? TRUE : FALSE; else { MagickSizeType length; length=(MagickSizeType) jpeg_info.input_components*image->columns* image->rows*sizeof(JSAMPLE); if (length == (MagickSizeType) ((size_t) length)) { /* Perform optimization only if available memory resources permit it. */ status=AcquireMagickResource(MemoryResource,length); RelinquishMagickResource(MemoryResource,length); jpeg_info.optimize_coding=status == MagickFalse ? FALSE : TRUE; } } #if (JPEG_LIB_VERSION >= 61) && defined(C_PROGRESSIVE_SUPPORTED) if ((LocaleCompare(image_info->magick,"PJPEG") == 0) || (image_info->interlace != NoInterlace)) { if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: progressive"); jpeg_simple_progression(&jpeg_info); } else if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: non-progressive"); #else if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Interlace: nonprogressive"); #endif quality=92; if ((image_info->compression != LosslessJPEGCompression) && (image->quality <= 100)) { if (image->quality != UndefinedCompressionQuality) quality=(int) image->quality; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: %.20g", (double) image->quality); } else { #if !defined(C_LOSSLESS_SUPPORTED) quality=100; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Quality: 100"); #else if (image->quality < 100) (void) ThrowMagickException(&image->exception,GetMagickModule(), CoderWarning,"LosslessToLossyJPEGConversion","`%s'",image->filename); else { int point_transform, predictor; predictor=image->quality/100; /* range 1-7 */ point_transform=image->quality % 20; /* range 0-15 */ jpeg_simple_lossless(&jpeg_info,predictor,point_transform); if (image->debug != MagickFalse) { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Compression: lossless"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Predictor: %d",predictor); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Point Transform: %d",point_transform); } } #endif } option=GetImageOption(image_info,"jpeg:extent"); if (option != (const char *) NULL) { Image *jpeg_image; ImageInfo *jpeg_info; jpeg_info=CloneImageInfo(image_info); jpeg_info->blob=NULL; jpeg_image=CloneImage(image,0,0,MagickTrue,&image->exception); if (jpeg_image != (Image *) NULL) { MagickSizeType extent; size_t maximum, minimum; /* Search for compression quality that does not exceed image extent. */ jpeg_image->quality=0; extent=(MagickSizeType) SiPrefixToDoubleInterval(option,100.0); (void) DeleteImageOption(jpeg_info,"jpeg:extent"); (void) DeleteImageArtifact(jpeg_image,"jpeg:extent"); maximum=image_info->quality; if (maximum < 2) maximum=101; for (minimum=2; minimum < maximum; ) { (void) AcquireUniqueFilename(jpeg_image->filename); jpeg_image->quality=minimum+(maximum-minimum+1)/2; (void) WriteJPEGImage(jpeg_info,jpeg_image); if (GetBlobSize(jpeg_image) <= extent) minimum=jpeg_image->quality+1; else maximum=jpeg_image->quality-1; (void) RelinquishUniqueFileResource(jpeg_image->filename); } quality=(int) minimum-1; jpeg_image=DestroyImage(jpeg_image); } jpeg_info=DestroyImageInfo(jpeg_info); } jpeg_set_quality(&jpeg_info,quality,TRUE); #if (JPEG_LIB_VERSION >= 70) option=GetImageOption(image_info,"quality"); if (option != (const char *) NULL) { GeometryInfo geometry_info; int flags; /* Set quality scaling for luminance and chrominance separately. */ flags=ParseGeometry(option,&geometry_info); if (((flags & RhoValue) != 0) && ((flags & SigmaValue) != 0)) { jpeg_info.q_scale_factor[0]=jpeg_quality_scaling((int) (geometry_info.rho+0.5)); jpeg_info.q_scale_factor[1]=jpeg_quality_scaling((int) (geometry_info.sigma+0.5)); jpeg_default_qtables(&jpeg_info,TRUE); } } #endif colorspace=jpeg_info.in_color_space; value=GetImageOption(image_info,"jpeg:colorspace"); if (value == (char *) NULL) value=GetImageProperty(image,"jpeg:colorspace"); if (value != (char *) NULL) colorspace=StringToInteger(value); sampling_factor=(const char *) NULL; if (colorspace == jpeg_info.in_color_space) { value=GetImageOption(image_info,"jpeg:sampling-factor"); if (value == (char *) NULL) value=GetImageProperty(image,"jpeg:sampling-factor"); if (value != (char *) NULL) { sampling_factor=value; if (image->debug != MagickFalse) (void) LogMagickEvent(CoderEvent,GetMagickModule(), " Input sampling-factors=%s",sampling_factor); } } if (image_info->sampling_factor != (char *) NULL) sampling_factor=image_info->sampling_factor; if (sampling_factor == (const char *) NULL) { if (quality >= 90) for (i=0; i < MAX_COMPONENTS; i++) { jpeg_info.comp_info[i].h_samp_factor=1; jpeg_info.comp_info[i].v_samp_factor=1; } } else { char **factors; GeometryInfo geometry_info; MagickStatusType flags; /* Set sampling factor. */ i=0; factors=SamplingFactorToList(sampling_factor); if (factors != (char **) NULL) { for (i=0; i < MAX_COMPONENTS; i++) { if (factors[i] == (char *) NULL) break; flags=ParseGeometry(factors[i],&geometry_info); if ((flags & SigmaValue) == 0) geometry_info.sigma=geometry_info.rho; jpeg_info.comp_info[i].h_samp_factor=(int) geometry_info.rho; jpeg_info.comp_info[i].v_samp_factor=(int) geometry_info.sigma; factors[i]=(char *) RelinquishMagickMemory(factors[i]); } factors=(char **) RelinquishMagickMemory(factors); } for ( ; i < MAX_COMPONENTS; i++) { jpeg_info.comp_info[i].h_samp_factor=1; jpeg_info.comp_info[i].v_samp_factor=1; } } option=GetImageOption(image_info,"jpeg:q-table"); if (option != (const char *) NULL) { QuantizationTable *table; /* Custom quantization tables. */ table=GetQuantizationTable(option,"0",&image->exception); if (table != (QuantizationTable *) NULL) { for (i=0; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=0; jpeg_add_quant_table(&jpeg_info,0,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } table=GetQuantizationTable(option,"1",&image->exception); if (table != (QuantizationTable *) NULL) { for (i=1; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=1; jpeg_add_quant_table(&jpeg_info,1,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } table=GetQuantizationTable(option,"2",&image->exception); if (table != (QuantizationTable *) NULL) { for (i=2; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=2; jpeg_add_quant_table(&jpeg_info,2,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } table=GetQuantizationTable(option,"3",&image->exception); if (table != (QuantizationTable *) NULL) { for (i=3; i < MAX_COMPONENTS; i++) jpeg_info.comp_info[i].quant_tbl_no=3; jpeg_add_quant_table(&jpeg_info,3,table->levels, jpeg_quality_scaling(quality),0); table=DestroyQuantizationTable(table); } } jpeg_start_compress(&jpeg_info,TRUE); if (image->debug != MagickFalse) { if (image->storage_class == PseudoClass) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Storage class: PseudoClass"); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Storage class: DirectClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Depth: %.20g", (double) image->depth); if (image->colors != 0) (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Number of colors: %.20g",(double) image->colors); else (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Number of colors: unspecified"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "JPEG data precision: %d",(int) jpeg_info.data_precision); switch (image->colorspace) { case CMYKColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Storage class: DirectClass"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: CMYK"); break; } case YCbCrColorspace: case Rec601YCbCrColorspace: case Rec709YCbCrColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: YCbCr"); break; } default: break; } switch (image->colorspace) { case CMYKColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: CMYK"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor, jpeg_info.comp_info[3].h_samp_factor, jpeg_info.comp_info[3].v_samp_factor); break; } case GRAYColorspace: case Rec601LumaColorspace: case Rec709LumaColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: GRAY"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d",jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor); break; } case sRGBColorspace: case RGBColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Image colorspace is RGB"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor); break; } case YCbCrColorspace: case Rec601YCbCrColorspace: case Rec709YCbCrColorspace: { (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Colorspace: YCbCr"); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor); break; } default: { (void) LogMagickEvent(CoderEvent,GetMagickModule(),"Colorspace: %d", image->colorspace); (void) LogMagickEvent(CoderEvent,GetMagickModule(), "Sampling factors: %dx%d,%dx%d,%dx%d,%dx%d", jpeg_info.comp_info[0].h_samp_factor, jpeg_info.comp_info[0].v_samp_factor, jpeg_info.comp_info[1].h_samp_factor, jpeg_info.comp_info[1].v_samp_factor, jpeg_info.comp_info[2].h_samp_factor, jpeg_info.comp_info[2].v_samp_factor, jpeg_info.comp_info[3].h_samp_factor, jpeg_info.comp_info[3].v_samp_factor); break; } } } /* Write JPEG profiles. */ value=GetImageProperty(image,"comment"); if (value != (char *) NULL) for (i=0; i < (ssize_t) strlen(value); i+=65533L) jpeg_write_marker(&jpeg_info,JPEG_COM,(unsigned char *) value+i, (unsigned int) MagickMin((size_t) strlen(value+i),65533L)); if (image->profiles != (void *) NULL) WriteProfile(&jpeg_info,image); /* Convert MIFF to JPEG raster pixels. */ memory_info=AcquireVirtualMemory((size_t) image->columns, jpeg_info.input_components*sizeof(*jpeg_pixels)); if (memory_info == (MemoryInfo *) NULL) ThrowWriterException(ResourceLimitError,"MemoryAllocationFailed"); jpeg_pixels=(JSAMPLE *) GetVirtualMemoryBlob(memory_info); if (setjmp(error_manager.error_recovery) != 0) { jpeg_destroy_compress(&jpeg_info); if (memory_info != (MemoryInfo *) NULL) memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(MagickFalse); } scanline[0]=(JSAMPROW) jpeg_pixels; scale=65535/(unsigned short) GetQuantumRange((size_t) jpeg_info.data_precision); if (scale == 0) scale=1; if (jpeg_info.data_precision <= 8) { if ((jpeg_info.in_color_space == JCS_RGB) || (jpeg_info.in_color_space == JCS_YCbCr)) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) ScaleQuantumToChar(GetPixelRed(p)); *q++=(JSAMPLE) ScaleQuantumToChar(GetPixelGreen(p)); *q++=(JSAMPLE) ScaleQuantumToChar(GetPixelBlue(p)); p++; } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else if (jpeg_info.in_color_space == JCS_GRAYSCALE) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) ScaleQuantumToChar(ClampToQuantum( GetPixelLuma(image,p))); p++; } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=jpeg_pixels; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { /* Convert DirectClass packets to contiguous CMYK scanlines. */ *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelCyan(p)))); *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelMagenta(p)))); *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelYellow(p)))); *q++=(JSAMPLE) (ScaleQuantumToChar((Quantum) (QuantumRange- GetPixelBlack(indexes+x)))); p++; } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } } else if (jpeg_info.in_color_space == JCS_GRAYSCALE) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) (ScaleQuantumToShort(ClampToQuantum( GetPixelLuma(image,p)))/scale); p++; } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else if ((jpeg_info.in_color_space == JCS_RGB) || (jpeg_info.in_color_space == JCS_YCbCr)) for (y=0; y < (ssize_t) image->rows; y++) { register const PixelPacket *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=jpeg_pixels; for (x=0; x < (ssize_t) image->columns; x++) { *q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelRed(p))/scale); *q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelGreen(p))/scale); *q++=(JSAMPLE) (ScaleQuantumToShort(GetPixelBlue(p))/scale); p++; } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } else for (y=0; y < (ssize_t) image->rows; y++) { register const IndexPacket *indexes; register const PixelPacket *p; register ssize_t x; p=GetVirtualPixels(image,0,y,image->columns,1,&image->exception); if (p == (const PixelPacket *) NULL) break; q=jpeg_pixels; indexes=GetVirtualIndexQueue(image); for (x=0; x < (ssize_t) image->columns; x++) { /* Convert DirectClass packets to contiguous CMYK scanlines. */ *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelRed(p))/ scale); *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelGreen(p))/ scale); *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange-GetPixelBlue(p))/ scale); *q++=(JSAMPLE) (ScaleQuantumToShort(QuantumRange- GetPixelIndex(indexes+x))/scale); p++; } (void) jpeg_write_scanlines(&jpeg_info,scanline,1); status=SetImageProgress(image,SaveImageTag,(MagickOffsetType) y, image->rows); if (status == MagickFalse) break; } if (y == (ssize_t) image->rows) jpeg_finish_compress(&jpeg_info); /* Relinquish resources. */ jpeg_destroy_compress(&jpeg_info); memory_info=RelinquishVirtualMemory(memory_info); (void) CloseBlob(image); return(MagickTrue); } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2575_0
crossvul-cpp_data_good_3825_0
/* xfrm_user.c: User interface to configure xfrm engine. * * Copyright (C) 2002 David S. Miller (davem@redhat.com) * * Changes: * Mitsuru KANDA @USAGI * Kazunori MIYAZAWA @USAGI * Kunihiro Ishiguro <kunihiro@ipinfusion.com> * IPv6 support * */ #include <linux/crypto.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/types.h> #include <linux/slab.h> #include <linux/socket.h> #include <linux/string.h> #include <linux/net.h> #include <linux/skbuff.h> #include <linux/pfkeyv2.h> #include <linux/ipsec.h> #include <linux/init.h> #include <linux/security.h> #include <net/sock.h> #include <net/xfrm.h> #include <net/netlink.h> #include <net/ah.h> #include <asm/uaccess.h> #if IS_ENABLED(CONFIG_IPV6) #include <linux/in6.h> #endif static inline int aead_len(struct xfrm_algo_aead *alg) { return sizeof(*alg) + ((alg->alg_key_len + 7) / 8); } static int verify_one_alg(struct nlattr **attrs, enum xfrm_attr_type_t type) { struct nlattr *rt = attrs[type]; struct xfrm_algo *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < xfrm_alg_len(algp)) return -EINVAL; switch (type) { case XFRMA_ALG_AUTH: case XFRMA_ALG_CRYPT: case XFRMA_ALG_COMP: break; default: return -EINVAL; } algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static int verify_auth_trunc(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_ALG_AUTH_TRUNC]; struct xfrm_algo_auth *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < xfrm_alg_auth_len(algp)) return -EINVAL; algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static int verify_aead(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_ALG_AEAD]; struct xfrm_algo_aead *algp; if (!rt) return 0; algp = nla_data(rt); if (nla_len(rt) < aead_len(algp)) return -EINVAL; algp->alg_name[CRYPTO_MAX_ALG_NAME - 1] = '\0'; return 0; } static void verify_one_addr(struct nlattr **attrs, enum xfrm_attr_type_t type, xfrm_address_t **addrp) { struct nlattr *rt = attrs[type]; if (rt && addrp) *addrp = nla_data(rt); } static inline int verify_sec_ctx_len(struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = nla_data(rt); if (uctx->len != (sizeof(struct xfrm_user_sec_ctx) + uctx->ctx_len)) return -EINVAL; return 0; } static inline int verify_replay(struct xfrm_usersa_info *p, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_REPLAY_ESN_VAL]; if ((p->flags & XFRM_STATE_ESN) && !rt) return -EINVAL; if (!rt) return 0; if (p->id.proto != IPPROTO_ESP) return -EINVAL; if (p->replay_window != 0) return -EINVAL; return 0; } static int verify_newsa_info(struct xfrm_usersa_info *p, struct nlattr **attrs) { int err; err = -EINVAL; switch (p->family) { case AF_INET: break; case AF_INET6: #if IS_ENABLED(CONFIG_IPV6) break; #else err = -EAFNOSUPPORT; goto out; #endif default: goto out; } err = -EINVAL; switch (p->id.proto) { case IPPROTO_AH: if ((!attrs[XFRMA_ALG_AUTH] && !attrs[XFRMA_ALG_AUTH_TRUNC]) || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_ALG_COMP] || attrs[XFRMA_TFCPAD]) goto out; break; case IPPROTO_ESP: if (attrs[XFRMA_ALG_COMP]) goto out; if (!attrs[XFRMA_ALG_AUTH] && !attrs[XFRMA_ALG_AUTH_TRUNC] && !attrs[XFRMA_ALG_CRYPT] && !attrs[XFRMA_ALG_AEAD]) goto out; if ((attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_CRYPT]) && attrs[XFRMA_ALG_AEAD]) goto out; if (attrs[XFRMA_TFCPAD] && p->mode != XFRM_MODE_TUNNEL) goto out; break; case IPPROTO_COMP: if (!attrs[XFRMA_ALG_COMP] || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_TFCPAD]) goto out; break; #if IS_ENABLED(CONFIG_IPV6) case IPPROTO_DSTOPTS: case IPPROTO_ROUTING: if (attrs[XFRMA_ALG_COMP] || attrs[XFRMA_ALG_AUTH] || attrs[XFRMA_ALG_AUTH_TRUNC] || attrs[XFRMA_ALG_AEAD] || attrs[XFRMA_ALG_CRYPT] || attrs[XFRMA_ENCAP] || attrs[XFRMA_SEC_CTX] || attrs[XFRMA_TFCPAD] || !attrs[XFRMA_COADDR]) goto out; break; #endif default: goto out; } if ((err = verify_aead(attrs))) goto out; if ((err = verify_auth_trunc(attrs))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_AUTH))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_CRYPT))) goto out; if ((err = verify_one_alg(attrs, XFRMA_ALG_COMP))) goto out; if ((err = verify_sec_ctx_len(attrs))) goto out; if ((err = verify_replay(p, attrs))) goto out; err = -EINVAL; switch (p->mode) { case XFRM_MODE_TRANSPORT: case XFRM_MODE_TUNNEL: case XFRM_MODE_ROUTEOPTIMIZATION: case XFRM_MODE_BEET: break; default: goto out; } err = 0; out: return err; } static int attach_one_algo(struct xfrm_algo **algpp, u8 *props, struct xfrm_algo_desc *(*get_byname)(const char *, int), struct nlattr *rta) { struct xfrm_algo *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, xfrm_alg_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); *algpp = p; return 0; } static int attach_auth(struct xfrm_algo_auth **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo *ualg; struct xfrm_algo_auth *p; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aalg_get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmalloc(sizeof(*p) + (ualg->alg_key_len + 7) / 8, GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); p->alg_key_len = ualg->alg_key_len; p->alg_trunc_len = algo->uinfo.auth.icv_truncbits; memcpy(p->alg_key, ualg->alg_key, (ualg->alg_key_len + 7) / 8); *algpp = p; return 0; } static int attach_auth_trunc(struct xfrm_algo_auth **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo_auth *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aalg_get_byname(ualg->alg_name, 1); if (!algo) return -ENOSYS; if ((ualg->alg_trunc_len / 8) > MAX_AH_AUTH_LEN || ualg->alg_trunc_len > algo->uinfo.auth.icv_fullbits) return -EINVAL; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, xfrm_alg_auth_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); if (!p->alg_trunc_len) p->alg_trunc_len = algo->uinfo.auth.icv_truncbits; *algpp = p; return 0; } static int attach_aead(struct xfrm_algo_aead **algpp, u8 *props, struct nlattr *rta) { struct xfrm_algo_aead *p, *ualg; struct xfrm_algo_desc *algo; if (!rta) return 0; ualg = nla_data(rta); algo = xfrm_aead_get_byname(ualg->alg_name, ualg->alg_icv_len, 1); if (!algo) return -ENOSYS; *props = algo->desc.sadb_alg_id; p = kmemdup(ualg, aead_len(ualg), GFP_KERNEL); if (!p) return -ENOMEM; strcpy(p->alg_name, algo->name); *algpp = p; return 0; } static inline int xfrm_replay_verify_len(struct xfrm_replay_state_esn *replay_esn, struct nlattr *rp) { struct xfrm_replay_state_esn *up; if (!replay_esn || !rp) return 0; up = nla_data(rp); if (xfrm_replay_state_esn_len(replay_esn) != xfrm_replay_state_esn_len(up)) return -EINVAL; return 0; } static int xfrm_alloc_replay_state_esn(struct xfrm_replay_state_esn **replay_esn, struct xfrm_replay_state_esn **preplay_esn, struct nlattr *rta) { struct xfrm_replay_state_esn *p, *pp, *up; if (!rta) return 0; up = nla_data(rta); p = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!p) return -ENOMEM; pp = kmemdup(up, xfrm_replay_state_esn_len(up), GFP_KERNEL); if (!pp) { kfree(p); return -ENOMEM; } *replay_esn = p; *preplay_esn = pp; return 0; } static inline int xfrm_user_sec_ctx_size(struct xfrm_sec_ctx *xfrm_ctx) { int len = 0; if (xfrm_ctx) { len += sizeof(struct xfrm_user_sec_ctx); len += xfrm_ctx->ctx_len; } return len; } static void copy_from_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memcpy(&x->id, &p->id, sizeof(x->id)); memcpy(&x->sel, &p->sel, sizeof(x->sel)); memcpy(&x->lft, &p->lft, sizeof(x->lft)); x->props.mode = p->mode; x->props.replay_window = p->replay_window; x->props.reqid = p->reqid; x->props.family = p->family; memcpy(&x->props.saddr, &p->saddr, sizeof(x->props.saddr)); x->props.flags = p->flags; if (!x->sel.family && !(p->flags & XFRM_STATE_AF_UNSPEC)) x->sel.family = p->family; } /* * someday when pfkey also has support, we could have the code * somehow made shareable and move it to xfrm_state.c - JHS * */ static void xfrm_update_ae_params(struct xfrm_state *x, struct nlattr **attrs) { struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL]; struct nlattr *lt = attrs[XFRMA_LTIME_VAL]; struct nlattr *et = attrs[XFRMA_ETIMER_THRESH]; struct nlattr *rt = attrs[XFRMA_REPLAY_THRESH]; if (re) { struct xfrm_replay_state_esn *replay_esn; replay_esn = nla_data(re); memcpy(x->replay_esn, replay_esn, xfrm_replay_state_esn_len(replay_esn)); memcpy(x->preplay_esn, replay_esn, xfrm_replay_state_esn_len(replay_esn)); } if (rp) { struct xfrm_replay_state *replay; replay = nla_data(rp); memcpy(&x->replay, replay, sizeof(*replay)); memcpy(&x->preplay, replay, sizeof(*replay)); } if (lt) { struct xfrm_lifetime_cur *ltime; ltime = nla_data(lt); x->curlft.bytes = ltime->bytes; x->curlft.packets = ltime->packets; x->curlft.add_time = ltime->add_time; x->curlft.use_time = ltime->use_time; } if (et) x->replay_maxage = nla_get_u32(et); if (rt) x->replay_maxdiff = nla_get_u32(rt); } static struct xfrm_state *xfrm_state_construct(struct net *net, struct xfrm_usersa_info *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = xfrm_state_alloc(net); int err = -ENOMEM; if (!x) goto error_no_put; copy_from_user_state(x, p); if ((err = attach_aead(&x->aead, &x->props.ealgo, attrs[XFRMA_ALG_AEAD]))) goto error; if ((err = attach_auth_trunc(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH_TRUNC]))) goto error; if (!x->props.aalgo) { if ((err = attach_auth(&x->aalg, &x->props.aalgo, attrs[XFRMA_ALG_AUTH]))) goto error; } if ((err = attach_one_algo(&x->ealg, &x->props.ealgo, xfrm_ealg_get_byname, attrs[XFRMA_ALG_CRYPT]))) goto error; if ((err = attach_one_algo(&x->calg, &x->props.calgo, xfrm_calg_get_byname, attrs[XFRMA_ALG_COMP]))) goto error; if (attrs[XFRMA_ENCAP]) { x->encap = kmemdup(nla_data(attrs[XFRMA_ENCAP]), sizeof(*x->encap), GFP_KERNEL); if (x->encap == NULL) goto error; } if (attrs[XFRMA_TFCPAD]) x->tfcpad = nla_get_u32(attrs[XFRMA_TFCPAD]); if (attrs[XFRMA_COADDR]) { x->coaddr = kmemdup(nla_data(attrs[XFRMA_COADDR]), sizeof(*x->coaddr), GFP_KERNEL); if (x->coaddr == NULL) goto error; } xfrm_mark_get(attrs, &x->mark); err = __xfrm_init_state(x, false); if (err) goto error; if (attrs[XFRMA_SEC_CTX] && security_xfrm_state_alloc(x, nla_data(attrs[XFRMA_SEC_CTX]))) goto error; if ((err = xfrm_alloc_replay_state_esn(&x->replay_esn, &x->preplay_esn, attrs[XFRMA_REPLAY_ESN_VAL]))) goto error; x->km.seq = p->seq; x->replay_maxdiff = net->xfrm.sysctl_aevent_rseqth; /* sysctl_xfrm_aevent_etime is in 100ms units */ x->replay_maxage = (net->xfrm.sysctl_aevent_etime*HZ)/XFRM_AE_ETH_M; if ((err = xfrm_init_replay(x))) goto error; /* override default values from above */ xfrm_update_ae_params(x, attrs); return x; error: x->km.state = XFRM_STATE_DEAD; xfrm_state_put(x); error_no_put: *errp = err; return NULL; } static int xfrm_add_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_usersa_info *p = nlmsg_data(nlh); struct xfrm_state *x; int err; struct km_event c; uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; err = verify_newsa_info(p, attrs); if (err) return err; x = xfrm_state_construct(net, p, attrs, &err); if (!x) return err; xfrm_state_hold(x); if (nlh->nlmsg_type == XFRM_MSG_NEWSA) err = xfrm_state_add(x); else err = xfrm_state_update(x); security_task_getsecid(current, &sid); xfrm_audit_state_add(x, err ? 0 : 1, loginuid, sessionid, sid); if (err < 0) { x->km.state = XFRM_STATE_DEAD; __xfrm_state_put(x); goto out; } c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: xfrm_state_put(x); return err; } static struct xfrm_state *xfrm_user_state_lookup(struct net *net, struct xfrm_usersa_id *p, struct nlattr **attrs, int *errp) { struct xfrm_state *x = NULL; struct xfrm_mark m; int err; u32 mark = xfrm_mark_get(attrs, &m); if (xfrm_id_proto_match(p->proto, IPSEC_PROTO_ANY)) { err = -ESRCH; x = xfrm_state_lookup(net, mark, &p->daddr, p->spi, p->proto, p->family); } else { xfrm_address_t *saddr = NULL; verify_one_addr(attrs, XFRMA_SRCADDR, &saddr); if (!saddr) { err = -EINVAL; goto out; } err = -ESRCH; x = xfrm_state_lookup_byaddr(net, mark, &p->daddr, saddr, p->proto, p->family); } out: if (!x && errp) *errp = err; return x; } static int xfrm_del_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; int err = -ESRCH; struct km_event c; struct xfrm_usersa_id *p = nlmsg_data(nlh); uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; x = xfrm_user_state_lookup(net, p, attrs, &err); if (x == NULL) return err; if ((err = security_xfrm_state_delete(x)) != 0) goto out; if (xfrm_state_kern(x)) { err = -EPERM; goto out; } err = xfrm_state_delete(x); if (err < 0) goto out; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.event = nlh->nlmsg_type; km_state_notify(x, &c); out: security_task_getsecid(current, &sid); xfrm_audit_state_delete(x, err ? 0 : 1, loginuid, sessionid, sid); xfrm_state_put(x); return err; } static void copy_to_user_state(struct xfrm_state *x, struct xfrm_usersa_info *p) { memset(p, 0, sizeof(*p)); memcpy(&p->id, &x->id, sizeof(p->id)); memcpy(&p->sel, &x->sel, sizeof(p->sel)); memcpy(&p->lft, &x->lft, sizeof(p->lft)); memcpy(&p->curlft, &x->curlft, sizeof(p->curlft)); memcpy(&p->stats, &x->stats, sizeof(p->stats)); memcpy(&p->saddr, &x->props.saddr, sizeof(p->saddr)); p->mode = x->props.mode; p->replay_window = x->props.replay_window; p->reqid = x->props.reqid; p->family = x->props.family; p->flags = x->props.flags; p->seq = x->km.seq; } struct xfrm_dump_info { struct sk_buff *in_skb; struct sk_buff *out_skb; u32 nlmsg_seq; u16 nlmsg_flags; }; static int copy_sec_ctx(struct xfrm_sec_ctx *s, struct sk_buff *skb) { struct xfrm_user_sec_ctx *uctx; struct nlattr *attr; int ctx_size = sizeof(*uctx) + s->ctx_len; attr = nla_reserve(skb, XFRMA_SEC_CTX, ctx_size); if (attr == NULL) return -EMSGSIZE; uctx = nla_data(attr); uctx->exttype = XFRMA_SEC_CTX; uctx->len = ctx_size; uctx->ctx_doi = s->ctx_doi; uctx->ctx_alg = s->ctx_alg; uctx->ctx_len = s->ctx_len; memcpy(uctx + 1, s->ctx_str, s->ctx_len); return 0; } static int copy_to_user_auth(struct xfrm_algo_auth *auth, struct sk_buff *skb) { struct xfrm_algo *algo; struct nlattr *nla; nla = nla_reserve(skb, XFRMA_ALG_AUTH, sizeof(*algo) + (auth->alg_key_len + 7) / 8); if (!nla) return -EMSGSIZE; algo = nla_data(nla); strncpy(algo->alg_name, auth->alg_name, sizeof(algo->alg_name)); memcpy(algo->alg_key, auth->alg_key, (auth->alg_key_len + 7) / 8); algo->alg_key_len = auth->alg_key_len; return 0; } /* Don't change this without updating xfrm_sa_len! */ static int copy_to_user_state_extra(struct xfrm_state *x, struct xfrm_usersa_info *p, struct sk_buff *skb) { int ret = 0; copy_to_user_state(x, p); if (x->coaddr) { ret = nla_put(skb, XFRMA_COADDR, sizeof(*x->coaddr), x->coaddr); if (ret) goto out; } if (x->lastused) { ret = nla_put_u64(skb, XFRMA_LASTUSED, x->lastused); if (ret) goto out; } if (x->aead) { ret = nla_put(skb, XFRMA_ALG_AEAD, aead_len(x->aead), x->aead); if (ret) goto out; } if (x->aalg) { ret = copy_to_user_auth(x->aalg, skb); if (!ret) ret = nla_put(skb, XFRMA_ALG_AUTH_TRUNC, xfrm_alg_auth_len(x->aalg), x->aalg); if (ret) goto out; } if (x->ealg) { ret = nla_put(skb, XFRMA_ALG_CRYPT, xfrm_alg_len(x->ealg), x->ealg); if (ret) goto out; } if (x->calg) { ret = nla_put(skb, XFRMA_ALG_COMP, sizeof(*(x->calg)), x->calg); if (ret) goto out; } if (x->encap) { ret = nla_put(skb, XFRMA_ENCAP, sizeof(*x->encap), x->encap); if (ret) goto out; } if (x->tfcpad) { ret = nla_put_u32(skb, XFRMA_TFCPAD, x->tfcpad); if (ret) goto out; } ret = xfrm_mark_put(skb, &x->mark); if (ret) goto out; if (x->replay_esn) { ret = nla_put(skb, XFRMA_REPLAY_ESN_VAL, xfrm_replay_state_esn_len(x->replay_esn), x->replay_esn); if (ret) goto out; } if (x->security) ret = copy_sec_ctx(x->security, skb); out: return ret; } static int dump_one_state(struct xfrm_state *x, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct xfrm_usersa_info *p; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWSA, sizeof(*p), sp->nlmsg_flags); if (nlh == NULL) return -EMSGSIZE; p = nlmsg_data(nlh); err = copy_to_user_state_extra(x, p, skb); if (err) { nlmsg_cancel(skb, nlh); return err; } nlmsg_end(skb, nlh); return 0; } static int xfrm_dump_sa_done(struct netlink_callback *cb) { struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1]; xfrm_state_walk_done(walk); return 0; } static int xfrm_dump_sa(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_state_walk *walk = (struct xfrm_state_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_state_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_state_walk_init(walk, 0); } (void) xfrm_state_walk(net, walk, dump_one_state, &info); return skb->len; } static struct sk_buff *xfrm_state_netlink(struct sk_buff *in_skb, struct xfrm_state *x, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; int err; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_ATOMIC); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; err = dump_one_state(x, 0, &info); if (err) { kfree_skb(skb); return ERR_PTR(err); } return skb; } static inline size_t xfrm_spdinfo_msgsize(void) { return NLMSG_ALIGN(4) + nla_total_size(sizeof(struct xfrmu_spdinfo)) + nla_total_size(sizeof(struct xfrmu_spdhinfo)); } static int build_spdinfo(struct sk_buff *skb, struct net *net, u32 pid, u32 seq, u32 flags) { struct xfrmk_spdinfo si; struct xfrmu_spdinfo spc; struct xfrmu_spdhinfo sph; struct nlmsghdr *nlh; int err; u32 *f; nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSPDINFO, sizeof(u32), 0); if (nlh == NULL) /* shouldn't really happen ... */ return -EMSGSIZE; f = nlmsg_data(nlh); *f = flags; xfrm_spd_getinfo(net, &si); spc.incnt = si.incnt; spc.outcnt = si.outcnt; spc.fwdcnt = si.fwdcnt; spc.inscnt = si.inscnt; spc.outscnt = si.outscnt; spc.fwdscnt = si.fwdscnt; sph.spdhcnt = si.spdhcnt; sph.spdhmcnt = si.spdhmcnt; err = nla_put(skb, XFRMA_SPD_INFO, sizeof(spc), &spc); if (!err) err = nla_put(skb, XFRMA_SPD_HINFO, sizeof(sph), &sph); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_get_spdinfo(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct sk_buff *r_skb; u32 *flags = nlmsg_data(nlh); u32 spid = NETLINK_CB(skb).pid; u32 seq = nlh->nlmsg_seq; r_skb = nlmsg_new(xfrm_spdinfo_msgsize(), GFP_ATOMIC); if (r_skb == NULL) return -ENOMEM; if (build_spdinfo(r_skb, net, spid, seq, *flags) < 0) BUG(); return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid); } static inline size_t xfrm_sadinfo_msgsize(void) { return NLMSG_ALIGN(4) + nla_total_size(sizeof(struct xfrmu_sadhinfo)) + nla_total_size(4); /* XFRMA_SAD_CNT */ } static int build_sadinfo(struct sk_buff *skb, struct net *net, u32 pid, u32 seq, u32 flags) { struct xfrmk_sadinfo si; struct xfrmu_sadhinfo sh; struct nlmsghdr *nlh; int err; u32 *f; nlh = nlmsg_put(skb, pid, seq, XFRM_MSG_NEWSADINFO, sizeof(u32), 0); if (nlh == NULL) /* shouldn't really happen ... */ return -EMSGSIZE; f = nlmsg_data(nlh); *f = flags; xfrm_sad_getinfo(net, &si); sh.sadhmcnt = si.sadhmcnt; sh.sadhcnt = si.sadhcnt; err = nla_put_u32(skb, XFRMA_SAD_CNT, si.sadcnt); if (!err) err = nla_put(skb, XFRMA_SAD_HINFO, sizeof(sh), &sh); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_get_sadinfo(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct sk_buff *r_skb; u32 *flags = nlmsg_data(nlh); u32 spid = NETLINK_CB(skb).pid; u32 seq = nlh->nlmsg_seq; r_skb = nlmsg_new(xfrm_sadinfo_msgsize(), GFP_ATOMIC); if (r_skb == NULL) return -ENOMEM; if (build_sadinfo(r_skb, net, spid, seq, *flags) < 0) BUG(); return nlmsg_unicast(net->xfrm.nlsk, r_skb, spid); } static int xfrm_get_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_usersa_id *p = nlmsg_data(nlh); struct xfrm_state *x; struct sk_buff *resp_skb; int err = -ESRCH; x = xfrm_user_state_lookup(net, p, attrs, &err); if (x == NULL) goto out_noput; resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); } xfrm_state_put(x); out_noput: return err; } static int verify_userspi_info(struct xfrm_userspi_info *p) { switch (p->info.id.proto) { case IPPROTO_AH: case IPPROTO_ESP: break; case IPPROTO_COMP: /* IPCOMP spi is 16-bits. */ if (p->max >= 0x10000) return -EINVAL; break; default: return -EINVAL; } if (p->min > p->max) return -EINVAL; return 0; } static int xfrm_alloc_userspi(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct xfrm_userspi_info *p; struct sk_buff *resp_skb; xfrm_address_t *daddr; int family; int err; u32 mark; struct xfrm_mark m; p = nlmsg_data(nlh); err = verify_userspi_info(p); if (err) goto out_noput; family = p->info.family; daddr = &p->info.id.daddr; x = NULL; mark = xfrm_mark_get(attrs, &m); if (p->info.seq) { x = xfrm_find_acq_byseq(net, mark, p->info.seq); if (x && xfrm_addr_cmp(&x->id.daddr, daddr, family)) { xfrm_state_put(x); x = NULL; } } if (!x) x = xfrm_find_acq(net, &m, p->info.mode, p->info.reqid, p->info.id.proto, daddr, &p->info.saddr, 1, family); err = -ENOENT; if (x == NULL) goto out_noput; err = xfrm_alloc_spi(x, p->min, p->max); if (err) goto out; resp_skb = xfrm_state_netlink(skb, x, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); goto out; } err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); out: xfrm_state_put(x); out_noput: return err; } static int verify_policy_dir(u8 dir) { switch (dir) { case XFRM_POLICY_IN: case XFRM_POLICY_OUT: case XFRM_POLICY_FWD: break; default: return -EINVAL; } return 0; } static int verify_policy_type(u8 type) { switch (type) { case XFRM_POLICY_TYPE_MAIN: #ifdef CONFIG_XFRM_SUB_POLICY case XFRM_POLICY_TYPE_SUB: #endif break; default: return -EINVAL; } return 0; } static int verify_newpolicy_info(struct xfrm_userpolicy_info *p) { switch (p->share) { case XFRM_SHARE_ANY: case XFRM_SHARE_SESSION: case XFRM_SHARE_USER: case XFRM_SHARE_UNIQUE: break; default: return -EINVAL; } switch (p->action) { case XFRM_POLICY_ALLOW: case XFRM_POLICY_BLOCK: break; default: return -EINVAL; } switch (p->sel.family) { case AF_INET: break; case AF_INET6: #if IS_ENABLED(CONFIG_IPV6) break; #else return -EAFNOSUPPORT; #endif default: return -EINVAL; } return verify_policy_dir(p->dir); } static int copy_from_user_sec_ctx(struct xfrm_policy *pol, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_user_sec_ctx *uctx; if (!rt) return 0; uctx = nla_data(rt); return security_xfrm_policy_alloc(&pol->security, uctx); } static void copy_templates(struct xfrm_policy *xp, struct xfrm_user_tmpl *ut, int nr) { int i; xp->xfrm_nr = nr; for (i = 0; i < nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&t->id, &ut->id, sizeof(struct xfrm_id)); memcpy(&t->saddr, &ut->saddr, sizeof(xfrm_address_t)); t->reqid = ut->reqid; t->mode = ut->mode; t->share = ut->share; t->optional = ut->optional; t->aalgos = ut->aalgos; t->ealgos = ut->ealgos; t->calgos = ut->calgos; /* If all masks are ~0, then we allow all algorithms. */ t->allalgs = !~(t->aalgos & t->ealgos & t->calgos); t->encap_family = ut->family; } } static int validate_tmpl(int nr, struct xfrm_user_tmpl *ut, u16 family) { int i; if (nr > XFRM_MAX_DEPTH) return -EINVAL; for (i = 0; i < nr; i++) { /* We never validated the ut->family value, so many * applications simply leave it at zero. The check was * never made and ut->family was ignored because all * templates could be assumed to have the same family as * the policy itself. Now that we will have ipv4-in-ipv6 * and ipv6-in-ipv4 tunnels, this is no longer true. */ if (!ut[i].family) ut[i].family = family; switch (ut[i].family) { case AF_INET: break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: break; #endif default: return -EINVAL; } } return 0; } static int copy_from_user_tmpl(struct xfrm_policy *pol, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_TMPL]; if (!rt) { pol->xfrm_nr = 0; } else { struct xfrm_user_tmpl *utmpl = nla_data(rt); int nr = nla_len(rt) / sizeof(*utmpl); int err; err = validate_tmpl(nr, utmpl, pol->family); if (err) return err; copy_templates(pol, utmpl, nr); } return 0; } static int copy_from_user_policy_type(u8 *tp, struct nlattr **attrs) { struct nlattr *rt = attrs[XFRMA_POLICY_TYPE]; struct xfrm_userpolicy_type *upt; u8 type = XFRM_POLICY_TYPE_MAIN; int err; if (rt) { upt = nla_data(rt); type = upt->type; } err = verify_policy_type(type); if (err) return err; *tp = type; return 0; } static void copy_from_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p) { xp->priority = p->priority; xp->index = p->index; memcpy(&xp->selector, &p->sel, sizeof(xp->selector)); memcpy(&xp->lft, &p->lft, sizeof(xp->lft)); xp->action = p->action; xp->flags = p->flags; xp->family = p->sel.family; /* XXX xp->share = p->share; */ } static void copy_to_user_policy(struct xfrm_policy *xp, struct xfrm_userpolicy_info *p, int dir) { memcpy(&p->sel, &xp->selector, sizeof(p->sel)); memcpy(&p->lft, &xp->lft, sizeof(p->lft)); memcpy(&p->curlft, &xp->curlft, sizeof(p->curlft)); p->priority = xp->priority; p->index = xp->index; p->sel.family = xp->family; p->dir = dir; p->action = xp->action; p->flags = xp->flags; p->share = XFRM_SHARE_ANY; /* XXX xp->share */ } static struct xfrm_policy *xfrm_policy_construct(struct net *net, struct xfrm_userpolicy_info *p, struct nlattr **attrs, int *errp) { struct xfrm_policy *xp = xfrm_policy_alloc(net, GFP_KERNEL); int err; if (!xp) { *errp = -ENOMEM; return NULL; } copy_from_user_policy(xp, p); err = copy_from_user_policy_type(&xp->type, attrs); if (err) goto error; if (!(err = copy_from_user_tmpl(xp, attrs))) err = copy_from_user_sec_ctx(xp, attrs); if (err) goto error; xfrm_mark_get(attrs, &xp->mark); return xp; error: *errp = err; xp->walk.dead = 1; xfrm_policy_destroy(xp); return NULL; } static int xfrm_add_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_userpolicy_info *p = nlmsg_data(nlh); struct xfrm_policy *xp; struct km_event c; int err; int excl; uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; err = verify_newpolicy_info(p); if (err) return err; err = verify_sec_ctx_len(attrs); if (err) return err; xp = xfrm_policy_construct(net, p, attrs, &err); if (!xp) return err; /* shouldn't excl be based on nlh flags?? * Aha! this is anti-netlink really i.e more pfkey derived * in netlink excl is a flag and you wouldnt need * a type XFRM_MSG_UPDPOLICY - JHS */ excl = nlh->nlmsg_type == XFRM_MSG_NEWPOLICY; err = xfrm_policy_insert(p->dir, xp, excl); security_task_getsecid(current, &sid); xfrm_audit_policy_add(xp, err ? 0 : 1, loginuid, sessionid, sid); if (err) { security_xfrm_policy_free(xp->security); kfree(xp); return err; } c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); xfrm_pol_put(xp); return 0; } static int copy_to_user_tmpl(struct xfrm_policy *xp, struct sk_buff *skb) { struct xfrm_user_tmpl vec[XFRM_MAX_DEPTH]; int i; if (xp->xfrm_nr == 0) return 0; for (i = 0; i < xp->xfrm_nr; i++) { struct xfrm_user_tmpl *up = &vec[i]; struct xfrm_tmpl *kp = &xp->xfrm_vec[i]; memcpy(&up->id, &kp->id, sizeof(up->id)); up->family = kp->encap_family; memcpy(&up->saddr, &kp->saddr, sizeof(up->saddr)); up->reqid = kp->reqid; up->mode = kp->mode; up->share = kp->share; up->optional = kp->optional; up->aalgos = kp->aalgos; up->ealgos = kp->ealgos; up->calgos = kp->calgos; } return nla_put(skb, XFRMA_TMPL, sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr, vec); } static inline int copy_to_user_state_sec_ctx(struct xfrm_state *x, struct sk_buff *skb) { if (x->security) { return copy_sec_ctx(x->security, skb); } return 0; } static inline int copy_to_user_sec_ctx(struct xfrm_policy *xp, struct sk_buff *skb) { if (xp->security) return copy_sec_ctx(xp->security, skb); return 0; } static inline size_t userpolicy_type_attrsize(void) { #ifdef CONFIG_XFRM_SUB_POLICY return nla_total_size(sizeof(struct xfrm_userpolicy_type)); #else return 0; #endif } #ifdef CONFIG_XFRM_SUB_POLICY static int copy_to_user_policy_type(u8 type, struct sk_buff *skb) { struct xfrm_userpolicy_type upt = { .type = type, }; return nla_put(skb, XFRMA_POLICY_TYPE, sizeof(upt), &upt); } #else static inline int copy_to_user_policy_type(u8 type, struct sk_buff *skb) { return 0; } #endif static int dump_one_policy(struct xfrm_policy *xp, int dir, int count, void *ptr) { struct xfrm_dump_info *sp = ptr; struct xfrm_userpolicy_info *p; struct sk_buff *in_skb = sp->in_skb; struct sk_buff *skb = sp->out_skb; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, NETLINK_CB(in_skb).pid, sp->nlmsg_seq, XFRM_MSG_NEWPOLICY, sizeof(*p), sp->nlmsg_flags); if (nlh == NULL) return -EMSGSIZE; p = nlmsg_data(nlh); copy_to_user_policy(xp, p, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_sec_ctx(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } nlmsg_end(skb, nlh); return 0; } static int xfrm_dump_policy_done(struct netlink_callback *cb) { struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; xfrm_policy_walk_done(walk); return 0; } static int xfrm_dump_policy(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); struct xfrm_policy_walk *walk = (struct xfrm_policy_walk *) &cb->args[1]; struct xfrm_dump_info info; BUILD_BUG_ON(sizeof(struct xfrm_policy_walk) > sizeof(cb->args) - sizeof(cb->args[0])); info.in_skb = cb->skb; info.out_skb = skb; info.nlmsg_seq = cb->nlh->nlmsg_seq; info.nlmsg_flags = NLM_F_MULTI; if (!cb->args[0]) { cb->args[0] = 1; xfrm_policy_walk_init(walk, XFRM_POLICY_TYPE_ANY); } (void) xfrm_policy_walk(net, walk, dump_one_policy, &info); return skb->len; } static struct sk_buff *xfrm_policy_netlink(struct sk_buff *in_skb, struct xfrm_policy *xp, int dir, u32 seq) { struct xfrm_dump_info info; struct sk_buff *skb; int err; skb = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!skb) return ERR_PTR(-ENOMEM); info.in_skb = in_skb; info.out_skb = skb; info.nlmsg_seq = seq; info.nlmsg_flags = 0; err = dump_one_policy(xp, dir, 0, &info); if (err) { kfree_skb(skb); return ERR_PTR(err); } return skb; } static int xfrm_get_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_userpolicy_id *p; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct km_event c; int delete; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); p = nlmsg_data(nlh); delete = nlh->nlmsg_type == XFRM_MSG_DELPOLICY; err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = verify_policy_dir(p->dir); if (err) return err; if (p->index) xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, delete, &err); else { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_sec_ctx *ctx; err = verify_sec_ctx_len(attrs); if (err) return err; ctx = NULL; if (rt) { struct xfrm_user_sec_ctx *uctx = nla_data(rt); err = security_xfrm_policy_alloc(&ctx, uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel, ctx, delete, &err); security_xfrm_policy_free(ctx); } if (xp == NULL) return -ENOENT; if (!delete) { struct sk_buff *resp_skb; resp_skb = xfrm_policy_netlink(skb, xp, p->dir, nlh->nlmsg_seq); if (IS_ERR(resp_skb)) { err = PTR_ERR(resp_skb); } else { err = nlmsg_unicast(net->xfrm.nlsk, resp_skb, NETLINK_CB(skb).pid); } } else { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); xfrm_audit_policy_delete(xp, err ? 0 : 1, loginuid, sessionid, sid); if (err != 0) goto out; c.data.byid = p->index; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; km_policy_notify(xp, p->dir, &c); } out: xfrm_pol_put(xp); return err; } static int xfrm_flush_sa(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; struct xfrm_usersa_flush *p = nlmsg_data(nlh); struct xfrm_audit audit_info; int err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_state_flush(net, p->proto, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.proto = p->proto; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_state_notify(NULL, &c); return 0; } static inline size_t xfrm_aevent_msgsize(struct xfrm_state *x) { size_t replay_size = x->replay_esn ? xfrm_replay_state_esn_len(x->replay_esn) : sizeof(struct xfrm_replay_state); return NLMSG_ALIGN(sizeof(struct xfrm_aevent_id)) + nla_total_size(replay_size) + nla_total_size(sizeof(struct xfrm_lifetime_cur)) + nla_total_size(sizeof(struct xfrm_mark)) + nla_total_size(4) /* XFRM_AE_RTHR */ + nla_total_size(4); /* XFRM_AE_ETHR */ } static int build_aevent(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c) { struct xfrm_aevent_id *id; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_NEWAE, sizeof(*id), 0); if (nlh == NULL) return -EMSGSIZE; id = nlmsg_data(nlh); memcpy(&id->sa_id.daddr, &x->id.daddr,sizeof(x->id.daddr)); id->sa_id.spi = x->id.spi; id->sa_id.family = x->props.family; id->sa_id.proto = x->id.proto; memcpy(&id->saddr, &x->props.saddr,sizeof(x->props.saddr)); id->reqid = x->props.reqid; id->flags = c->data.aevent; if (x->replay_esn) { err = nla_put(skb, XFRMA_REPLAY_ESN_VAL, xfrm_replay_state_esn_len(x->replay_esn), x->replay_esn); } else { err = nla_put(skb, XFRMA_REPLAY_VAL, sizeof(x->replay), &x->replay); } if (err) goto out_cancel; err = nla_put(skb, XFRMA_LTIME_VAL, sizeof(x->curlft), &x->curlft); if (err) goto out_cancel; if (id->flags & XFRM_AE_RTHR) { err = nla_put_u32(skb, XFRMA_REPLAY_THRESH, x->replay_maxdiff); if (err) goto out_cancel; } if (id->flags & XFRM_AE_ETHR) { err = nla_put_u32(skb, XFRMA_ETIMER_THRESH, x->replay_maxage * 10 / HZ); if (err) goto out_cancel; } err = xfrm_mark_put(skb, &x->mark); if (err) goto out_cancel; return nlmsg_end(skb, nlh); out_cancel: nlmsg_cancel(skb, nlh); return err; } static int xfrm_get_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct sk_buff *r_skb; int err; struct km_event c; u32 mark; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct xfrm_usersa_id *id = &p->sa_id; mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &id->daddr, id->spi, id->proto, id->family); if (x == NULL) return -ESRCH; r_skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC); if (r_skb == NULL) { xfrm_state_put(x); return -ENOMEM; } /* * XXX: is this lock really needed - none of the other * gets lock (the concern is things getting updated * while we are still reading) - jhs */ spin_lock_bh(&x->lock); c.data.aevent = p->flags; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; if (build_aevent(r_skb, x, &c) < 0) BUG(); err = nlmsg_unicast(net->xfrm.nlsk, r_skb, NETLINK_CB(skb).pid); spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_new_ae(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; struct km_event c; int err = - EINVAL; u32 mark = 0; struct xfrm_mark m; struct xfrm_aevent_id *p = nlmsg_data(nlh); struct nlattr *rp = attrs[XFRMA_REPLAY_VAL]; struct nlattr *re = attrs[XFRMA_REPLAY_ESN_VAL]; struct nlattr *lt = attrs[XFRMA_LTIME_VAL]; if (!lt && !rp && !re) return err; /* pedantic mode - thou shalt sayeth replaceth */ if (!(nlh->nlmsg_flags&NLM_F_REPLACE)) return err; mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->sa_id.daddr, p->sa_id.spi, p->sa_id.proto, p->sa_id.family); if (x == NULL) return -ESRCH; if (x->km.state != XFRM_STATE_VALID) goto out; err = xfrm_replay_verify_len(x->replay_esn, rp); if (err) goto out; spin_lock_bh(&x->lock); xfrm_update_ae_params(x, attrs); spin_unlock_bh(&x->lock); c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.data.aevent = XFRM_AE_CU; km_state_notify(x, &c); err = 0; out: xfrm_state_put(x); return err; } static int xfrm_flush_policy(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct km_event c; u8 type = XFRM_POLICY_TYPE_MAIN; int err; struct xfrm_audit audit_info; err = copy_from_user_policy_type(&type, attrs); if (err) return err; audit_info.loginuid = audit_get_loginuid(current); audit_info.sessionid = audit_get_sessionid(current); security_task_getsecid(current, &audit_info.secid); err = xfrm_policy_flush(net, type, &audit_info); if (err) { if (err == -ESRCH) /* empty table */ return 0; return err; } c.data.type = type; c.event = nlh->nlmsg_type; c.seq = nlh->nlmsg_seq; c.pid = nlh->nlmsg_pid; c.net = net; km_policy_notify(NULL, 0, &c); return 0; } static int xfrm_add_pol_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_user_polexpire *up = nlmsg_data(nlh); struct xfrm_userpolicy_info *p = &up->pol; u8 type = XFRM_POLICY_TYPE_MAIN; int err = -ENOENT; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = verify_policy_dir(p->dir); if (err) return err; if (p->index) xp = xfrm_policy_byid(net, mark, type, p->dir, p->index, 0, &err); else { struct nlattr *rt = attrs[XFRMA_SEC_CTX]; struct xfrm_sec_ctx *ctx; err = verify_sec_ctx_len(attrs); if (err) return err; ctx = NULL; if (rt) { struct xfrm_user_sec_ctx *uctx = nla_data(rt); err = security_xfrm_policy_alloc(&ctx, uctx); if (err) return err; } xp = xfrm_policy_bysel_ctx(net, mark, type, p->dir, &p->sel, ctx, 0, &err); security_xfrm_policy_free(ctx); } if (xp == NULL) return -ENOENT; if (unlikely(xp->walk.dead)) goto out; err = 0; if (up->hard) { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); xfrm_policy_delete(xp, p->dir); xfrm_audit_policy_delete(xp, 1, loginuid, sessionid, sid); } else { // reset the timers here? WARN(1, "Dont know what to do with soft policy expire\n"); } km_policy_expired(xp, p->dir, up->hard, current->pid); out: xfrm_pol_put(xp); return err; } static int xfrm_add_sa_expire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_state *x; int err; struct xfrm_user_expire *ue = nlmsg_data(nlh); struct xfrm_usersa_info *p = &ue->state; struct xfrm_mark m; u32 mark = xfrm_mark_get(attrs, &m); x = xfrm_state_lookup(net, mark, &p->id.daddr, p->id.spi, p->id.proto, p->family); err = -ENOENT; if (x == NULL) return err; spin_lock_bh(&x->lock); err = -EINVAL; if (x->km.state != XFRM_STATE_VALID) goto out; km_state_expired(x, ue->hard, current->pid); if (ue->hard) { uid_t loginuid = audit_get_loginuid(current); u32 sessionid = audit_get_sessionid(current); u32 sid; security_task_getsecid(current, &sid); __xfrm_state_delete(x); xfrm_audit_state_delete(x, 1, loginuid, sessionid, sid); } err = 0; out: spin_unlock_bh(&x->lock); xfrm_state_put(x); return err; } static int xfrm_add_acquire(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct net *net = sock_net(skb->sk); struct xfrm_policy *xp; struct xfrm_user_tmpl *ut; int i; struct nlattr *rt = attrs[XFRMA_TMPL]; struct xfrm_mark mark; struct xfrm_user_acquire *ua = nlmsg_data(nlh); struct xfrm_state *x = xfrm_state_alloc(net); int err = -ENOMEM; if (!x) goto nomem; xfrm_mark_get(attrs, &mark); err = verify_newpolicy_info(&ua->policy); if (err) goto bad_policy; /* build an XP */ xp = xfrm_policy_construct(net, &ua->policy, attrs, &err); if (!xp) goto free_state; memcpy(&x->id, &ua->id, sizeof(ua->id)); memcpy(&x->props.saddr, &ua->saddr, sizeof(ua->saddr)); memcpy(&x->sel, &ua->sel, sizeof(ua->sel)); xp->mark.m = x->mark.m = mark.m; xp->mark.v = x->mark.v = mark.v; ut = nla_data(rt); /* extract the templates and for each call km_key */ for (i = 0; i < xp->xfrm_nr; i++, ut++) { struct xfrm_tmpl *t = &xp->xfrm_vec[i]; memcpy(&x->id, &t->id, sizeof(x->id)); x->props.mode = t->mode; x->props.reqid = t->reqid; x->props.family = ut->family; t->aalgos = ua->aalgos; t->ealgos = ua->ealgos; t->calgos = ua->calgos; err = km_query(x, t, xp); } kfree(x); kfree(xp); return 0; bad_policy: WARN(1, "BAD policy passed\n"); free_state: kfree(x); nomem: return err; } #ifdef CONFIG_XFRM_MIGRATE static int copy_from_user_migrate(struct xfrm_migrate *ma, struct xfrm_kmaddress *k, struct nlattr **attrs, int *num) { struct nlattr *rt = attrs[XFRMA_MIGRATE]; struct xfrm_user_migrate *um; int i, num_migrate; if (k != NULL) { struct xfrm_user_kmaddress *uk; uk = nla_data(attrs[XFRMA_KMADDRESS]); memcpy(&k->local, &uk->local, sizeof(k->local)); memcpy(&k->remote, &uk->remote, sizeof(k->remote)); k->family = uk->family; k->reserved = uk->reserved; } um = nla_data(rt); num_migrate = nla_len(rt) / sizeof(*um); if (num_migrate <= 0 || num_migrate > XFRM_MAX_DEPTH) return -EINVAL; for (i = 0; i < num_migrate; i++, um++, ma++) { memcpy(&ma->old_daddr, &um->old_daddr, sizeof(ma->old_daddr)); memcpy(&ma->old_saddr, &um->old_saddr, sizeof(ma->old_saddr)); memcpy(&ma->new_daddr, &um->new_daddr, sizeof(ma->new_daddr)); memcpy(&ma->new_saddr, &um->new_saddr, sizeof(ma->new_saddr)); ma->proto = um->proto; ma->mode = um->mode; ma->reqid = um->reqid; ma->old_family = um->old_family; ma->new_family = um->new_family; } *num = i; return 0; } static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { struct xfrm_userpolicy_id *pi = nlmsg_data(nlh); struct xfrm_migrate m[XFRM_MAX_DEPTH]; struct xfrm_kmaddress km, *kmp; u8 type; int err; int n = 0; if (attrs[XFRMA_MIGRATE] == NULL) return -EINVAL; kmp = attrs[XFRMA_KMADDRESS] ? &km : NULL; err = copy_from_user_policy_type(&type, attrs); if (err) return err; err = copy_from_user_migrate((struct xfrm_migrate *)m, kmp, attrs, &n); if (err) return err; if (!n) return 0; xfrm_migrate(&pi->sel, pi->dir, type, m, n, kmp); return 0; } #else static int xfrm_do_migrate(struct sk_buff *skb, struct nlmsghdr *nlh, struct nlattr **attrs) { return -ENOPROTOOPT; } #endif #ifdef CONFIG_XFRM_MIGRATE static int copy_to_user_migrate(const struct xfrm_migrate *m, struct sk_buff *skb) { struct xfrm_user_migrate um; memset(&um, 0, sizeof(um)); um.proto = m->proto; um.mode = m->mode; um.reqid = m->reqid; um.old_family = m->old_family; memcpy(&um.old_daddr, &m->old_daddr, sizeof(um.old_daddr)); memcpy(&um.old_saddr, &m->old_saddr, sizeof(um.old_saddr)); um.new_family = m->new_family; memcpy(&um.new_daddr, &m->new_daddr, sizeof(um.new_daddr)); memcpy(&um.new_saddr, &m->new_saddr, sizeof(um.new_saddr)); return nla_put(skb, XFRMA_MIGRATE, sizeof(um), &um); } static int copy_to_user_kmaddress(const struct xfrm_kmaddress *k, struct sk_buff *skb) { struct xfrm_user_kmaddress uk; memset(&uk, 0, sizeof(uk)); uk.family = k->family; uk.reserved = k->reserved; memcpy(&uk.local, &k->local, sizeof(uk.local)); memcpy(&uk.remote, &k->remote, sizeof(uk.remote)); return nla_put(skb, XFRMA_KMADDRESS, sizeof(uk), &uk); } static inline size_t xfrm_migrate_msgsize(int num_migrate, int with_kma) { return NLMSG_ALIGN(sizeof(struct xfrm_userpolicy_id)) + (with_kma ? nla_total_size(sizeof(struct xfrm_kmaddress)) : 0) + nla_total_size(sizeof(struct xfrm_user_migrate) * num_migrate) + userpolicy_type_attrsize(); } static int build_migrate(struct sk_buff *skb, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k, const struct xfrm_selector *sel, u8 dir, u8 type) { const struct xfrm_migrate *mp; struct xfrm_userpolicy_id *pol_id; struct nlmsghdr *nlh; int i, err; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MIGRATE, sizeof(*pol_id), 0); if (nlh == NULL) return -EMSGSIZE; pol_id = nlmsg_data(nlh); /* copy data from selector, dir, and type to the pol_id */ memset(pol_id, 0, sizeof(*pol_id)); memcpy(&pol_id->sel, sel, sizeof(pol_id->sel)); pol_id->dir = dir; if (k != NULL) { err = copy_to_user_kmaddress(k, skb); if (err) goto out_cancel; } err = copy_to_user_policy_type(type, skb); if (err) goto out_cancel; for (i = 0, mp = m ; i < num_migrate; i++, mp++) { err = copy_to_user_migrate(mp, skb); if (err) goto out_cancel; } return nlmsg_end(skb, nlh); out_cancel: nlmsg_cancel(skb, nlh); return err; } static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k) { struct net *net = &init_net; struct sk_buff *skb; skb = nlmsg_new(xfrm_migrate_msgsize(num_migrate, !!k), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; /* build migrate */ if (build_migrate(skb, m, num_migrate, k, sel, dir, type) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MIGRATE, GFP_ATOMIC); } #else static int xfrm_send_migrate(const struct xfrm_selector *sel, u8 dir, u8 type, const struct xfrm_migrate *m, int num_migrate, const struct xfrm_kmaddress *k) { return -ENOPROTOOPT; } #endif #define XMSGSIZE(type) sizeof(struct type) static const int xfrm_msg_min[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_DELSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_GETSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_id), [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userspi_info), [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_acquire), [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_expire), [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_info), [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_info), [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_polexpire), [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = XMSGSIZE(xfrm_usersa_flush), [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = 0, [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), [XFRM_MSG_GETAE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_aevent_id), [XFRM_MSG_REPORT - XFRM_MSG_BASE] = XMSGSIZE(xfrm_user_report), [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = XMSGSIZE(xfrm_userpolicy_id), [XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = sizeof(u32), [XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = sizeof(u32), }; #undef XMSGSIZE static const struct nla_policy xfrma_policy[XFRMA_MAX+1] = { [XFRMA_SA] = { .len = sizeof(struct xfrm_usersa_info)}, [XFRMA_POLICY] = { .len = sizeof(struct xfrm_userpolicy_info)}, [XFRMA_LASTUSED] = { .type = NLA_U64}, [XFRMA_ALG_AUTH_TRUNC] = { .len = sizeof(struct xfrm_algo_auth)}, [XFRMA_ALG_AEAD] = { .len = sizeof(struct xfrm_algo_aead) }, [XFRMA_ALG_AUTH] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ALG_CRYPT] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ALG_COMP] = { .len = sizeof(struct xfrm_algo) }, [XFRMA_ENCAP] = { .len = sizeof(struct xfrm_encap_tmpl) }, [XFRMA_TMPL] = { .len = sizeof(struct xfrm_user_tmpl) }, [XFRMA_SEC_CTX] = { .len = sizeof(struct xfrm_sec_ctx) }, [XFRMA_LTIME_VAL] = { .len = sizeof(struct xfrm_lifetime_cur) }, [XFRMA_REPLAY_VAL] = { .len = sizeof(struct xfrm_replay_state) }, [XFRMA_REPLAY_THRESH] = { .type = NLA_U32 }, [XFRMA_ETIMER_THRESH] = { .type = NLA_U32 }, [XFRMA_SRCADDR] = { .len = sizeof(xfrm_address_t) }, [XFRMA_COADDR] = { .len = sizeof(xfrm_address_t) }, [XFRMA_POLICY_TYPE] = { .len = sizeof(struct xfrm_userpolicy_type)}, [XFRMA_MIGRATE] = { .len = sizeof(struct xfrm_user_migrate) }, [XFRMA_KMADDRESS] = { .len = sizeof(struct xfrm_user_kmaddress) }, [XFRMA_MARK] = { .len = sizeof(struct xfrm_mark) }, [XFRMA_TFCPAD] = { .type = NLA_U32 }, [XFRMA_REPLAY_ESN_VAL] = { .len = sizeof(struct xfrm_replay_state_esn) }, }; static struct xfrm_link { int (*doit)(struct sk_buff *, struct nlmsghdr *, struct nlattr **); int (*dump)(struct sk_buff *, struct netlink_callback *); int (*done)(struct netlink_callback *); } xfrm_dispatch[XFRM_NR_MSGTYPES] = { [XFRM_MSG_NEWSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_DELSA - XFRM_MSG_BASE] = { .doit = xfrm_del_sa }, [XFRM_MSG_GETSA - XFRM_MSG_BASE] = { .doit = xfrm_get_sa, .dump = xfrm_dump_sa, .done = xfrm_dump_sa_done }, [XFRM_MSG_NEWPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_DELPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy }, [XFRM_MSG_GETPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_get_policy, .dump = xfrm_dump_policy, .done = xfrm_dump_policy_done }, [XFRM_MSG_ALLOCSPI - XFRM_MSG_BASE] = { .doit = xfrm_alloc_userspi }, [XFRM_MSG_ACQUIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_acquire }, [XFRM_MSG_EXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_sa_expire }, [XFRM_MSG_UPDPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_add_policy }, [XFRM_MSG_UPDSA - XFRM_MSG_BASE] = { .doit = xfrm_add_sa }, [XFRM_MSG_POLEXPIRE - XFRM_MSG_BASE] = { .doit = xfrm_add_pol_expire}, [XFRM_MSG_FLUSHSA - XFRM_MSG_BASE] = { .doit = xfrm_flush_sa }, [XFRM_MSG_FLUSHPOLICY - XFRM_MSG_BASE] = { .doit = xfrm_flush_policy }, [XFRM_MSG_NEWAE - XFRM_MSG_BASE] = { .doit = xfrm_new_ae }, [XFRM_MSG_GETAE - XFRM_MSG_BASE] = { .doit = xfrm_get_ae }, [XFRM_MSG_MIGRATE - XFRM_MSG_BASE] = { .doit = xfrm_do_migrate }, [XFRM_MSG_GETSADINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_sadinfo }, [XFRM_MSG_GETSPDINFO - XFRM_MSG_BASE] = { .doit = xfrm_get_spdinfo }, }; static int xfrm_user_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh) { struct net *net = sock_net(skb->sk); struct nlattr *attrs[XFRMA_MAX+1]; struct xfrm_link *link; int type, err; type = nlh->nlmsg_type; if (type > XFRM_MSG_MAX) return -EINVAL; type -= XFRM_MSG_BASE; link = &xfrm_dispatch[type]; /* All operations require privileges, even GET */ if (!capable(CAP_NET_ADMIN)) return -EPERM; if ((type == (XFRM_MSG_GETSA - XFRM_MSG_BASE) || type == (XFRM_MSG_GETPOLICY - XFRM_MSG_BASE)) && (nlh->nlmsg_flags & NLM_F_DUMP)) { if (link->dump == NULL) return -EINVAL; { struct netlink_dump_control c = { .dump = link->dump, .done = link->done, }; return netlink_dump_start(net->xfrm.nlsk, skb, nlh, &c); } } err = nlmsg_parse(nlh, xfrm_msg_min[type], attrs, XFRMA_MAX, xfrma_policy); if (err < 0) return err; if (link->doit == NULL) return -EINVAL; return link->doit(skb, nlh, attrs); } static void xfrm_netlink_rcv(struct sk_buff *skb) { mutex_lock(&xfrm_cfg_mutex); netlink_rcv_skb(skb, &xfrm_user_rcv_msg); mutex_unlock(&xfrm_cfg_mutex); } static inline size_t xfrm_expire_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_expire)) + nla_total_size(sizeof(struct xfrm_mark)); } static int build_expire(struct sk_buff *skb, struct xfrm_state *x, const struct km_event *c) { struct xfrm_user_expire *ue; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_EXPIRE, sizeof(*ue), 0); if (nlh == NULL) return -EMSGSIZE; ue = nlmsg_data(nlh); copy_to_user_state(x, &ue->state); ue->hard = (c->data.hard != 0) ? 1 : 0; err = xfrm_mark_put(skb, &x->mark); if (err) return err; return nlmsg_end(skb, nlh); } static int xfrm_exp_state_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_expire_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_expire(skb, x, c) < 0) { kfree_skb(skb); return -EMSGSIZE; } return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_aevent_state_notify(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_aevent_msgsize(x), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_aevent(skb, x, c) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_AEVENTS, GFP_ATOMIC); } static int xfrm_notify_sa_flush(const struct km_event *c) { struct net *net = c->net; struct xfrm_usersa_flush *p; struct nlmsghdr *nlh; struct sk_buff *skb; int len = NLMSG_ALIGN(sizeof(struct xfrm_usersa_flush)); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHSA, sizeof(*p), 0); if (nlh == NULL) { kfree_skb(skb); return -EMSGSIZE; } p = nlmsg_data(nlh); p->proto = c->data.proto; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); } static inline size_t xfrm_sa_len(struct xfrm_state *x) { size_t l = 0; if (x->aead) l += nla_total_size(aead_len(x->aead)); if (x->aalg) { l += nla_total_size(sizeof(struct xfrm_algo) + (x->aalg->alg_key_len + 7) / 8); l += nla_total_size(xfrm_alg_auth_len(x->aalg)); } if (x->ealg) l += nla_total_size(xfrm_alg_len(x->ealg)); if (x->calg) l += nla_total_size(sizeof(*x->calg)); if (x->encap) l += nla_total_size(sizeof(*x->encap)); if (x->tfcpad) l += nla_total_size(sizeof(x->tfcpad)); if (x->replay_esn) l += nla_total_size(xfrm_replay_state_esn_len(x->replay_esn)); if (x->security) l += nla_total_size(sizeof(struct xfrm_user_sec_ctx) + x->security->ctx_len); if (x->coaddr) l += nla_total_size(sizeof(*x->coaddr)); /* Must count x->lastused as it may become non-zero behind our back. */ l += nla_total_size(sizeof(u64)); return l; } static int xfrm_notify_sa(struct xfrm_state *x, const struct km_event *c) { struct net *net = xs_net(x); struct xfrm_usersa_info *p; struct xfrm_usersa_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; int len = xfrm_sa_len(x); int headlen, err; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELSA) { len += nla_total_size(headlen); headlen = sizeof(*id); len += nla_total_size(sizeof(struct xfrm_mark)); } len += NLMSG_ALIGN(headlen); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; p = nlmsg_data(nlh); if (c->event == XFRM_MSG_DELSA) { struct nlattr *attr; id = nlmsg_data(nlh); memcpy(&id->daddr, &x->id.daddr, sizeof(id->daddr)); id->spi = x->id.spi; id->family = x->props.family; id->proto = x->id.proto; attr = nla_reserve(skb, XFRMA_SA, sizeof(*p)); err = -EMSGSIZE; if (attr == NULL) goto out_free_skb; p = nla_data(attr); } err = copy_to_user_state_extra(x, p, skb); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_SA, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_send_state_notify(struct xfrm_state *x, const struct km_event *c) { switch (c->event) { case XFRM_MSG_EXPIRE: return xfrm_exp_state_notify(x, c); case XFRM_MSG_NEWAE: return xfrm_aevent_state_notify(x, c); case XFRM_MSG_DELSA: case XFRM_MSG_UPDSA: case XFRM_MSG_NEWSA: return xfrm_notify_sa(x, c); case XFRM_MSG_FLUSHSA: return xfrm_notify_sa_flush(c); default: printk(KERN_NOTICE "xfrm_user: Unknown SA event %d\n", c->event); break; } return 0; } static inline size_t xfrm_acquire_msgsize(struct xfrm_state *x, struct xfrm_policy *xp) { return NLMSG_ALIGN(sizeof(struct xfrm_user_acquire)) + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr) + nla_total_size(sizeof(struct xfrm_mark)) + nla_total_size(xfrm_user_sec_ctx_size(x->security)) + userpolicy_type_attrsize(); } static int build_acquire(struct sk_buff *skb, struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { __u32 seq = xfrm_get_acqseq(); struct xfrm_user_acquire *ua; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_ACQUIRE, sizeof(*ua), 0); if (nlh == NULL) return -EMSGSIZE; ua = nlmsg_data(nlh); memcpy(&ua->id, &x->id, sizeof(ua->id)); memcpy(&ua->saddr, &x->props.saddr, sizeof(ua->saddr)); memcpy(&ua->sel, &x->sel, sizeof(ua->sel)); copy_to_user_policy(xp, &ua->policy, dir); ua->aalgos = xt->aalgos; ua->ealgos = xt->ealgos; ua->calgos = xt->calgos; ua->seq = x->km.seq = seq; err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_state_sec_ctx(x, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } return nlmsg_end(skb, nlh); } static int xfrm_send_acquire(struct xfrm_state *x, struct xfrm_tmpl *xt, struct xfrm_policy *xp, int dir) { struct net *net = xs_net(x); struct sk_buff *skb; skb = nlmsg_new(xfrm_acquire_msgsize(x, xp), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_acquire(skb, x, xt, xp, dir) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_ACQUIRE, GFP_ATOMIC); } /* User gives us xfrm_user_policy_info followed by an array of 0 * or more templates. */ static struct xfrm_policy *xfrm_compile_policy(struct sock *sk, int opt, u8 *data, int len, int *dir) { struct net *net = sock_net(sk); struct xfrm_userpolicy_info *p = (struct xfrm_userpolicy_info *)data; struct xfrm_user_tmpl *ut = (struct xfrm_user_tmpl *) (p + 1); struct xfrm_policy *xp; int nr; switch (sk->sk_family) { case AF_INET: if (opt != IP_XFRM_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #if IS_ENABLED(CONFIG_IPV6) case AF_INET6: if (opt != IPV6_XFRM_POLICY) { *dir = -EOPNOTSUPP; return NULL; } break; #endif default: *dir = -EINVAL; return NULL; } *dir = -EINVAL; if (len < sizeof(*p) || verify_newpolicy_info(p)) return NULL; nr = ((len - sizeof(*p)) / sizeof(*ut)); if (validate_tmpl(nr, ut, p->sel.family)) return NULL; if (p->dir > XFRM_POLICY_OUT) return NULL; xp = xfrm_policy_alloc(net, GFP_ATOMIC); if (xp == NULL) { *dir = -ENOBUFS; return NULL; } copy_from_user_policy(xp, p); xp->type = XFRM_POLICY_TYPE_MAIN; copy_templates(xp, ut, nr); *dir = p->dir; return xp; } static inline size_t xfrm_polexpire_msgsize(struct xfrm_policy *xp) { return NLMSG_ALIGN(sizeof(struct xfrm_user_polexpire)) + nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr) + nla_total_size(xfrm_user_sec_ctx_size(xp->security)) + nla_total_size(sizeof(struct xfrm_mark)) + userpolicy_type_attrsize(); } static int build_polexpire(struct sk_buff *skb, struct xfrm_policy *xp, int dir, const struct km_event *c) { struct xfrm_user_polexpire *upe; int hard = c->data.hard; struct nlmsghdr *nlh; int err; nlh = nlmsg_put(skb, c->pid, 0, XFRM_MSG_POLEXPIRE, sizeof(*upe), 0); if (nlh == NULL) return -EMSGSIZE; upe = nlmsg_data(nlh); copy_to_user_policy(xp, &upe->pol, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_sec_ctx(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) { nlmsg_cancel(skb, nlh); return err; } upe->hard = !!hard; return nlmsg_end(skb, nlh); } static int xfrm_exp_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { struct net *net = xp_net(xp); struct sk_buff *skb; skb = nlmsg_new(xfrm_polexpire_msgsize(xp), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_polexpire(skb, xp, dir, c) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_EXPIRE, GFP_ATOMIC); } static int xfrm_notify_policy(struct xfrm_policy *xp, int dir, const struct km_event *c) { int len = nla_total_size(sizeof(struct xfrm_user_tmpl) * xp->xfrm_nr); struct net *net = xp_net(xp); struct xfrm_userpolicy_info *p; struct xfrm_userpolicy_id *id; struct nlmsghdr *nlh; struct sk_buff *skb; int headlen, err; headlen = sizeof(*p); if (c->event == XFRM_MSG_DELPOLICY) { len += nla_total_size(headlen); headlen = sizeof(*id); } len += userpolicy_type_attrsize(); len += nla_total_size(sizeof(struct xfrm_mark)); len += NLMSG_ALIGN(headlen); skb = nlmsg_new(len, GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, c->event, headlen, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; p = nlmsg_data(nlh); if (c->event == XFRM_MSG_DELPOLICY) { struct nlattr *attr; id = nlmsg_data(nlh); memset(id, 0, sizeof(*id)); id->dir = dir; if (c->data.byid) id->index = xp->index; else memcpy(&id->sel, &xp->selector, sizeof(id->sel)); attr = nla_reserve(skb, XFRMA_POLICY, sizeof(*p)); err = -EMSGSIZE; if (attr == NULL) goto out_free_skb; p = nla_data(attr); } copy_to_user_policy(xp, p, dir); err = copy_to_user_tmpl(xp, skb); if (!err) err = copy_to_user_policy_type(xp->type, skb); if (!err) err = xfrm_mark_put(skb, &xp->mark); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_notify_policy_flush(const struct km_event *c) { struct net *net = c->net; struct nlmsghdr *nlh; struct sk_buff *skb; int err; skb = nlmsg_new(userpolicy_type_attrsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; nlh = nlmsg_put(skb, c->pid, c->seq, XFRM_MSG_FLUSHPOLICY, 0, 0); err = -EMSGSIZE; if (nlh == NULL) goto out_free_skb; err = copy_to_user_policy_type(c->data.type, skb); if (err) goto out_free_skb; nlmsg_end(skb, nlh); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_POLICY, GFP_ATOMIC); out_free_skb: kfree_skb(skb); return err; } static int xfrm_send_policy_notify(struct xfrm_policy *xp, int dir, const struct km_event *c) { switch (c->event) { case XFRM_MSG_NEWPOLICY: case XFRM_MSG_UPDPOLICY: case XFRM_MSG_DELPOLICY: return xfrm_notify_policy(xp, dir, c); case XFRM_MSG_FLUSHPOLICY: return xfrm_notify_policy_flush(c); case XFRM_MSG_POLEXPIRE: return xfrm_exp_policy_notify(xp, dir, c); default: printk(KERN_NOTICE "xfrm_user: Unknown Policy event %d\n", c->event); } return 0; } static inline size_t xfrm_report_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_report)); } static int build_report(struct sk_buff *skb, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct xfrm_user_report *ur; struct nlmsghdr *nlh; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_REPORT, sizeof(*ur), 0); if (nlh == NULL) return -EMSGSIZE; ur = nlmsg_data(nlh); ur->proto = proto; memcpy(&ur->sel, sel, sizeof(ur->sel)); if (addr) { int err = nla_put(skb, XFRMA_COADDR, sizeof(*addr), addr); if (err) { nlmsg_cancel(skb, nlh); return err; } } return nlmsg_end(skb, nlh); } static int xfrm_send_report(struct net *net, u8 proto, struct xfrm_selector *sel, xfrm_address_t *addr) { struct sk_buff *skb; skb = nlmsg_new(xfrm_report_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_report(skb, proto, sel, addr) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_REPORT, GFP_ATOMIC); } static inline size_t xfrm_mapping_msgsize(void) { return NLMSG_ALIGN(sizeof(struct xfrm_user_mapping)); } static int build_mapping(struct sk_buff *skb, struct xfrm_state *x, xfrm_address_t *new_saddr, __be16 new_sport) { struct xfrm_user_mapping *um; struct nlmsghdr *nlh; nlh = nlmsg_put(skb, 0, 0, XFRM_MSG_MAPPING, sizeof(*um), 0); if (nlh == NULL) return -EMSGSIZE; um = nlmsg_data(nlh); memcpy(&um->id.daddr, &x->id.daddr, sizeof(um->id.daddr)); um->id.spi = x->id.spi; um->id.family = x->props.family; um->id.proto = x->id.proto; memcpy(&um->new_saddr, new_saddr, sizeof(um->new_saddr)); memcpy(&um->old_saddr, &x->props.saddr, sizeof(um->old_saddr)); um->new_sport = new_sport; um->old_sport = x->encap->encap_sport; um->reqid = x->props.reqid; return nlmsg_end(skb, nlh); } static int xfrm_send_mapping(struct xfrm_state *x, xfrm_address_t *ipaddr, __be16 sport) { struct net *net = xs_net(x); struct sk_buff *skb; if (x->id.proto != IPPROTO_ESP) return -EINVAL; if (!x->encap) return -EINVAL; skb = nlmsg_new(xfrm_mapping_msgsize(), GFP_ATOMIC); if (skb == NULL) return -ENOMEM; if (build_mapping(skb, x, ipaddr, sport) < 0) BUG(); return nlmsg_multicast(net->xfrm.nlsk, skb, 0, XFRMNLGRP_MAPPING, GFP_ATOMIC); } static struct xfrm_mgr netlink_mgr = { .id = "netlink", .notify = xfrm_send_state_notify, .acquire = xfrm_send_acquire, .compile_policy = xfrm_compile_policy, .notify_policy = xfrm_send_policy_notify, .report = xfrm_send_report, .migrate = xfrm_send_migrate, .new_mapping = xfrm_send_mapping, }; static int __net_init xfrm_user_net_init(struct net *net) { struct sock *nlsk; struct netlink_kernel_cfg cfg = { .groups = XFRMNLGRP_MAX, .input = xfrm_netlink_rcv, }; nlsk = netlink_kernel_create(net, NETLINK_XFRM, THIS_MODULE, &cfg); if (nlsk == NULL) return -ENOMEM; net->xfrm.nlsk_stash = nlsk; /* Don't set to NULL */ rcu_assign_pointer(net->xfrm.nlsk, nlsk); return 0; } static void __net_exit xfrm_user_net_exit(struct list_head *net_exit_list) { struct net *net; list_for_each_entry(net, net_exit_list, exit_list) RCU_INIT_POINTER(net->xfrm.nlsk, NULL); synchronize_net(); list_for_each_entry(net, net_exit_list, exit_list) netlink_kernel_release(net->xfrm.nlsk_stash); } static struct pernet_operations xfrm_user_net_ops = { .init = xfrm_user_net_init, .exit_batch = xfrm_user_net_exit, }; static int __init xfrm_user_init(void) { int rv; printk(KERN_INFO "Initializing XFRM netlink socket\n"); rv = register_pernet_subsys(&xfrm_user_net_ops); if (rv < 0) return rv; rv = xfrm_register_km(&netlink_mgr); if (rv < 0) unregister_pernet_subsys(&xfrm_user_net_ops); return rv; } static void __exit xfrm_user_exit(void) { xfrm_unregister_km(&netlink_mgr); unregister_pernet_subsys(&xfrm_user_net_ops); } module_init(xfrm_user_init); module_exit(xfrm_user_exit); MODULE_LICENSE("GPL"); MODULE_ALIAS_NET_PF_PROTO(PF_NETLINK, NETLINK_XFRM);
./CrossVul/dataset_final_sorted/CWE-200/c/good_3825_0
crossvul-cpp_data_bad_3568_9
/* -*- Mode: c; c-basic-offset: 2 -*- * * raptor_rss.c - Raptor Feeds (RSS and Atom) tag soup parser * * Copyright (C) 2003-2010, David Beckett http://www.dajobe.org/ * Copyright (C) 2003-2005, University of Bristol, UK http://www.bristol.ac.uk/ * * This package is Free Software and part of Redland http://librdf.org/ * * It is licensed under the following three licenses as alternatives: * 1. GNU Lesser General Public License (LGPL) V2.1 or any newer version * 2. GNU General Public License (GPL) V2 or any newer version * 3. Apache License, V2.0 or any newer version * * You may not use this file except in compliance with at least one of * the above three licenses. * * See LICENSE.html or LICENSE.txt at the top of this package for the * complete terms and further detail along with the license texts for * the licenses in COPYING.LIB, COPYING and LICENSE-2.0.txt respectively. * * */ #ifdef HAVE_CONFIG_H #include <raptor_config.h> #endif #ifdef WIN32 #include <win32_raptor_config.h> #endif #include <stdio.h> #include <string.h> #include <ctype.h> #include <stdarg.h> #ifdef HAVE_ERRNO_H #include <errno.h> #endif /* Raptor includes */ #include "raptor2.h" #include "raptor_internal.h" #include "raptor_rss.h" /* local prototypes */ static void raptor_rss_uplift_items(raptor_parser* rdf_parser); static int raptor_rss_emit(raptor_parser* rdf_parser); static void raptor_rss_start_element_handler(void *user_data, raptor_xml_element* xml_element); static void raptor_rss_end_element_handler(void *user_data, raptor_xml_element* xml_element); static void raptor_rss_cdata_handler(void *user_data, raptor_xml_element* xml_element, const unsigned char *s, int len); static void raptor_rss_comment_handler(void *user_data, raptor_xml_element* xml_element, const unsigned char *s); static void raptor_rss_sax2_new_namespace_handler(void *user_data, raptor_namespace* nspace); /* * RSS parser object */ struct raptor_rss_parser_s { /* static model */ raptor_rss_model model; /* current line */ char *line; /* current line length */ int line_length; /* current char in line buffer */ int offset; /* static statement for use in passing to user code */ raptor_statement statement; raptor_sax2 *sax2; /* rss node type of current CONTAINER item */ raptor_rss_type current_type; /* one place stack */ raptor_rss_type prev_type; raptor_rss_fields_type current_field; /* emptyness of current element */ int element_is_empty; /* stack of namespaces */ raptor_namespace_stack *nstack; /* non-0 if this is an atom 1.0 parser */ int is_atom; /* namespaces declared here */ raptor_namespace* nspaces[RAPTOR_RSS_NAMESPACES_SIZE]; /* namespaces seen during parsing or creating output model */ char nspaces_seen[RAPTOR_RSS_NAMESPACES_SIZE]; /* current BLOCK pointer (inside CONTAINER of type current_type) */ raptor_rss_block *current_block; }; typedef struct raptor_rss_parser_s raptor_rss_parser; typedef enum { RAPTOR_RSS_CONTENT_TYPE_NONE, RAPTOR_RSS_CONTENT_TYPE_XML, RAPTOR_RSS_CONTENT_TYPE_TEXT } raptor_rss_content_type; struct raptor_rss_element_s { raptor_world* world; raptor_uri* uri; /* Two types of content */ raptor_rss_content_type type; /* 1) XML */ raptor_xml_writer* xml_writer; /* XML written to this iostream to the xml_content string */ raptor_iostream* iostream; /* ends up here */ void *xml_content; size_t xml_content_length; /* 2) cdata */ raptor_stringbuffer* sb; }; typedef struct raptor_rss_element_s raptor_rss_element; static void raptor_free_rss_element(raptor_rss_element *rss_element) { if(rss_element->uri) raptor_free_uri(rss_element->uri); if(rss_element->type == RAPTOR_RSS_CONTENT_TYPE_XML) { if(rss_element->xml_writer) raptor_free_xml_writer(rss_element->xml_writer); if(rss_element->iostream) raptor_free_iostream(rss_element->iostream); if(rss_element->xml_content) raptor_free_memory(rss_element->xml_content); } if(rss_element->sb) raptor_free_stringbuffer(rss_element->sb); RAPTOR_FREE(raptor_rss_element, rss_element); } static int raptor_rss_parse_init(raptor_parser* rdf_parser, const char *name) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; raptor_sax2* sax2; int n; raptor_rss_common_init(rdf_parser->world); raptor_rss_model_init(rdf_parser->world, &rss_parser->model); rss_parser->prev_type = RAPTOR_RSS_NONE; rss_parser->current_field = RAPTOR_RSS_FIELD_NONE; rss_parser->current_type = RAPTOR_RSS_NONE; rss_parser->current_block = NULL; if(rss_parser->sax2) { raptor_free_sax2(rss_parser->sax2); rss_parser->sax2 = NULL; } rss_parser->nstack = raptor_new_namespaces(rdf_parser->world, 1); /* Initialise the namespaces */ for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) { unsigned const char* prefix; raptor_uri* uri; raptor_namespace* nspace = NULL; prefix = (unsigned const char*)raptor_rss_namespaces_info[n].prefix; uri = rdf_parser->world->rss_namespaces_info_uris[n]; if(prefix && uri) nspace = raptor_new_namespace_from_uri(rss_parser->nstack, prefix, uri, 0); rss_parser->nspaces[n] = nspace; } sax2 = raptor_new_sax2(rdf_parser->world, &rdf_parser->locator, rdf_parser); rss_parser->sax2 = sax2; raptor_sax2_set_start_element_handler(sax2, raptor_rss_start_element_handler); raptor_sax2_set_end_element_handler(sax2, raptor_rss_end_element_handler); raptor_sax2_set_characters_handler(sax2, raptor_rss_cdata_handler); raptor_sax2_set_cdata_handler(sax2, raptor_rss_cdata_handler); raptor_sax2_set_comment_handler(sax2, raptor_rss_comment_handler); raptor_sax2_set_namespace_handler(sax2, raptor_rss_sax2_new_namespace_handler); raptor_statement_init(&rss_parser->statement, rdf_parser->world); return 0; } static void raptor_rss_parse_terminate(raptor_parser *rdf_parser) { raptor_rss_parser *rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; if(rss_parser->sax2) raptor_free_sax2(rss_parser->sax2); raptor_rss_model_clear(&rss_parser->model); for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) { if(rss_parser->nspaces[n]) raptor_free_namespace(rss_parser->nspaces[n]); } if(rss_parser->nstack) raptor_free_namespaces(rss_parser->nstack); raptor_rss_common_terminate(rdf_parser->world); } static int raptor_rss_parse_start(raptor_parser *rdf_parser) { raptor_uri *uri = rdf_parser->base_uri; raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int n; /* base URI required for RSS */ if(!uri) return 1; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) rss_parser->nspaces_seen[n] = 'N'; /* Optionally forbid internal network and file requests in the XML parser */ raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_NET, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_NET)); raptor_sax2_set_option(rss_parser->sax2, RAPTOR_OPTION_NO_FILE, NULL, RAPTOR_OPTIONS_GET_NUMERIC(rdf_parser, RAPTOR_OPTION_NO_FILE)); if(rdf_parser->uri_filter) raptor_sax2_set_uri_filter(rss_parser->sax2, rdf_parser->uri_filter, rdf_parser->uri_filter_user_data); raptor_sax2_parse_start(rss_parser->sax2, uri); return 0; } static int raptor_rss_add_container(raptor_rss_parser *rss_parser, const char *name) { raptor_rss_type type = RAPTOR_RSS_NONE; if(!strcmp(name, "rss") || !strcmp(name, "rdf") || !strcmp(name, "RDF")) { /* rss */ } else if(!raptor_strcasecmp(name, "channel")) { /* rss or atom 0.3 channel */ type = RAPTOR_RSS_CHANNEL; } else if(!strcmp(name, "feed")) { /* atom 1.0 feed */ type = RAPTOR_RSS_CHANNEL; rss_parser->is_atom = 1; } else if(!strcmp(name, "item")) { type = RAPTOR_RSS_ITEM; } else if(!strcmp(name, "entry")) { type = RAPTOR_RSS_ITEM; rss_parser->is_atom = 1; } else { int i; for(i = 0; i < RAPTOR_RSS_COMMON_SIZE; i++) { if(!(raptor_rss_items_info[i].flags & RAPTOR_RSS_ITEM_CONTAINER)) continue; if(!strcmp(name, raptor_rss_items_info[i].name)) { /* rss and atom clash on the author name field (rss) or type (atom) */ if(i != RAPTOR_ATOM_AUTHOR || (i == RAPTOR_ATOM_AUTHOR && rss_parser->is_atom)) { type = (raptor_rss_type)i; break; } } } } if(type != RAPTOR_RSS_NONE) { if(type == RAPTOR_RSS_ITEM) raptor_rss_model_add_item(&rss_parser->model); else raptor_rss_model_add_common(&rss_parser->model, type); /* Inner container - push the current type onto a 1-place stack */ if(rss_parser->current_type != RAPTOR_RSS_NONE) rss_parser->prev_type = rss_parser->current_type; rss_parser->current_type = type; } return (type == RAPTOR_RSS_NONE); } static raptor_uri* raptor_rss_promote_namespace_uri(raptor_world *world, raptor_uri* nspace_URI) { /* RSS 0.9 and RSS 1.1 namespaces => RSS 1.0 namespace */ if((raptor_uri_equals(nspace_URI, world->rss_namespaces_info_uris[RSS0_9_NS]) || raptor_uri_equals(nspace_URI, world->rss_namespaces_info_uris[RSS1_1_NS]))) { nspace_URI = world->rss_namespaces_info_uris[RSS1_0_NS]; } /* Atom 0.3 namespace => Atom 1.0 namespace */ if(raptor_uri_equals(nspace_URI, world->rss_namespaces_info_uris[ATOM0_3_NS])) { nspace_URI = world->rss_namespaces_info_uris[ATOM1_0_NS]; } return nspace_URI; } static raptor_rss_item* raptor_rss_get_current_item(raptor_rss_parser *rss_parser) { raptor_rss_item* item; if(rss_parser->current_type == RAPTOR_RSS_ITEM) item = rss_parser->model.last; else item = raptor_rss_model_get_common(&rss_parser->model, rss_parser->current_type); return item; } static int raptor_rss_block_set_field(raptor_world *world, raptor_uri *base_uri, raptor_rss_block *block, const raptor_rss_block_field_info *bfi, const char *string) { int attribute_type = bfi->attribute_type; int offset = bfi->offset; if(attribute_type == RSS_BLOCK_FIELD_TYPE_URL) { raptor_uri* uri; uri = raptor_new_uri_relative_to_base(world, base_uri, (const unsigned char*)string); if(!uri) return 1; block->urls[offset] = uri; } else if(attribute_type == RSS_BLOCK_FIELD_TYPE_STRING) { size_t len = strlen(string); block->strings[offset] = RAPTOR_MALLOC(char*, len + 1); if(!block->strings[offset]) return 1; memcpy(block->strings[offset], string, len+1); } else { #ifdef RAPTOR_DEBUG RAPTOR_FATAL2("Found unknown attribute_type %d\n", attribute_type); #endif return 1; } return 0; } static void raptor_rss_start_element_handler(void *user_data, raptor_xml_element* xml_element) { raptor_parser *rdf_parser; raptor_rss_parser *rss_parser; raptor_rss_block *block = NULL; raptor_uri* base_uri; raptor_qname *el_qname; const unsigned char *name; int ns_attributes_count; raptor_qname** named_attrs; const raptor_namespace* el_nspace; raptor_rss_element* rss_element; int i; rdf_parser = (raptor_parser*)user_data; rss_parser = (raptor_rss_parser*)rdf_parser->context; rss_element = RAPTOR_CALLOC(raptor_rss_element*, 1, sizeof(*rss_element)); if(!rss_element) { rdf_parser->failed = 1; return; } rss_element->world = rdf_parser->world; rss_element->sb = raptor_new_stringbuffer(); xml_element->user_data = rss_element; if(xml_element->parent) { raptor_rss_element* parent_rss_element; parent_rss_element = (raptor_rss_element*)(xml_element->parent->user_data); if(parent_rss_element->xml_writer) rss_element->xml_writer = parent_rss_element->xml_writer; } if(rss_element->xml_writer) { raptor_xml_writer_start_element(rss_element->xml_writer, xml_element); return; } el_qname = raptor_xml_element_get_name(xml_element); name = el_qname->local_name; el_nspace = el_qname->nspace; named_attrs = raptor_xml_element_get_attributes(xml_element); ns_attributes_count = raptor_xml_element_get_attributes_count(xml_element); base_uri = raptor_sax2_inscope_base_uri(rss_parser->sax2); /* No container type - identify and record in rss_parser->current_type * either as a top-level container or an inner-container */ if(!raptor_rss_add_container(rss_parser, (const char*)name)) { #ifdef RAPTOR_DEBUG if(1) { raptor_rss_type old_type = rss_parser->prev_type; if(old_type != rss_parser->current_type && old_type != RAPTOR_RSS_NONE) RAPTOR_DEBUG5("FOUND inner container type %d - %s INSIDE current container type %d - %s\n", rss_parser->current_type, raptor_rss_items_info[rss_parser->current_type].name, old_type, raptor_rss_items_info[old_type].name); else RAPTOR_DEBUG3("FOUND container type %d - %s\n", rss_parser->current_type, raptor_rss_items_info[rss_parser->current_type].name); } #endif /* check a few container attributes */ if(named_attrs) { raptor_rss_item* update_item = raptor_rss_get_current_item(rss_parser); for(i = 0; i < ns_attributes_count; i++) { raptor_qname* attr = named_attrs[i]; const char* attrName = (const char*)attr->local_name; const unsigned char* attrValue = attr->value; RAPTOR_DEBUG3(" container attribute %s=%s\n", attrName, attrValue); if(!strcmp(attrName, "about")) { if(update_item) { update_item->uri = raptor_new_uri(rdf_parser->world, attrValue); update_item->term = raptor_new_term_from_uri(rdf_parser->world, update_item->uri); } } } } return; } else if(rss_parser->current_type == RAPTOR_RSS_NONE) { RAPTOR_DEBUG2("Unknown container element named %s\n", name); /* Nothing more that can be done with unknown element - skip it */ return; } /* have container (current_type) so this element is inside it is either: * 1. a metadata block element (such as rss:enclosure) * 2. a field (such as atom:title) */ /* Find field ID */ rss_parser->current_field = RAPTOR_RSS_FIELD_UNKNOWN; for(i = 0; i < RAPTOR_RSS_FIELDS_SIZE; i++) { raptor_uri* nspace_URI; raptor_uri* field_nspace_URI; rss_info_namespace nsid = raptor_rss_fields_info[i].nspace; if(strcmp((const char*)name, raptor_rss_fields_info[i].name)) continue; if(!el_nspace) { if(nsid != RSS_NO_NS && nsid != RSS1_0_NS && nsid != RSS0_91_NS && nsid != RSS0_9_NS && nsid != RSS1_1_NS) continue; /* Matches if the element has no namespace and field is not atom */ rss_parser->current_field = (raptor_rss_fields_type)i; break; } /* Promote element namespaces */ nspace_URI = raptor_rss_promote_namespace_uri(rdf_parser->world, raptor_namespace_get_uri(el_nspace)); field_nspace_URI = rdf_parser->world->rss_namespaces_info_uris[raptor_rss_fields_info[i].nspace]; if(raptor_uri_equals(nspace_URI, field_nspace_URI)) { rss_parser->current_field = (raptor_rss_fields_type)i; break; } } if(rss_parser->current_field == RAPTOR_RSS_FIELD_UNKNOWN) { RAPTOR_DEBUG3("Unknown field element named %s inside type %s\n", name, raptor_rss_items_info[rss_parser->current_type].name); return; } /* Found a block element to process */ if(raptor_rss_fields_info[rss_parser->current_field].flags & RAPTOR_RSS_INFO_FLAG_BLOCK_VALUE) { raptor_rss_type block_type; raptor_rss_item* update_item; const unsigned char *id; raptor_term* block_term; block_type = raptor_rss_fields_info[rss_parser->current_field].block_type; RAPTOR_DEBUG3("FOUND new block type %d - %s\n", block_type, raptor_rss_items_info[block_type].name); update_item = raptor_rss_get_current_item(rss_parser); id = raptor_world_generate_bnodeid(rdf_parser->world); block_term = raptor_new_term_from_blank(rdf_parser->world, id); RAPTOR_FREE(char*, id); block = raptor_new_rss_block(rdf_parser->world, block_type, block_term); raptor_free_term(block_term); raptor_rss_item_add_block(update_item, block); rss_parser->current_block = block; rss_parser->nspaces_seen[raptor_rss_items_info[block_type].nspace] = 'Y'; /* Now check block attributes */ if(named_attrs) { for(i = 0; i < ns_attributes_count; i++) { raptor_qname* attr = named_attrs[i]; const char* attrName = (const char*)attr->local_name; const unsigned char* attrValue = attr->value; const raptor_rss_block_field_info *bfi; int offset = -1; for(bfi = &raptor_rss_block_fields_info[0]; bfi->type != RAPTOR_RSS_NONE; bfi++) { if(!bfi->attribute) continue; if(bfi->type == block_type && !strcmp(attrName, bfi->attribute)) { offset = bfi->offset; break; } } if(offset < 0) continue; /* Found attribute for this block type */ RAPTOR_DEBUG3(" found block attribute %s=%s\n", attrName, attrValue); if(raptor_rss_block_set_field(rdf_parser->world, base_uri, block, bfi, (const char*)attrValue)) { rdf_parser->failed = 1; return; } } } return; } /* Process field */ RAPTOR_DEBUG4("FOUND field %d - %s inside type %s\n", rss_parser->current_field, raptor_rss_fields_info[rss_parser->current_field].name, raptor_rss_items_info[rss_parser->current_type].name); /* Mark namespace seen in new field */ if(1) { rss_info_namespace ns_index; ns_index = raptor_rss_fields_info[rss_parser->current_field].nspace; rss_parser->nspaces_seen[ns_index] = 'Y'; } /* Now check for field attributes */ if(named_attrs) { for(i = 0; i < ns_attributes_count; i++) { raptor_qname* attr = named_attrs[i]; const unsigned char* attrName = attr->local_name; const unsigned char* attrValue = attr->value; RAPTOR_DEBUG3(" attribute %s=%s\n", attrName, attrValue); /* Pick a few attributes to care about */ if(!strcmp((const char*)attrName, "isPermaLink")) { raptor_rss_item* update_item = rss_parser->model.last; if(!strcmp((const char*)name, "guid")) { /* <guid isPermaLink="..."> */ if(update_item) { raptor_rss_field* field = raptor_rss_new_field(rdf_parser->world); RAPTOR_DEBUG1("fa1 - "); raptor_rss_item_add_field(update_item, RAPTOR_RSS_FIELD_GUID, field); if(!strcmp((const char*)attrValue, "true")) { RAPTOR_DEBUG2(" setting guid to URI '%s'\n", attrValue); field->uri = raptor_new_uri_relative_to_base(rdf_parser->world, base_uri, (const unsigned char*)attrValue); } else { size_t len = strlen((const char*)attrValue); RAPTOR_DEBUG2(" setting guid to string '%s'\n", attrValue); field->value = RAPTOR_MALLOC(unsigned char*, len + 1); if(!field->value) { rdf_parser->failed = 1; return; } memcpy(field->value, attrValue, len + 1); } } } } else if(!strcmp((const char*)attrName, "href")) { if(rss_parser->current_field == RAPTOR_RSS_FIELD_LINK || rss_parser->current_field == RAPTOR_RSS_FIELD_ATOM_LINK) { RAPTOR_DEBUG2(" setting href as URI string for type %s\n", raptor_rss_items_info[rss_parser->current_type].name); if(rss_element->uri) raptor_free_uri(rss_element->uri); rss_element->uri = raptor_new_uri_relative_to_base(rdf_parser->world, base_uri, (const unsigned char*)attrValue); } } else if(!strcmp((const char*)attrName, "type")) { if(rss_parser->current_field == RAPTOR_RSS_FIELD_ATOM_LINK) { /* do nothing with atom link attribute type */ } else if(rss_parser->is_atom) { /* Atom only typing */ if(!strcmp((const char*)attrValue, "xhtml") || !strcmp((const char*)attrValue, "xml") || strstr((const char*)attrValue, "+xml")) { RAPTOR_DEBUG2(" found type '%s', making an XML writer\n", attrValue); rss_element->type = RAPTOR_RSS_CONTENT_TYPE_XML; rss_element->iostream = raptor_new_iostream_to_string(rdf_parser->world, &rss_element->xml_content, &rss_element->xml_content_length, raptor_alloc_memory); rss_element->xml_writer = raptor_new_xml_writer(rdf_parser->world, NULL, rss_element->iostream); raptor_xml_writer_set_option(rss_element->xml_writer, RAPTOR_OPTION_WRITER_XML_DECLARATION, NULL, 0); raptor_free_stringbuffer(rss_element->sb); rss_element->sb = NULL; } } } else if(!strcmp((const char*)attrName, "version")) { if(!raptor_strcasecmp((const char*)name, "feed")) { if(!strcmp((const char*)attrValue, "0.3")) rss_parser->is_atom = 1; } } } } /* if have field attributes */ } static void raptor_rss_end_element_handler(void *user_data, raptor_xml_element* xml_element) { raptor_parser* rdf_parser; raptor_rss_parser* rss_parser; #ifdef RAPTOR_DEBUG const unsigned char* name = raptor_xml_element_get_name(xml_element)->local_name; #endif raptor_rss_element* rss_element; size_t cdata_len = 0; unsigned char* cdata = NULL; rss_element = (raptor_rss_element*)xml_element->user_data; rdf_parser = (raptor_parser*)user_data; rss_parser = (raptor_rss_parser*)rdf_parser->context; if(rss_element->xml_writer) { if(rss_element->type != RAPTOR_RSS_CONTENT_TYPE_XML) { raptor_xml_writer_end_element(rss_element->xml_writer, xml_element); goto tidy_end_element; } /* otherwise we are done making XML */ raptor_free_iostream(rss_element->iostream); rss_element->iostream = NULL; cdata = (unsigned char*)rss_element->xml_content; cdata_len = rss_element->xml_content_length; } if(rss_element->sb) { cdata_len = raptor_stringbuffer_length(rss_element->sb); cdata = raptor_stringbuffer_as_string(rss_element->sb); } if(cdata) { raptor_uri* base_uri = NULL; base_uri = raptor_sax2_inscope_base_uri(rss_parser->sax2); if(rss_parser->current_block) { const raptor_rss_block_field_info *bfi; int handled = 0; /* in a block, maybe store the CDATA there */ for(bfi = &raptor_rss_block_fields_info[0]; bfi->type != RAPTOR_RSS_NONE; bfi++) { if(bfi->type != rss_parser->current_block->rss_type || bfi->attribute != NULL) continue; /* Set author name from element */ if(raptor_rss_block_set_field(rdf_parser->world, base_uri, rss_parser->current_block, bfi, (const char*)cdata)) { rdf_parser->failed = 1; return; } handled = 1; break; } #ifdef RAPTOR_DEBUG if(!handled) { raptor_rss_type block_type = rss_parser->current_block->rss_type; RAPTOR_DEBUG3("Ignoring cdata for block %d - %s\n", block_type, raptor_rss_items_info[block_type].name); } #endif rss_parser->current_block = NULL; goto do_end_element; } if(rss_parser->current_type == RAPTOR_RSS_NONE || (rss_parser->current_field == RAPTOR_RSS_FIELD_NONE || rss_parser->current_field == RAPTOR_RSS_FIELD_UNKNOWN)) { unsigned char *p = cdata; size_t i; for(i = cdata_len; i > 0 && *p; i--) { if(!isspace(*p)) break; p++; } if(i > 0 && *p) { RAPTOR_DEBUG4("IGNORING non-whitespace text '%s' inside type %s, field %s\n", cdata, raptor_rss_items_info[rss_parser->current_type].name, raptor_rss_fields_info[rss_parser->current_field].name); } goto do_end_element; } if(rss_parser->current_type >= RAPTOR_RSS_COMMON_IGNORED) { /* skipHours, skipDays common but IGNORED */ RAPTOR_DEBUG2("Ignoring fields for type %s\n", raptor_rss_items_info[rss_parser->current_type].name); } else { raptor_rss_item* update_item = raptor_rss_get_current_item(rss_parser); raptor_rss_field* field = raptor_rss_new_field(rdf_parser->world); /* if value is always an uri, make it so */ if(raptor_rss_fields_info[rss_parser->current_field].flags & RAPTOR_RSS_INFO_FLAG_URI_VALUE) { RAPTOR_DEBUG4("Added URI %s to field %s of type %s\n", cdata, raptor_rss_fields_info[rss_parser->current_field].name, raptor_rss_items_info[rss_parser->current_type].name); field->uri = raptor_new_uri_relative_to_base(rdf_parser->world, base_uri, cdata); } else { RAPTOR_DEBUG4("Added text '%s' to field %s of type %s\n", cdata, raptor_rss_fields_info[rss_parser->current_field].name, raptor_rss_items_info[rss_parser->current_type].name); field->uri = NULL; field->value = RAPTOR_MALLOC(unsigned char*, cdata_len + 1); if(!field->value) { rdf_parser->failed = 1; return; } memcpy(field->value, cdata, cdata_len); field->value[cdata_len] = '\0'; } RAPTOR_DEBUG1("fa3 - "); raptor_rss_item_add_field(update_item, rss_parser->current_field, field); } } /* end if contained cdata */ if(raptor_xml_element_is_empty(xml_element)) { /* Empty element, so consider adding one of the attributes as * literal or URI content */ if(rss_parser->current_type >= RAPTOR_RSS_COMMON_IGNORED) { /* skipHours, skipDays common but IGNORED */ RAPTOR_DEBUG3("Ignoring empty element %s for type %s\n", name, raptor_rss_items_info[rss_parser->current_type].name); } else if(rss_element->uri) { raptor_rss_item* update_item = raptor_rss_get_current_item(rss_parser); raptor_rss_field* field = raptor_rss_new_field(rdf_parser->world); if(rss_parser->current_field == RAPTOR_RSS_FIELD_UNKNOWN) { RAPTOR_DEBUG2("Cannot add URI from alternate attribute to type %s unknown field\n", raptor_rss_items_info[rss_parser->current_type].name); raptor_rss_field_free(field); } else { RAPTOR_DEBUG3("Added URI to field %s of type %s\n", raptor_rss_fields_info[rss_parser->current_field].name, raptor_rss_items_info[rss_parser->current_type].name); field->uri = rss_element->uri; rss_element->uri = NULL; RAPTOR_DEBUG1("fa2 - "); raptor_rss_item_add_field(update_item, rss_parser->current_field, field); } } } do_end_element: if(rss_parser->current_type != RAPTOR_RSS_NONE) { if(rss_parser->current_field != RAPTOR_RSS_FIELD_NONE) { RAPTOR_DEBUG3("Ending element %s field %s\n", name, raptor_rss_fields_info[rss_parser->current_field].name); rss_parser->current_field = RAPTOR_RSS_FIELD_NONE; } else { RAPTOR_DEBUG3("Ending element %s type %s\n", name, raptor_rss_items_info[rss_parser->current_type].name); if(rss_parser->prev_type != RAPTOR_RSS_NONE) { rss_parser->current_type = rss_parser->prev_type; rss_parser->prev_type = RAPTOR_RSS_NONE; RAPTOR_DEBUG3("Returning to type %d - %s\n", rss_parser->current_type, raptor_rss_items_info[rss_parser->current_type].name); } else rss_parser->current_type = RAPTOR_RSS_NONE; } } if(rss_parser->current_block) { #ifdef RAPTOR_DEBUG raptor_rss_type block_type = rss_parser->current_block->rss_type; RAPTOR_DEBUG3("Ending current block %d - %s\n", block_type, raptor_rss_items_info[block_type].name); #endif rss_parser->current_block = NULL; } tidy_end_element: if(rss_element) raptor_free_rss_element(rss_element); } static void raptor_rss_cdata_handler(void *user_data, raptor_xml_element* xml_element, const unsigned char *s, int len) { raptor_rss_element* rss_element; rss_element = (raptor_rss_element*)xml_element->user_data; if(rss_element->xml_writer) { raptor_xml_writer_cdata_counted(rss_element->xml_writer, s, len); return; } raptor_stringbuffer_append_counted_string(rss_element->sb, s, len, 1); } static void raptor_rss_comment_handler(void *user_data, raptor_xml_element* xml_element, const unsigned char *s) { raptor_rss_element* rss_element; if(!xml_element) return; rss_element = (raptor_rss_element*)xml_element->user_data; if(rss_element->xml_writer) { raptor_xml_writer_comment(rss_element->xml_writer, s); return; } } static void raptor_rss_sax2_new_namespace_handler(void *user_data, raptor_namespace* nspace) { raptor_parser* rdf_parser = (raptor_parser*)user_data; raptor_rss_parser* rss_parser; int n; rss_parser = (raptor_rss_parser*)rdf_parser->context; for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) { raptor_uri* ns_uri = rdf_parser->world->rss_namespaces_info_uris[n]; if(!ns_uri) continue; if(!raptor_uri_equals(ns_uri, nspace->uri)) { rss_parser->nspaces_seen[n] = 'Y'; break; } } } /* Add an rss:link from string contents of either: * atom:id * atom:link[@rel="self"]/@href */ static int raptor_rss_insert_rss_link(raptor_parser* rdf_parser, raptor_rss_item* item) { raptor_rss_block *block; raptor_rss_field* id_field; raptor_rss_field* field = NULL; /* Try atom:id first */ id_field = item->fields[RAPTOR_RSS_FIELD_ATOM_ID]; if(id_field && id_field->value) { const char *value = (const char*)id_field->value; size_t len = strlen(value); field = raptor_rss_new_field(item->world); if(!field) return 1; field->value = RAPTOR_MALLOC(unsigned char*, len + 1); if(!field->value) return 1; memcpy(field->value, value, len + 1); raptor_rss_item_add_field(item, RAPTOR_RSS_FIELD_LINK, field); return 0; } for(block = item->blocks; block; block = block->next) { if(block->rss_type != RAPTOR_ATOM_LINK) continue; /* <link @href> is url at offset RAPTOR_RSS_LINK_HREF_URL_OFFSET * <link @rel> is string at offset RAPTOR_RSS_LINK_REL_STRING_OFFSET * The raptor_rss_block_fields_info structure records this */ if(!block->urls[RAPTOR_RSS_LINK_HREF_URL_OFFSET] || (block->strings[RAPTOR_RSS_LINK_REL_STRING_OFFSET] && strcmp(block->strings[RAPTOR_RSS_LINK_REL_STRING_OFFSET], "self")) ) continue; /* set the field rss:link to the string value of the @href */ field = raptor_rss_new_field(item->world); field->value = raptor_uri_to_string(block->urls[0]); raptor_rss_item_add_field(item, RAPTOR_RSS_FIELD_LINK, field); return 0; } return 0; } static int raptor_rss_insert_identifiers(raptor_parser* rdf_parser) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int i; raptor_rss_item* item; for(i = 0; i< RAPTOR_RSS_COMMON_SIZE; i++) { for(item = rss_parser->model.common[i]; item; item = item->next) { if(!item->fields_count) continue; RAPTOR_DEBUG3("Inserting identifiers in common type %d - %s\n", i, raptor_rss_items_info[i].name); if(item->uri) { item->term = raptor_new_term_from_uri(rdf_parser->world, item->uri); } else { int url_fields[2]; int url_fields_count = 1; int f; url_fields[0] = (i== RAPTOR_RSS_IMAGE) ? RAPTOR_RSS_FIELD_URL : RAPTOR_RSS_FIELD_LINK; if(i == RAPTOR_RSS_CHANNEL) { url_fields[1] = RAPTOR_RSS_FIELD_ATOM_ID; url_fields_count++; } for(f = 0; f < url_fields_count; f++) { raptor_rss_field* field; for(field = item->fields[url_fields[f]]; field; field = field->next) { raptor_uri *new_uri = NULL; if(field->value) new_uri = raptor_new_uri(rdf_parser->world, (const unsigned char*)field->value); else if(field->uri) new_uri = raptor_uri_copy(field->uri); if(!new_uri) return 1; item->term = raptor_new_term_from_uri(rdf_parser->world, new_uri); raptor_free_uri(new_uri); if(!item->term) return 1; break; } } if(!item->term) { const unsigned char *id; /* need to make bnode */ id = raptor_world_generate_bnodeid(rdf_parser->world); item->term = raptor_new_term_from_blank(rdf_parser->world, id); RAPTOR_FREE(char*, id); } } /* Try to add an rss:link if missing */ if(i == RAPTOR_RSS_CHANNEL && !item->fields[RAPTOR_RSS_FIELD_LINK]) { if(raptor_rss_insert_rss_link(rdf_parser, item)) return 1; } item->node_type = &raptor_rss_items_info[i]; item->node_typei = i; } } /* sequence of rss:item */ for(item = rss_parser->model.items; item; item = item->next) { raptor_rss_block *block; raptor_uri* uri; if(!item->fields[RAPTOR_RSS_FIELD_LINK]) { if(raptor_rss_insert_rss_link(rdf_parser, item)) return 1; } if(item->uri) { uri = raptor_uri_copy(item->uri); } else { if(item->fields[RAPTOR_RSS_FIELD_LINK]) { if(item->fields[RAPTOR_RSS_FIELD_LINK]->value) uri = raptor_new_uri(rdf_parser->world, (const unsigned char*)item->fields[RAPTOR_RSS_FIELD_LINK]->value); else if(item->fields[RAPTOR_RSS_FIELD_LINK]->uri) uri = raptor_uri_copy(item->fields[RAPTOR_RSS_FIELD_LINK]->uri); } else if(item->fields[RAPTOR_RSS_FIELD_ATOM_ID]) { if(item->fields[RAPTOR_RSS_FIELD_ATOM_ID]->value) uri = raptor_new_uri(rdf_parser->world, (const unsigned char*)item->fields[RAPTOR_RSS_FIELD_ATOM_ID]->value); else if(item->fields[RAPTOR_RSS_FIELD_ATOM_ID]->uri) uri = raptor_uri_copy(item->fields[RAPTOR_RSS_FIELD_ATOM_ID]->uri); } } item->term = raptor_new_term_from_uri(rdf_parser->world, uri); raptor_free_uri(uri); uri = NULL; for(block = item->blocks; block; block = block->next) { if(!block->identifier) { const unsigned char *id; /* need to make bnode */ id = raptor_world_generate_bnodeid(rdf_parser->world); item->term = raptor_new_term_from_blank(rdf_parser->world, id); RAPTOR_FREE(char*, id); } } item->node_type = &raptor_rss_items_info[RAPTOR_RSS_ITEM]; item->node_typei = RAPTOR_RSS_ITEM; } return 0; } static int raptor_rss_emit_type_triple(raptor_parser* rdf_parser, raptor_term *resource, raptor_uri *type_uri) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; raptor_term *predicate_term; raptor_term *object_term; if(!resource) { raptor_parser_error(rdf_parser, "RSS node has no identifier"); return 1; } rss_parser->statement.subject = resource; predicate_term = raptor_new_term_from_uri(rdf_parser->world, RAPTOR_RDF_type_URI(rdf_parser->world)); rss_parser->statement.predicate = predicate_term; object_term = raptor_new_term_from_uri(rdf_parser->world, type_uri); rss_parser->statement.object = object_term; /* Generate the statement */ (*rdf_parser->statement_handler)(rdf_parser->user_data, &rss_parser->statement); raptor_free_term(predicate_term); raptor_free_term(object_term); return 0; } static int raptor_rss_emit_block(raptor_parser* rdf_parser, raptor_term *resource, raptor_rss_block *block) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; raptor_rss_type block_type = block->rss_type; raptor_uri *predicate_uri; raptor_term *predicate_term = NULL; const raptor_rss_block_field_info *bfi; raptor_rss_fields_type predicate_field; if(!block->identifier) { raptor_parser_error(rdf_parser, "Block has no identifier"); return 1; } predicate_field = raptor_rss_items_info[block_type].predicate; predicate_uri = rdf_parser->world->rss_fields_info_uris[predicate_field]; predicate_term = raptor_new_term_from_uri(rdf_parser->world, predicate_uri); rss_parser->statement.subject = resource; rss_parser->statement.predicate = predicate_term; rss_parser->statement.object = block->identifier; (*rdf_parser->statement_handler)(rdf_parser->user_data, &rss_parser->statement); raptor_free_term(predicate_term); predicate_term = NULL; if(raptor_rss_emit_type_triple(rdf_parser, block->identifier, block->node_type)) return 1; for(bfi = &raptor_rss_block_fields_info[0]; bfi->type != RAPTOR_RSS_NONE; bfi++) { int attribute_type; int offset; if(bfi->type != block_type || !bfi->attribute) continue; attribute_type = bfi->attribute_type; offset = bfi->offset; predicate_uri = rdf_parser->world->rss_fields_info_uris[bfi->field]; predicate_term = raptor_new_term_from_uri(rdf_parser->world, predicate_uri); rss_parser->statement.predicate = predicate_term; if(attribute_type == RSS_BLOCK_FIELD_TYPE_URL) { raptor_uri *uri = block->urls[offset]; if(uri) { raptor_term* object_term; object_term = raptor_new_term_from_uri(rdf_parser->world, uri); rss_parser->statement.object = object_term; (*rdf_parser->statement_handler)(rdf_parser->user_data, &rss_parser->statement); raptor_free_term(object_term); } } else if(attribute_type == RSS_BLOCK_FIELD_TYPE_STRING) { const char *str = block->strings[offset]; if(str) { raptor_term* object_term; object_term = raptor_new_term_from_literal(rdf_parser->world, (const unsigned char*)str, NULL, NULL); rss_parser->statement.object = object_term; (*rdf_parser->statement_handler)(rdf_parser->user_data, &rss_parser->statement); raptor_free_term(object_term); } } else { #ifdef RAPTOR_DEBUG RAPTOR_FATAL2("Found unknown attribute_type %d\n", attribute_type); #endif } raptor_free_term(predicate_term); predicate_term = NULL; } return 0; } static int raptor_rss_emit_item(raptor_parser* rdf_parser, raptor_rss_item *item) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int f; raptor_rss_block *block; raptor_uri *type_uri; if(!item->fields_count) return 0; /* HACK - FIXME - set correct atom output class type */ if(item->node_typei == RAPTOR_ATOM_AUTHOR) type_uri = rdf_parser->world->rss_fields_info_uris[RAPTOR_RSS_RDF_ATOM_AUTHOR_CLASS]; else type_uri = rdf_parser->world->rss_types_info_uris[item->node_typei]; if(raptor_rss_emit_type_triple(rdf_parser, item->term, type_uri)) return 1; for(f = 0; f< RAPTOR_RSS_FIELDS_SIZE; f++) { raptor_rss_field* field; raptor_uri* predicate_uri = NULL; raptor_term* predicate_term = NULL; /* This is only made by a connection */ if(f == RAPTOR_RSS_FIELD_ITEMS) continue; /* skip predicates with no URI (no namespace e.g. RSS 2) */ predicate_uri = rdf_parser->world->rss_fields_info_uris[f]; if(!predicate_uri) continue; predicate_term = raptor_new_term_from_uri(rdf_parser->world, predicate_uri); if(!predicate_term) continue; rss_parser->statement.predicate = predicate_term; for(field = item->fields[f]; field; field = field->next) { raptor_term* object_term; if(field->value) { /* FIXME - should store and emit languages */ object_term = raptor_new_term_from_literal(rdf_parser->world, field->value, NULL, NULL); } else { object_term = raptor_new_term_from_uri(rdf_parser->world, field->uri); } rss_parser->statement.object = object_term; /* Generate the statement */ (*rdf_parser->statement_handler)(rdf_parser->user_data, &rss_parser->statement); raptor_free_term(object_term); } raptor_free_term(predicate_term); } for(block = item->blocks; block; block = block->next) { raptor_rss_emit_block(rdf_parser, item->term, block); } return 0; } static int raptor_rss_emit_connection(raptor_parser* rdf_parser, raptor_term *subject_identifier, raptor_uri* predicate_uri, int predicate_ordinal, raptor_term *object_identifier) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; raptor_uri *puri = NULL; raptor_term *predicate_term = NULL; if(!subject_identifier) { raptor_parser_error(rdf_parser, "Connection subject has no identifier"); return 1; } rss_parser->statement.subject = subject_identifier; if(!predicate_uri) { /* new URI object */ puri = raptor_new_uri_from_rdf_ordinal(rdf_parser->world, predicate_ordinal); predicate_uri = puri; } predicate_term = raptor_new_term_from_uri(rdf_parser->world, predicate_uri); rss_parser->statement.predicate = predicate_term; rss_parser->statement.object = object_identifier; /* Generate the statement */ (*rdf_parser->statement_handler)(rdf_parser->user_data, &rss_parser->statement); raptor_free_term(predicate_term); if(puri) raptor_free_uri(puri); return 0; } static int raptor_rss_emit(raptor_parser* rdf_parser) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int i; raptor_rss_item* item; int rc = 0; if(!rss_parser->model.common[RAPTOR_RSS_CHANNEL]) { raptor_parser_error(rdf_parser, "No RSS channel item present"); return 1; } if(!rss_parser->model.common[RAPTOR_RSS_CHANNEL]->term) { raptor_parser_error(rdf_parser, "RSS channel has no identifier"); return 1; } /* Emit start default graph mark */ raptor_parser_start_graph(rdf_parser, NULL, 0); rdf_parser->emitted_default_graph++; /* Emit all the common type blocks (channel, author, ...) */ for(i = 0; i< RAPTOR_RSS_COMMON_SIZE; i++) { for(item = rss_parser->model.common[i]; item; item = item->next) { if(!item->fields_count) continue; RAPTOR_DEBUG3("Emitting type %i - %s\n", i, raptor_rss_items_info[i].name); if(!item->term) { raptor_parser_error(rdf_parser, "RSS %s has no identifier", raptor_rss_items_info[i].name); rc = 1; goto tidy; } if(raptor_rss_emit_item(rdf_parser, item)) { rc = 1; goto tidy; } /* Add connections to channel */ if(i != RAPTOR_RSS_CHANNEL) { if(raptor_rss_emit_connection(rdf_parser, rss_parser->model.common[RAPTOR_RSS_CHANNEL]->term, rdf_parser->world->rss_types_info_uris[i], 0, item->term)) { rc = 1; goto tidy; } } } } /* Emit the feed item blocks */ if(rss_parser->model.items_count) { const unsigned char* id; raptor_term *items; id = raptor_world_generate_bnodeid(rdf_parser->world); /* make a new genid for the <rdf:Seq> node */ items = raptor_new_term_from_blank(rdf_parser->world, id); RAPTOR_FREE(char*, id); /* _:genid1 rdf:type rdf:Seq . */ if(raptor_rss_emit_type_triple(rdf_parser, items, RAPTOR_RDF_Seq_URI(rdf_parser->world))) { raptor_free_term(items); rc = 1; goto tidy; } /* <channelURI> rss:items _:genid1 . */ if(raptor_rss_emit_connection(rdf_parser, rss_parser->model.common[RAPTOR_RSS_CHANNEL]->term, rdf_parser->world->rss_fields_info_uris[RAPTOR_RSS_FIELD_ITEMS], 0, items)) { raptor_free_term(items); rc= 1; goto tidy; } /* sequence of rss:item */ for(i = 1, item = rss_parser->model.items; item; item = item->next, i++) { if(raptor_rss_emit_item(rdf_parser, item) || raptor_rss_emit_connection(rdf_parser, items, NULL, i,item->term)) { raptor_free_term(items); rc = 1; goto tidy; } } raptor_free_term(items); } tidy: if(rdf_parser->emitted_default_graph) { raptor_parser_end_graph(rdf_parser, NULL, 0); rdf_parser->emitted_default_graph--; } return rc; } static int raptor_rss_copy_field(raptor_rss_parser* rss_parser, raptor_rss_item* item, const raptor_field_pair* pair) { raptor_rss_fields_type from_field = pair->from; raptor_rss_fields_type to_field = pair->to; raptor_rss_field* field = NULL; if(!(item->fields[from_field] && item->fields[from_field]->value)) return 1; if(from_field == to_field) { field = item->fields[from_field]; } else { if(item->fields[to_field] && item->fields[to_field]->value) return 1; field = raptor_rss_new_field(item->world); field->is_mapped = 1; raptor_rss_item_add_field(item, to_field, field); } /* Ensure output namespace is declared */ rss_parser->nspaces_seen[raptor_rss_fields_info[to_field].nspace] = 'Y'; if(!field->value) { if(pair->conversion) pair->conversion(item->fields[from_field], field); else { size_t len; /* Otherwise default action is to copy from_field value */ len = strlen((const char*)item->fields[from_field]->value); field->value = RAPTOR_MALLOC(unsigned char*, len + 1); if(!field->value) return 1; memcpy(field->value, item->fields[from_field]->value, len + 1); } } return 0; } static void raptor_rss_uplift_fields(raptor_rss_parser* rss_parser, raptor_rss_item* item) { int i; /* COPY some fields from atom to rss/dc */ for(i = 0; raptor_atom_to_rss[i].from != RAPTOR_RSS_FIELD_UNKNOWN; i++) { #ifdef RAPTOR_DEBUG raptor_rss_fields_type from_field = raptor_atom_to_rss[i].from; raptor_rss_fields_type to_field = raptor_atom_to_rss[i].to; #endif if(raptor_rss_copy_field(rss_parser, item, &raptor_atom_to_rss[i])) continue; RAPTOR_DEBUG3("Copied field %s to rss field %s\n", raptor_rss_fields_info[from_field].name, raptor_rss_fields_info[to_field].name); } } static void raptor_rss_uplift_items(raptor_parser* rdf_parser) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int i; raptor_rss_item* item; for(i = 0; i< RAPTOR_RSS_COMMON_SIZE; i++) { for(item = rss_parser->model.common[i]; item; item = item->next) { raptor_rss_uplift_fields(rss_parser, item); } } for(item = rss_parser->model.items; item; item = item->next) { raptor_rss_uplift_fields(rss_parser, item); } } static void raptor_rss_start_namespaces(raptor_parser* rdf_parser) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; int i; int n; /* for each item type (channel, item, ...) */ for(i = 0; i< RAPTOR_RSS_COMMON_SIZE; i++) { raptor_rss_item* item; /* for each item instance of a type */ for(item = rss_parser->model.common[i]; item; item = item->next) { int f; if(!item->fields_count) continue; /* for each field */ for(f = 0; f< RAPTOR_RSS_FIELDS_SIZE; f++) { raptor_rss_field* field; /* for each field value */ for(field = item->fields[f]; field; field = field->next) { rss_info_namespace ns_index = raptor_rss_fields_info[f].nspace; rss_parser->nspaces_seen[ns_index] = 'Y'; /* knowing there is one value is enough */ break; } } } } /* start the namespaces */ for(n = 0; n < RAPTOR_RSS_NAMESPACES_SIZE; n++) { if(rss_parser->nspaces[n] && rss_parser->nspaces_seen[n] == 'Y') raptor_parser_start_namespace(rdf_parser, rss_parser->nspaces[n]); } } static int raptor_rss_parse_chunk(raptor_parser* rdf_parser, const unsigned char *s, size_t len, int is_end) { raptor_rss_parser* rss_parser = (raptor_rss_parser*)rdf_parser->context; if(rdf_parser->failed) return 1; raptor_sax2_parse_chunk(rss_parser->sax2, s, len, is_end); if(!is_end) return 0; if(rdf_parser->failed) return 1; /* turn strings into URIs, move things around if needed */ if(raptor_rss_insert_identifiers(rdf_parser)) { rdf_parser->failed = 1; return 1; } /* add some new fields */ raptor_rss_uplift_items(rdf_parser); /* find out what namespaces to declare and start them */ raptor_rss_start_namespaces(rdf_parser); /* generate the triples */ raptor_rss_emit(rdf_parser); return 0; } static int raptor_rss_parse_recognise_syntax(raptor_parser_factory* factory, const unsigned char *buffer, size_t len, const unsigned char *identifier, const unsigned char *suffix, const char *mime_type) { int score = 0; if(suffix) { if(!strcmp((const char*)suffix, "rss")) score = 7; if(!strcmp((const char*)suffix, "atom")) score = 5; if(!strcmp((const char*)suffix, "xml")) score = 4; } if(identifier) { if(!strncmp((const char*)identifier, "http://feed", 11)) score += 5; else if(strstr((const char*)identifier, "feed")) score += 3; if(strstr((const char*)identifier, "rss2")) score += 5; else if(!suffix && strstr((const char*)identifier, "rss")) score += 4; else if(!suffix && strstr((const char*)identifier, "atom")) score += 4; else if(strstr((const char*)identifier, "rss.xml")) score += 4; else if(strstr((const char*)identifier, "atom.xml")) score += 4; } if(mime_type) { if(!strstr((const char*)mime_type, "html")) { if(strstr((const char*)mime_type, "rss")) score += 4; else if(strstr((const char*)mime_type, "xml")) score += 4; else if(strstr((const char*)mime_type, "atom")) score += 4; } } return score; } static const char* const rss_tag_soup_names[2] = { "rss-tag-soup", NULL }; #define RSS_TAG_SOUP_TYPES_COUNT 6 static const raptor_type_q rss_tag_soup_types[RSS_TAG_SOUP_TYPES_COUNT + 1] = { { "application/rss", 15, 8}, { "application/rss+xml", 19, 8}, { "text/rss", 8, 8}, { "application/xml", 15, 3}, { "text/xml", 8, 3}, { "application/atom+xml", 20, 3}, { NULL, 0, 0} }; static int raptor_rss_parser_register_factory(raptor_parser_factory *factory) { int rc = 0; factory->desc.names = rss_tag_soup_names; factory->desc.mime_types = rss_tag_soup_types; factory->desc.label = "RSS Tag Soup"; factory->desc.uri_strings = NULL; factory->desc.flags = RAPTOR_SYNTAX_NEED_BASE_URI; factory->context_length = sizeof(raptor_rss_parser); factory->init = raptor_rss_parse_init; factory->terminate = raptor_rss_parse_terminate; factory->start = raptor_rss_parse_start; factory->chunk = raptor_rss_parse_chunk; factory->recognise_syntax = raptor_rss_parse_recognise_syntax; return rc; } int raptor_init_parser_rss(raptor_world* world) { return !raptor_world_register_parser_factory(world, &raptor_rss_parser_register_factory); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3568_9
crossvul-cpp_data_good_1841_0
/* * SWIOTLB-based DMA API implementation * * Copyright (C) 2012 ARM Ltd. * Author: Catalin Marinas <catalin.marinas@arm.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/gfp.h> #include <linux/export.h> #include <linux/slab.h> #include <linux/genalloc.h> #include <linux/dma-mapping.h> #include <linux/dma-contiguous.h> #include <linux/vmalloc.h> #include <linux/swiotlb.h> #include <asm/cacheflush.h> struct dma_map_ops *dma_ops; EXPORT_SYMBOL(dma_ops); static pgprot_t __get_dma_pgprot(struct dma_attrs *attrs, pgprot_t prot, bool coherent) { if (!coherent || dma_get_attr(DMA_ATTR_WRITE_COMBINE, attrs)) return pgprot_writecombine(prot); return prot; } static struct gen_pool *atomic_pool; #define DEFAULT_DMA_COHERENT_POOL_SIZE SZ_256K static size_t atomic_pool_size = DEFAULT_DMA_COHERENT_POOL_SIZE; static int __init early_coherent_pool(char *p) { atomic_pool_size = memparse(p, &p); return 0; } early_param("coherent_pool", early_coherent_pool); static void *__alloc_from_pool(size_t size, struct page **ret_page, gfp_t flags) { unsigned long val; void *ptr = NULL; if (!atomic_pool) { WARN(1, "coherent pool not initialised!\n"); return NULL; } val = gen_pool_alloc(atomic_pool, size); if (val) { phys_addr_t phys = gen_pool_virt_to_phys(atomic_pool, val); *ret_page = phys_to_page(phys); ptr = (void *)val; memset(ptr, 0, size); } return ptr; } static bool __in_atomic_pool(void *start, size_t size) { return addr_in_gen_pool(atomic_pool, (unsigned long)start, size); } static int __free_from_pool(void *start, size_t size) { if (!__in_atomic_pool(start, size)) return 0; gen_pool_free(atomic_pool, (unsigned long)start, size); return 1; } static void *__dma_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flags, struct dma_attrs *attrs) { if (dev == NULL) { WARN_ONCE(1, "Use an actual device structure for DMA allocation\n"); return NULL; } if (IS_ENABLED(CONFIG_ZONE_DMA) && dev->coherent_dma_mask <= DMA_BIT_MASK(32)) flags |= GFP_DMA; if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) { struct page *page; void *addr; size = PAGE_ALIGN(size); page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT, get_order(size)); if (!page) return NULL; *dma_handle = phys_to_dma(dev, page_to_phys(page)); addr = page_address(page); memset(addr, 0, size); return addr; } else { return swiotlb_alloc_coherent(dev, size, dma_handle, flags); } } static void __dma_free_coherent(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle, struct dma_attrs *attrs) { bool freed; phys_addr_t paddr = dma_to_phys(dev, dma_handle); if (dev == NULL) { WARN_ONCE(1, "Use an actual device structure for DMA allocation\n"); return; } freed = dma_release_from_contiguous(dev, phys_to_page(paddr), size >> PAGE_SHIFT); if (!freed) swiotlb_free_coherent(dev, size, vaddr, dma_handle); } static void *__dma_alloc(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flags, struct dma_attrs *attrs) { struct page *page; void *ptr, *coherent_ptr; bool coherent = is_device_dma_coherent(dev); size = PAGE_ALIGN(size); if (!coherent && !(flags & __GFP_WAIT)) { struct page *page = NULL; void *addr = __alloc_from_pool(size, &page, flags); if (addr) *dma_handle = phys_to_dma(dev, page_to_phys(page)); return addr; } ptr = __dma_alloc_coherent(dev, size, dma_handle, flags, attrs); if (!ptr) goto no_mem; /* no need for non-cacheable mapping if coherent */ if (coherent) return ptr; /* remove any dirty cache lines on the kernel alias */ __dma_flush_range(ptr, ptr + size); /* create a coherent mapping */ page = virt_to_page(ptr); coherent_ptr = dma_common_contiguous_remap(page, size, VM_USERMAP, __get_dma_pgprot(attrs, __pgprot(PROT_NORMAL_NC), false), NULL); if (!coherent_ptr) goto no_map; return coherent_ptr; no_map: __dma_free_coherent(dev, size, ptr, *dma_handle, attrs); no_mem: *dma_handle = DMA_ERROR_CODE; return NULL; } static void __dma_free(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle, struct dma_attrs *attrs) { void *swiotlb_addr = phys_to_virt(dma_to_phys(dev, dma_handle)); if (!is_device_dma_coherent(dev)) { if (__free_from_pool(vaddr, size)) return; vunmap(vaddr); } __dma_free_coherent(dev, size, swiotlb_addr, dma_handle, attrs); } static dma_addr_t __swiotlb_map_page(struct device *dev, struct page *page, unsigned long offset, size_t size, enum dma_data_direction dir, struct dma_attrs *attrs) { dma_addr_t dev_addr; dev_addr = swiotlb_map_page(dev, page, offset, size, dir, attrs); if (!is_device_dma_coherent(dev)) __dma_map_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); return dev_addr; } static void __swiotlb_unmap_page(struct device *dev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir, struct dma_attrs *attrs) { if (!is_device_dma_coherent(dev)) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); swiotlb_unmap_page(dev, dev_addr, size, dir, attrs); } static int __swiotlb_map_sg_attrs(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir, struct dma_attrs *attrs) { struct scatterlist *sg; int i, ret; ret = swiotlb_map_sg_attrs(dev, sgl, nelems, dir, attrs); if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, ret, i) __dma_map_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); return ret; } static void __swiotlb_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir, struct dma_attrs *attrs) { struct scatterlist *sg; int i; if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, nelems, i) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); swiotlb_unmap_sg_attrs(dev, sgl, nelems, dir, attrs); } static void __swiotlb_sync_single_for_cpu(struct device *dev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir) { if (!is_device_dma_coherent(dev)) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); swiotlb_sync_single_for_cpu(dev, dev_addr, size, dir); } static void __swiotlb_sync_single_for_device(struct device *dev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir) { swiotlb_sync_single_for_device(dev, dev_addr, size, dir); if (!is_device_dma_coherent(dev)) __dma_map_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); } static void __swiotlb_sync_sg_for_cpu(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir) { struct scatterlist *sg; int i; if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, nelems, i) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); swiotlb_sync_sg_for_cpu(dev, sgl, nelems, dir); } static void __swiotlb_sync_sg_for_device(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir) { struct scatterlist *sg; int i; swiotlb_sync_sg_for_device(dev, sgl, nelems, dir); if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, nelems, i) __dma_map_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); } /* vma->vm_page_prot must be set appropriately before calling this function */ static int __dma_common_mmap(struct device *dev, struct vm_area_struct *vma, void *cpu_addr, dma_addr_t dma_addr, size_t size) { int ret = -ENXIO; unsigned long nr_vma_pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT; unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT; unsigned long pfn = dma_to_phys(dev, dma_addr) >> PAGE_SHIFT; unsigned long off = vma->vm_pgoff; if (dma_mmap_from_coherent(dev, vma, cpu_addr, size, &ret)) return ret; if (off < nr_pages && nr_vma_pages <= (nr_pages - off)) { ret = remap_pfn_range(vma, vma->vm_start, pfn + off, vma->vm_end - vma->vm_start, vma->vm_page_prot); } return ret; } static int __swiotlb_mmap(struct device *dev, struct vm_area_struct *vma, void *cpu_addr, dma_addr_t dma_addr, size_t size, struct dma_attrs *attrs) { vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot, is_device_dma_coherent(dev)); return __dma_common_mmap(dev, vma, cpu_addr, dma_addr, size); } static struct dma_map_ops swiotlb_dma_ops = { .alloc = __dma_alloc, .free = __dma_free, .mmap = __swiotlb_mmap, .map_page = __swiotlb_map_page, .unmap_page = __swiotlb_unmap_page, .map_sg = __swiotlb_map_sg_attrs, .unmap_sg = __swiotlb_unmap_sg_attrs, .sync_single_for_cpu = __swiotlb_sync_single_for_cpu, .sync_single_for_device = __swiotlb_sync_single_for_device, .sync_sg_for_cpu = __swiotlb_sync_sg_for_cpu, .sync_sg_for_device = __swiotlb_sync_sg_for_device, .dma_supported = swiotlb_dma_supported, .mapping_error = swiotlb_dma_mapping_error, }; static int __init atomic_pool_init(void) { pgprot_t prot = __pgprot(PROT_NORMAL_NC); unsigned long nr_pages = atomic_pool_size >> PAGE_SHIFT; struct page *page; void *addr; unsigned int pool_size_order = get_order(atomic_pool_size); if (dev_get_cma_area(NULL)) page = dma_alloc_from_contiguous(NULL, nr_pages, pool_size_order); else page = alloc_pages(GFP_DMA, pool_size_order); if (page) { int ret; void *page_addr = page_address(page); memset(page_addr, 0, atomic_pool_size); __dma_flush_range(page_addr, page_addr + atomic_pool_size); atomic_pool = gen_pool_create(PAGE_SHIFT, -1); if (!atomic_pool) goto free_page; addr = dma_common_contiguous_remap(page, atomic_pool_size, VM_USERMAP, prot, atomic_pool_init); if (!addr) goto destroy_genpool; ret = gen_pool_add_virt(atomic_pool, (unsigned long)addr, page_to_phys(page), atomic_pool_size, -1); if (ret) goto remove_mapping; gen_pool_set_algo(atomic_pool, gen_pool_first_fit_order_align, (void *)PAGE_SHIFT); pr_info("DMA: preallocated %zu KiB pool for atomic allocations\n", atomic_pool_size / 1024); return 0; } goto out; remove_mapping: dma_common_free_remap(addr, atomic_pool_size, VM_USERMAP); destroy_genpool: gen_pool_destroy(atomic_pool); atomic_pool = NULL; free_page: if (!dma_release_from_contiguous(NULL, page, nr_pages)) __free_pages(page, pool_size_order); out: pr_err("DMA: failed to allocate %zu KiB pool for atomic coherent allocation\n", atomic_pool_size / 1024); return -ENOMEM; } static int __init arm64_dma_init(void) { int ret; dma_ops = &swiotlb_dma_ops; ret = atomic_pool_init(); return ret; } arch_initcall(arm64_dma_init); #define PREALLOC_DMA_DEBUG_ENTRIES 4096 static int __init dma_debug_do_init(void) { dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES); return 0; } fs_initcall(dma_debug_do_init);
./CrossVul/dataset_final_sorted/CWE-200/c/good_1841_0
crossvul-cpp_data_good_759_1
/* * IPv6 output functions * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * * Based on linux/net/ipv4/ip_output.c * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * A.N.Kuznetsov : airthmetics in fragmentation. * extension headers are implemented. * route changes now work. * ip6_forward does not confuse sniffers. * etc. * * H. von Brand : Added missing #include <linux/string.h> * Imran Patel : frag id should be in NBO * Kazunori MIYAZAWA @USAGI * : add ip6_append_data and related functions * for datagram xmit */ #include <linux/errno.h> #include <linux/kernel.h> #include <linux/string.h> #include <linux/socket.h> #include <linux/net.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/in6.h> #include <linux/tcp.h> #include <linux/route.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv6.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/ndisc.h> #include <net/protocol.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/rawv6.h> #include <net/icmp.h> #include <net/xfrm.h> #include <net/checksum.h> #include <linux/mroute6.h> static int ip6_finish_output2(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct net_device *dev = dst->dev; struct neighbour *neigh; struct in6_addr *nexthop; int ret; skb->protocol = htons(ETH_P_IPV6); skb->dev = dev; if (ipv6_addr_is_multicast(&ipv6_hdr(skb)->daddr)) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (!(dev->flags & IFF_LOOPBACK) && sk_mc_loop(skb->sk) && ((mroute6_socket(dev_net(dev), skb) && !(IP6CB(skb)->flags & IP6SKB_FORWARDED)) || ipv6_chk_mcast_addr(dev, &ipv6_hdr(skb)->daddr, &ipv6_hdr(skb)->saddr))) { struct sk_buff *newskb = skb_clone(skb, GFP_ATOMIC); /* Do not check for IFF_ALLMULTI; multicast routing is not supported in any case. */ if (newskb) NF_HOOK(NFPROTO_IPV6, NF_INET_POST_ROUTING, newskb, NULL, newskb->dev, dev_loopback_xmit); if (ipv6_hdr(skb)->hop_limit == 0) { IP6_INC_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } } IP6_UPD_PO_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTMCAST, skb->len); if (IPV6_ADDR_MC_SCOPE(&ipv6_hdr(skb)->daddr) <= IPV6_ADDR_SCOPE_NODELOCAL && !(dev->flags & IFF_LOOPBACK)) { kfree_skb(skb); return 0; } } rcu_read_lock_bh(); nexthop = rt6_nexthop((struct rt6_info *)dst); neigh = __ipv6_neigh_lookup_noref(dst->dev, nexthop); if (unlikely(!neigh)) neigh = __neigh_create(&nd_tbl, nexthop, dst->dev, false); if (!IS_ERR(neigh)) { ret = dst_neigh_output(dst, neigh, skb); rcu_read_unlock_bh(); return ret; } rcu_read_unlock_bh(); IP6_INC_STATS(dev_net(dst->dev), ip6_dst_idev(dst), IPSTATS_MIB_OUTNOROUTES); kfree_skb(skb); return -EINVAL; } static int ip6_finish_output(struct sk_buff *skb) { if ((skb->len > ip6_skb_dst_mtu(skb) && !skb_is_gso(skb)) || dst_allfrag(skb_dst(skb)) || (IP6CB(skb)->frag_max_size && skb->len > IP6CB(skb)->frag_max_size)) return ip6_fragment(skb, ip6_finish_output2); else return ip6_finish_output2(skb); } int ip6_output(struct sock *sk, struct sk_buff *skb) { struct net_device *dev = skb_dst(skb)->dev; struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); if (unlikely(idev->cnf.disable_ipv6)) { IP6_INC_STATS(dev_net(dev), idev, IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return 0; } return NF_HOOK_COND(NFPROTO_IPV6, NF_INET_POST_ROUTING, skb, NULL, dev, ip6_finish_output, !(IP6CB(skb)->flags & IP6SKB_REROUTED)); } /* * xmit an sk_buff (used by TCP, SCTP and DCCP) */ int ip6_xmit(struct sock *sk, struct sk_buff *skb, struct flowi6 *fl6, struct ipv6_txoptions *opt, int tclass) { struct net *net = sock_net(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct in6_addr *first_hop = &fl6->daddr; struct dst_entry *dst = skb_dst(skb); unsigned int head_room; struct ipv6hdr *hdr; u8 proto = fl6->flowi6_proto; int seg_len = skb->len; int hlimit = -1; u32 mtu; head_room = sizeof(struct ipv6hdr) + LL_RESERVED_SPACE(dst->dev); if (opt) head_room += opt->opt_nflen + opt->opt_flen; if (unlikely(skb_headroom(skb) < head_room)) { struct sk_buff *skb2 = skb_realloc_headroom(skb, head_room); if (!skb2) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); return -ENOBUFS; } if (skb->sk) skb_set_owner_w(skb2, skb->sk); consume_skb(skb); skb = skb2; } if (opt) { seg_len += opt->opt_nflen + opt->opt_flen; if (opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &first_hop); } skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); /* * Fill in the IPv6 header */ if (np) hlimit = np->hop_limit; if (hlimit < 0) hlimit = ip6_dst_hoplimit(dst); ip6_flow_hdr(hdr, tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel)); hdr->payload_len = htons(seg_len); hdr->nexthdr = proto; hdr->hop_limit = hlimit; hdr->saddr = fl6->saddr; hdr->daddr = *first_hop; skb->protocol = htons(ETH_P_IPV6); skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; mtu = dst_mtu(dst); if ((skb->len <= mtu) || skb->ignore_df || skb_is_gso(skb)) { IP6_UPD_PO_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUT, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_LOCAL_OUT, skb, NULL, dst->dev, dst_output); } skb->dev = dst->dev; ipv6_local_error(sk, EMSGSIZE, fl6, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } EXPORT_SYMBOL(ip6_xmit); static int ip6_call_ra_chain(struct sk_buff *skb, int sel) { struct ip6_ra_chain *ra; struct sock *last = NULL; read_lock(&ip6_ra_lock); for (ra = ip6_ra_chain; ra; ra = ra->next) { struct sock *sk = ra->sk; if (sk && ra->sel == sel && (!sk->sk_bound_dev_if || sk->sk_bound_dev_if == skb->dev->ifindex)) { if (last) { struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC); if (skb2) rawv6_rcv(last, skb2); } last = sk; } } if (last) { rawv6_rcv(last, skb); read_unlock(&ip6_ra_lock); return 1; } read_unlock(&ip6_ra_lock); return 0; } static int ip6_forward_proxy_check(struct sk_buff *skb) { struct ipv6hdr *hdr = ipv6_hdr(skb); u8 nexthdr = hdr->nexthdr; __be16 frag_off; int offset; if (ipv6_ext_hdr(nexthdr)) { offset = ipv6_skip_exthdr(skb, sizeof(*hdr), &nexthdr, &frag_off); if (offset < 0) return 0; } else offset = sizeof(struct ipv6hdr); if (nexthdr == IPPROTO_ICMPV6) { struct icmp6hdr *icmp6; if (!pskb_may_pull(skb, (skb_network_header(skb) + offset + 1 - skb->data))) return 0; icmp6 = (struct icmp6hdr *)(skb_network_header(skb) + offset); switch (icmp6->icmp6_type) { case NDISC_ROUTER_SOLICITATION: case NDISC_ROUTER_ADVERTISEMENT: case NDISC_NEIGHBOUR_SOLICITATION: case NDISC_NEIGHBOUR_ADVERTISEMENT: case NDISC_REDIRECT: /* For reaction involving unicast neighbor discovery * message destined to the proxied address, pass it to * input function. */ return 1; default: break; } } /* * The proxying router can't forward traffic sent to a link-local * address, so signal the sender and discard the packet. This * behavior is clarified by the MIPv6 specification. */ if (ipv6_addr_type(&hdr->daddr) & IPV6_ADDR_LINKLOCAL) { dst_link_failure(skb); return -1; } return 0; } static inline int ip6_forward_finish(struct sk_buff *skb) { return dst_output(skb); } static unsigned int ip6_dst_mtu_forward(const struct dst_entry *dst) { unsigned int mtu; struct inet6_dev *idev; if (dst_metric_locked(dst, RTAX_MTU)) { mtu = dst_metric_raw(dst, RTAX_MTU); if (mtu) return mtu; } mtu = IPV6_MIN_MTU; rcu_read_lock(); idev = __in6_dev_get(dst->dev); if (idev) mtu = idev->cnf.mtu6; rcu_read_unlock(); return mtu; } static bool ip6_pkt_too_big(const struct sk_buff *skb, unsigned int mtu) { if (skb->len <= mtu) return false; /* ipv6 conntrack defrag sets max_frag_size + ignore_df */ if (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu) return true; if (skb->ignore_df) return false; if (skb_is_gso(skb) && skb_gso_network_seglen(skb) <= mtu) return false; return true; } int ip6_forward(struct sk_buff *skb) { struct dst_entry *dst = skb_dst(skb); struct ipv6hdr *hdr = ipv6_hdr(skb); struct inet6_skb_parm *opt = IP6CB(skb); struct net *net = dev_net(dst->dev); u32 mtu; if (net->ipv6.devconf_all->forwarding == 0) goto error; if (skb->pkt_type != PACKET_HOST) goto drop; if (unlikely(skb->sk)) goto drop; if (skb_warn_if_lro(skb)) goto drop; if (!xfrm6_policy_check(NULL, XFRM_POLICY_FWD, skb)) { IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } skb_forward_csum(skb); /* * We DO NOT make any processing on * RA packets, pushing them to user level AS IS * without ane WARRANTY that application will be able * to interpret them. The reason is that we * cannot make anything clever here. * * We are not end-node, so that if packet contains * AH/ESP, we cannot make anything. * Defragmentation also would be mistake, RA packets * cannot be fragmented, because there is no warranty * that different fragments will go along one path. --ANK */ if (unlikely(opt->flags & IP6SKB_ROUTERALERT)) { if (ip6_call_ra_chain(skb, ntohs(opt->ra))) return 0; } /* * check and decrement ttl */ if (hdr->hop_limit <= 1) { /* Force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_TIME_EXCEED, ICMPV6_EXC_HOPLIMIT, 0); IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INHDRERRORS); kfree_skb(skb); return -ETIMEDOUT; } /* XXX: idev->cnf.proxy_ndp? */ if (net->ipv6.devconf_all->proxy_ndp && pneigh_lookup(&nd_tbl, net, &hdr->daddr, skb->dev, 0)) { int proxied = ip6_forward_proxy_check(skb); if (proxied > 0) return ip6_input(skb); else if (proxied < 0) { IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } } if (!xfrm6_route_forward(skb)) { IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INDISCARDS); goto drop; } dst = skb_dst(skb); /* IPv6 specs say nothing about it, but it is clear that we cannot send redirects to source routed frames. We don't send redirects to frames decapsulated from IPsec. */ if (skb->dev == dst->dev && opt->srcrt == 0 && !skb_sec_path(skb)) { struct in6_addr *target = NULL; struct inet_peer *peer; struct rt6_info *rt; /* * incoming and outgoing devices are the same * send a redirect. */ rt = (struct rt6_info *) dst; if (rt->rt6i_flags & RTF_GATEWAY) target = &rt->rt6i_gateway; else target = &hdr->daddr; peer = inet_getpeer_v6(net->ipv6.peers, &rt->rt6i_dst.addr, 1); /* Limit redirects both by destination (here) and by source (inside ndisc_send_redirect) */ if (inet_peer_xrlim_allow(peer, 1*HZ)) ndisc_send_redirect(skb, target); if (peer) inet_putpeer(peer); } else { int addrtype = ipv6_addr_type(&hdr->saddr); /* This check is security critical. */ if (addrtype == IPV6_ADDR_ANY || addrtype & (IPV6_ADDR_MULTICAST | IPV6_ADDR_LOOPBACK)) goto error; if (addrtype & IPV6_ADDR_LINKLOCAL) { icmpv6_send(skb, ICMPV6_DEST_UNREACH, ICMPV6_NOT_NEIGHBOUR, 0); goto error; } } mtu = ip6_dst_mtu_forward(dst); if (mtu < IPV6_MIN_MTU) mtu = IPV6_MIN_MTU; if (ip6_pkt_too_big(skb, mtu)) { /* Again, force OUTPUT device used as source address */ skb->dev = dst->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INTOOBIGERRORS); IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (skb_cow(skb, dst->dev->hard_header_len)) { IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTDISCARDS); goto drop; } hdr = ipv6_hdr(skb); /* Mangling hops number delayed to point after skb COW */ hdr->hop_limit--; IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTFORWDATAGRAMS); IP6_ADD_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_OUTOCTETS, skb->len); return NF_HOOK(NFPROTO_IPV6, NF_INET_FORWARD, skb, skb->dev, dst->dev, ip6_forward_finish); error: IP6_INC_STATS_BH(net, ip6_dst_idev(dst), IPSTATS_MIB_INADDRERRORS); drop: kfree_skb(skb); return -EINVAL; } 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; skb_copy_hash(to, from); #ifdef CONFIG_NET_SCHED to->tc_index = from->tc_index; #endif nf_copy(to, from); skb_copy_secmark(to, from); } static void ipv6_select_ident(struct frag_hdr *fhdr, struct rt6_info *rt) { static u32 ip6_idents_hashrnd __read_mostly; static u32 ip6_idents_hashrnd_extra __read_mostly; u32 hash, id; net_get_random_once(&ip6_idents_hashrnd, sizeof(ip6_idents_hashrnd)); net_get_random_once(&ip6_idents_hashrnd_extra, sizeof(ip6_idents_hashrnd_extra)); hash = __ipv6_addr_jhash(&rt->rt6i_dst.addr, ip6_idents_hashrnd); hash = __ipv6_addr_jhash(&rt->rt6i_src.addr, hash); hash = jhash_1word(hash, ip6_idents_hashrnd_extra); id = ip_idents_reserve(hash, 1); fhdr->identification = htonl(id); } int ip6_fragment(struct sk_buff *skb, int (*output)(struct sk_buff *)) { struct sk_buff *frag; struct rt6_info *rt = (struct rt6_info *)skb_dst(skb); struct ipv6_pinfo *np = skb->sk && !dev_recursion_level() ? inet6_sk(skb->sk) : NULL; struct ipv6hdr *tmp_hdr; struct frag_hdr *fh; unsigned int mtu, hlen, left, len; int hroom, troom; __be32 frag_id = 0; int ptr, offset = 0, err = 0; u8 *prevhdr, nexthdr = 0; struct net *net = dev_net(skb_dst(skb)->dev); err = ip6_find_1stfragopt(skb, &prevhdr); if (err < 0) goto fail; hlen = err; nexthdr = *prevhdr; mtu = ip6_skb_dst_mtu(skb); /* We must not fragment if the socket is set to force MTU discovery * or if the skb it not generated by a local socket. */ if (unlikely(!skb->ignore_df && skb->len > mtu) || (IP6CB(skb)->frag_max_size && IP6CB(skb)->frag_max_size > mtu)) { if (skb->sk && dst_allfrag(skb_dst(skb))) sk_nocaps_add(skb->sk, NETIF_F_GSO_MASK); skb->dev = skb_dst(skb)->dev; icmpv6_send(skb, ICMPV6_PKT_TOOBIG, 0, mtu); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return -EMSGSIZE; } if (np && np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } mtu -= hlen + sizeof(struct frag_hdr); if (skb_has_frag_list(skb)) { int first_len = skb_pagelen(skb); struct sk_buff *frag2; if (first_len - hlen > mtu || ((first_len - hlen) & 7) || skb_cloned(skb)) goto slow_path; skb_walk_frags(skb, frag) { /* Correct geometry. */ if (frag->len > mtu || ((frag->len & 7) && frag->next) || skb_headroom(frag) < hlen) goto slow_path_clean; /* Partially cloned skb? */ if (skb_shared(frag)) goto slow_path_clean; BUG_ON(frag->sk); if (skb->sk) { frag->sk = skb->sk; frag->destructor = sock_wfree; } skb->truesize -= frag->truesize; } err = 0; offset = 0; frag = skb_shinfo(skb)->frag_list; skb_frag_list_init(skb); /* BUILD HEADER */ *prevhdr = NEXTHDR_FRAGMENT; tmp_hdr = kmemdup(skb_network_header(skb), hlen, GFP_ATOMIC); if (!tmp_hdr) { IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); return -ENOMEM; } __skb_pull(skb, hlen); fh = (struct frag_hdr *)__skb_push(skb, sizeof(struct frag_hdr)); __skb_push(skb, hlen); skb_reset_network_header(skb); memcpy(skb_network_header(skb), tmp_hdr, hlen); ipv6_select_ident(fh, rt); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(IP6_MF); frag_id = fh->identification; first_len = skb_pagelen(skb); skb->data_len = first_len - skb_headlen(skb); skb->len = first_len; ipv6_hdr(skb)->payload_len = htons(first_len - sizeof(struct ipv6hdr)); dst_hold(&rt->dst); for (;;) { /* Prepare header of the next frame, * before previous one went down. */ if (frag) { frag->ip_summed = CHECKSUM_NONE; skb_reset_transport_header(frag); fh = (struct frag_hdr *)__skb_push(frag, sizeof(struct frag_hdr)); __skb_push(frag, hlen); skb_reset_network_header(frag); memcpy(skb_network_header(frag), tmp_hdr, hlen); offset += skb->len - hlen - sizeof(struct frag_hdr); fh->nexthdr = nexthdr; fh->reserved = 0; fh->frag_off = htons(offset); if (frag->next != NULL) fh->frag_off |= htons(IP6_MF); fh->identification = frag_id; ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ip6_copy_metadata(frag, skb); } err = output(skb); if (!err) IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGCREATES); if (err || !frag) break; skb = frag; frag = skb->next; skb->next = NULL; } kfree(tmp_hdr); if (err == 0) { IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGOKS); ip6_rt_put(rt); return 0; } kfree_skb_list(frag); IP6_INC_STATS(net, ip6_dst_idev(&rt->dst), IPSTATS_MIB_FRAGFAILS); ip6_rt_put(rt); return err; slow_path_clean: skb_walk_frags(skb, frag2) { if (frag2 == frag) break; frag2->sk = NULL; frag2->destructor = NULL; skb->truesize += frag2->truesize; } } slow_path: if ((skb->ip_summed == CHECKSUM_PARTIAL) && skb_checksum_help(skb)) goto fail; left = skb->len - hlen; /* Space per frame */ ptr = hlen; /* Where to start from */ /* * Fragment the datagram. */ *prevhdr = NEXTHDR_FRAGMENT; hroom = LL_RESERVED_SPACE(rt->dst.dev); troom = rt->dst.dev->needed_tailroom; /* * Keep copying data until we run out. */ while (left > 0) { len = left; /* IF: it doesn't fit, use 'mtu' - the data space left */ if (len > mtu) len = mtu; /* IF: we are not sending up to and including the packet end then align the next start on an eight byte boundary */ if (len < left) { len &= ~7; } /* * Allocate buffer. */ if ((frag = alloc_skb(len + hlen + sizeof(struct frag_hdr) + hroom + troom, GFP_ATOMIC)) == NULL) { NETDEBUG(KERN_INFO "IPv6: frag: no memory for new fragment!\n"); IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); err = -ENOMEM; goto fail; } /* * Set up data on packet */ ip6_copy_metadata(frag, skb); skb_reserve(frag, hroom); skb_put(frag, len + hlen + sizeof(struct frag_hdr)); skb_reset_network_header(frag); fh = (struct frag_hdr *)(skb_network_header(frag) + hlen); frag->transport_header = (frag->network_header + hlen + sizeof(struct frag_hdr)); /* * Charge the memory for the fragment to any owner * it might possess */ if (skb->sk) skb_set_owner_w(frag, skb->sk); /* * Copy the packet header into the new buffer. */ skb_copy_from_linear_data(skb, skb_network_header(frag), hlen); /* * Build fragment header. */ fh->nexthdr = nexthdr; fh->reserved = 0; if (!frag_id) { ipv6_select_ident(fh, rt); frag_id = fh->identification; } else fh->identification = frag_id; /* * Copy a block of the IP datagram. */ BUG_ON(skb_copy_bits(skb, ptr, skb_transport_header(frag), len)); left -= len; fh->frag_off = htons(offset); if (left > 0) fh->frag_off |= htons(IP6_MF); ipv6_hdr(frag)->payload_len = htons(frag->len - sizeof(struct ipv6hdr)); ptr += len; offset += len; /* * Put this fragment into the sending queue. */ err = output(frag); if (err) goto fail; IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGCREATES); } IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGOKS); consume_skb(skb); return err; fail: IP6_INC_STATS(net, ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_FRAGFAILS); kfree_skb(skb); return err; } static inline int ip6_rt_check(const struct rt6key *rt_key, const struct in6_addr *fl_addr, const struct in6_addr *addr_cache) { return (rt_key->plen != 128 || !ipv6_addr_equal(fl_addr, &rt_key->addr)) && (addr_cache == NULL || !ipv6_addr_equal(fl_addr, addr_cache)); } static struct dst_entry *ip6_sk_dst_check(struct sock *sk, struct dst_entry *dst, const struct flowi6 *fl6) { struct ipv6_pinfo *np = inet6_sk(sk); struct rt6_info *rt; if (!dst) goto out; if (dst->ops->family != AF_INET6) { dst_release(dst); return NULL; } rt = (struct rt6_info *)dst; /* Yes, checking route validity in not connected * case is not very simple. Take into account, * that we do not support routing by source, TOS, * and MSG_DONTROUTE --ANK (980726) * * 1. ip6_rt_check(): If route was host route, * check that cached destination is current. * If it is network route, we still may * check its validity using saved pointer * to the last used address: daddr_cache. * We do not want to save whole address now, * (because main consumer of this service * is tcp, which has not this problem), * so that the last trick works only on connected * sockets. * 2. oif also should be the same. */ if (ip6_rt_check(&rt->rt6i_dst, &fl6->daddr, np->daddr_cache) || #ifdef CONFIG_IPV6_SUBTREES ip6_rt_check(&rt->rt6i_src, &fl6->saddr, np->saddr_cache) || #endif (fl6->flowi6_oif && fl6->flowi6_oif != dst->dev->ifindex)) { dst_release(dst); dst = NULL; } out: return dst; } static int ip6_dst_lookup_tail(struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { struct net *net = sock_net(sk); #ifdef CONFIG_IPV6_OPTIMISTIC_DAD struct neighbour *n; struct rt6_info *rt; #endif int err; if (*dst == NULL) *dst = ip6_route_output(net, sk, fl6); if ((err = (*dst)->error)) goto out_err_release; if (ipv6_addr_any(&fl6->saddr)) { struct rt6_info *rt = (struct rt6_info *) *dst; err = ip6_route_get_saddr(net, rt, &fl6->daddr, sk ? inet6_sk(sk)->srcprefs : 0, &fl6->saddr); if (err) goto out_err_release; } #ifdef CONFIG_IPV6_OPTIMISTIC_DAD /* * Here if the dst entry we've looked up * has a neighbour entry that is in the INCOMPLETE * state and the src address from the flow is * marked as OPTIMISTIC, we release the found * dst entry and replace it instead with the * dst entry of the nexthop router */ rt = (struct rt6_info *) *dst; rcu_read_lock_bh(); n = __ipv6_neigh_lookup_noref(rt->dst.dev, rt6_nexthop(rt)); err = n && !(n->nud_state & NUD_VALID) ? -EINVAL : 0; rcu_read_unlock_bh(); if (err) { struct inet6_ifaddr *ifp; struct flowi6 fl_gw6; int redirect; ifp = ipv6_get_ifaddr(net, &fl6->saddr, (*dst)->dev, 1); redirect = (ifp && ifp->flags & IFA_F_OPTIMISTIC); if (ifp) in6_ifa_put(ifp); if (redirect) { /* * We need to get the dst entry for the * default router instead */ dst_release(*dst); memcpy(&fl_gw6, fl6, sizeof(struct flowi6)); memset(&fl_gw6.daddr, 0, sizeof(struct in6_addr)); *dst = ip6_route_output(net, sk, &fl_gw6); if ((err = (*dst)->error)) goto out_err_release; } } #endif if (ipv6_addr_v4mapped(&fl6->saddr) && !(ipv6_addr_v4mapped(&fl6->daddr) || ipv6_addr_any(&fl6->daddr))) { err = -EAFNOSUPPORT; goto out_err_release; } return 0; out_err_release: if (err == -ENETUNREACH) IP6_INC_STATS(net, NULL, IPSTATS_MIB_OUTNOROUTES); dst_release(*dst); *dst = NULL; return err; } /** * ip6_dst_lookup - perform route lookup on flow * @sk: socket which provides route info * @dst: pointer to dst_entry * for result * @fl6: flow to lookup * * This function performs a route lookup on the given flow. * * It returns zero on success, or a standard errno code on error. */ int ip6_dst_lookup(struct sock *sk, struct dst_entry **dst, struct flowi6 *fl6) { *dst = NULL; return ip6_dst_lookup_tail(sk, dst, fl6); } EXPORT_SYMBOL_GPL(ip6_dst_lookup); /** * ip6_dst_lookup_flow - perform route lookup on flow with ipsec * @sk: socket which provides route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = NULL; int err; err = ip6_dst_lookup_tail(sk, &dst, fl6); if (err) return ERR_PTR(err); if (final_dst) fl6->daddr = *final_dst; return xfrm_lookup_route(sock_net(sk), dst, flowi6_to_flowi(fl6), sk, 0); } EXPORT_SYMBOL_GPL(ip6_dst_lookup_flow); /** * ip6_sk_dst_lookup_flow - perform socket cached route lookup on flow * @sk: socket which provides the dst cache and route info * @fl6: flow to lookup * @final_dst: final destination address for ipsec lookup * * This function performs a route lookup on the given flow with the * possibility of using the cached route in the socket if it is valid. * It will take the socket dst lock when operating on the dst cache. * As a result, this function can only be used in process context. * * It returns a valid dst pointer on success, or a pointer encoded * error code. */ struct dst_entry *ip6_sk_dst_lookup_flow(struct sock *sk, struct flowi6 *fl6, const struct in6_addr *final_dst) { struct dst_entry *dst = sk_dst_check(sk, inet6_sk(sk)->dst_cookie); dst = ip6_sk_dst_check(sk, dst, fl6); if (!dst) dst = ip6_dst_lookup_flow(sk, fl6, final_dst); return dst; } EXPORT_SYMBOL_GPL(ip6_sk_dst_lookup_flow); static inline int ip6_ufo_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int hh_len, int fragheaderlen, int transhdrlen, int mtu, unsigned int flags, struct rt6_info *rt) { struct sk_buff *skb; struct frag_hdr fhdr; int err; /* There is support for UDP large send offload by network * device, so create one single skb packet containing complete * udp datagram */ if ((skb = skb_peek_tail(&sk->sk_write_queue)) == NULL) { skb = sock_alloc_send_skb(sk, hh_len + fragheaderlen + transhdrlen + 20, (flags & MSG_DONTWAIT), &err); if (skb == NULL) return err; /* reserve space for Hardware header */ skb_reserve(skb, hh_len); /* create space for UDP/IP header */ skb_put(skb, fragheaderlen + transhdrlen); /* initialize network header pointer */ skb_reset_network_header(skb); /* initialize protocol header pointer */ skb->transport_header = skb->network_header + fragheaderlen; skb->protocol = htons(ETH_P_IPV6); skb->csum = 0; __skb_queue_tail(&sk->sk_write_queue, skb); } else if (skb_is_gso(skb)) { goto append; } skb->ip_summed = CHECKSUM_PARTIAL; /* Specify the length of each IPv6 datagram fragment. * It has to be a multiple of 8. */ skb_shinfo(skb)->gso_size = (mtu - fragheaderlen - sizeof(struct frag_hdr)) & ~7; skb_shinfo(skb)->gso_type = SKB_GSO_UDP; ipv6_select_ident(&fhdr, rt); skb_shinfo(skb)->ip6_frag_id = fhdr.identification; append: return skb_append_datato_frags(sk, skb, getfrag, from, (length - transhdrlen)); } static inline struct ipv6_opt_hdr *ip6_opt_dup(struct ipv6_opt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static inline struct ipv6_rt_hdr *ip6_rthdr_dup(struct ipv6_rt_hdr *src, gfp_t gfp) { return src ? kmemdup(src, (src->hdrlen + 1) * 8, gfp) : NULL; } static void ip6_append_data_mtu(unsigned int *mtu, int *maxfraglen, unsigned int fragheaderlen, struct sk_buff *skb, struct rt6_info *rt, unsigned int orig_mtu) { if (!(rt->dst.flags & DST_XFRM_TUNNEL)) { if (skb == NULL) { /* first fragment, reserve header_len */ *mtu = orig_mtu - rt->dst.header_len; } else { /* * this fragment is not first, the headers * space is regarded as data space. */ *mtu = orig_mtu; } *maxfraglen = ((*mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); } } int ip6_append_data(struct sock *sk, int getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb), void *from, int length, int transhdrlen, int hlimit, int tclass, struct ipv6_txoptions *opt, struct flowi6 *fl6, struct rt6_info *rt, unsigned int flags, int dontfrag) { struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct inet_cork *cork; struct sk_buff *skb, *skb_prev = NULL; unsigned int maxfraglen, fragheaderlen, mtu, orig_mtu, pmtu; int exthdrlen; int dst_exthdrlen; int hh_len; int copy; int err; int offset = 0; __u8 tx_flags = 0; u32 tskey = 0; if (flags&MSG_PROBE) return 0; cork = &inet->cork.base; if (skb_queue_empty(&sk->sk_write_queue)) { /* * setup for corking */ if (opt) { if (WARN_ON(np->cork.opt)) return -EINVAL; np->cork.opt = kzalloc(sizeof(*opt), sk->sk_allocation); if (unlikely(np->cork.opt == NULL)) return -ENOBUFS; np->cork.opt->tot_len = sizeof(*opt); np->cork.opt->opt_flen = opt->opt_flen; np->cork.opt->opt_nflen = opt->opt_nflen; np->cork.opt->dst0opt = ip6_opt_dup(opt->dst0opt, sk->sk_allocation); if (opt->dst0opt && !np->cork.opt->dst0opt) return -ENOBUFS; np->cork.opt->dst1opt = ip6_opt_dup(opt->dst1opt, sk->sk_allocation); if (opt->dst1opt && !np->cork.opt->dst1opt) return -ENOBUFS; np->cork.opt->hopopt = ip6_opt_dup(opt->hopopt, sk->sk_allocation); if (opt->hopopt && !np->cork.opt->hopopt) return -ENOBUFS; np->cork.opt->srcrt = ip6_rthdr_dup(opt->srcrt, sk->sk_allocation); if (opt->srcrt && !np->cork.opt->srcrt) return -ENOBUFS; /* need source address above miyazawa*/ } dst_hold(&rt->dst); cork->dst = &rt->dst; inet->cork.fl.u.ip6 = *fl6; np->cork.hop_limit = hlimit; np->cork.tclass = tclass; if (rt->dst.flags & DST_XFRM_TUNNEL) mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? READ_ONCE(rt->dst.dev->mtu) : dst_mtu(&rt->dst); else mtu = np->pmtudisc >= IPV6_PMTUDISC_PROBE ? READ_ONCE(rt->dst.dev->mtu) : dst_mtu(rt->dst.path); if (np->frag_size < mtu) { if (np->frag_size) mtu = np->frag_size; } if (mtu < IPV6_MIN_MTU) return -EINVAL; cork->fragsize = mtu; if (dst_allfrag(rt->dst.path)) cork->flags |= IPCORK_ALLFRAG; cork->length = 0; exthdrlen = (opt ? opt->opt_flen : 0); length += exthdrlen; transhdrlen += exthdrlen; dst_exthdrlen = rt->dst.header_len - rt->rt6i_nfheader_len; } else { rt = (struct rt6_info *)cork->dst; fl6 = &inet->cork.fl.u.ip6; opt = np->cork.opt; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; mtu = cork->fragsize; } orig_mtu = mtu; hh_len = LL_RESERVED_SPACE(rt->dst.dev); fragheaderlen = sizeof(struct ipv6hdr) + rt->rt6i_nfheader_len + (opt ? opt->opt_nflen : 0); maxfraglen = ((mtu - fragheaderlen) & ~7) + fragheaderlen - sizeof(struct frag_hdr); if (mtu <= sizeof(struct ipv6hdr) + IPV6_MAXPLEN) { unsigned int maxnonfragsize, headersize; headersize = sizeof(struct ipv6hdr) + (opt ? opt->opt_flen + opt->opt_nflen : 0) + (dst_allfrag(&rt->dst) ? sizeof(struct frag_hdr) : 0) + rt->rt6i_nfheader_len; if (ip6_sk_ignore_df(sk)) maxnonfragsize = sizeof(struct ipv6hdr) + IPV6_MAXPLEN; else maxnonfragsize = mtu; /* as per RFC 7112 section 5, the entire IPv6 Header Chain must fit * the first fragment */ if (headersize + transhdrlen > mtu) goto emsgsize; /* dontfrag active */ if ((cork->length + length > mtu - headersize) && dontfrag && (sk->sk_protocol == IPPROTO_UDP || sk->sk_protocol == IPPROTO_RAW)) { ipv6_local_rxpmtu(sk, fl6, mtu - headersize + sizeof(struct ipv6hdr)); goto emsgsize; } if (cork->length + length > maxnonfragsize - headersize) { emsgsize: pmtu = max_t(int, mtu - headersize + sizeof(struct ipv6hdr), 0); ipv6_local_error(sk, EMSGSIZE, fl6, pmtu); return -EMSGSIZE; } } if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_RAW) { sock_tx_timestamp(sk, &tx_flags); if (tx_flags & SKBTX_ANY_SW_TSTAMP && sk->sk_tsflags & SOF_TIMESTAMPING_OPT_ID) tskey = sk->sk_tskey++; } /* * Let's try using as much space as possible. * Use MTU if total length of the message fits into the MTU. * Otherwise, we need to reserve fragment header and * fragment alignment (= 8-15 octects, in total). * * Note that we may need to "move" the data from the tail of * of the buffer to the new fragment when we split * the message. * * FIXME: It may be fragmented into multiple chunks * at once if non-fragmentable extension headers * are too large. * --yoshfuji */ skb = skb_peek_tail(&sk->sk_write_queue); cork->length += length; if ((skb && skb_is_gso(skb)) || (((length + fragheaderlen) > mtu) && (skb_queue_len(&sk->sk_write_queue) <= 1) && (sk->sk_protocol == IPPROTO_UDP) && (rt->dst.dev->features & NETIF_F_UFO) && (sk->sk_type == SOCK_DGRAM))) { err = ip6_ufo_append_data(sk, getfrag, from, length, hh_len, fragheaderlen, transhdrlen, mtu, flags, rt); if (err) goto error; return 0; } if (!skb) goto alloc_new_skb; while (length > 0) { /* Check if the remaining data fits into current packet. */ copy = (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - skb->len; if (copy < length) copy = maxfraglen - skb->len; if (copy <= 0) { char *data; unsigned int datalen; unsigned int fraglen; unsigned int fraggap; unsigned int alloclen; alloc_new_skb: /* There's no room in the current skb */ if (skb) fraggap = skb->len - maxfraglen; else fraggap = 0; /* update mtu and maxfraglen if necessary */ if (skb == NULL || skb_prev == NULL) ip6_append_data_mtu(&mtu, &maxfraglen, fragheaderlen, skb, rt, orig_mtu); skb_prev = skb; /* * If remaining data exceeds the mtu, * we know we need more fragment(s). */ datalen = length + fraggap; if (datalen > (cork->length <= mtu && !(cork->flags & IPCORK_ALLFRAG) ? mtu : maxfraglen) - fragheaderlen) datalen = maxfraglen - fragheaderlen - rt->dst.trailer_len; if ((flags & MSG_MORE) && !(rt->dst.dev->features&NETIF_F_SG)) alloclen = mtu; else alloclen = datalen + fragheaderlen; alloclen += dst_exthdrlen; if (datalen != length + fraggap) { /* * this is not the last fragment, the trailer * space is regarded as data space. */ datalen += rt->dst.trailer_len; } alloclen += rt->dst.trailer_len; fraglen = datalen + fragheaderlen; /* * We just reserve space for fragment header. * Note: this may be overallocation if the message * (without MSG_MORE) fits into the MTU. */ alloclen += sizeof(struct frag_hdr); copy = datalen - transhdrlen - fraggap; if (copy < 0) { err = -EINVAL; goto error; } if (transhdrlen) { skb = sock_alloc_send_skb(sk, alloclen + hh_len, (flags & MSG_DONTWAIT), &err); } else { skb = NULL; if (atomic_read(&sk->sk_wmem_alloc) <= 2 * sk->sk_sndbuf) skb = sock_wmalloc(sk, alloclen + hh_len, 1, sk->sk_allocation); if (unlikely(skb == NULL)) err = -ENOBUFS; } if (skb == NULL) goto error; /* * Fill in the control structures */ skb->protocol = htons(ETH_P_IPV6); skb->ip_summed = CHECKSUM_NONE; skb->csum = 0; /* reserve for fragmentation and ipsec header */ skb_reserve(skb, hh_len + sizeof(struct frag_hdr) + dst_exthdrlen); /* Only the initial fragment is time stamped */ skb_shinfo(skb)->tx_flags = tx_flags; tx_flags = 0; skb_shinfo(skb)->tskey = tskey; tskey = 0; /* * Find where to start putting bytes */ data = skb_put(skb, fraglen); skb_set_network_header(skb, exthdrlen); data += fragheaderlen; skb->transport_header = (skb->network_header + fragheaderlen); if (fraggap) { skb->csum = skb_copy_and_csum_bits( skb_prev, maxfraglen, data + transhdrlen, fraggap, 0); skb_prev->csum = csum_sub(skb_prev->csum, skb->csum); data += fraggap; pskb_trim_unique(skb_prev, maxfraglen); } if (copy > 0 && getfrag(from, data + transhdrlen, offset, copy, fraggap, skb) < 0) { err = -EFAULT; kfree_skb(skb); goto error; } offset += copy; length -= datalen - fraggap; transhdrlen = 0; exthdrlen = 0; dst_exthdrlen = 0; /* * Put the packet on the pending queue */ __skb_queue_tail(&sk->sk_write_queue, skb); continue; } if (copy > length) copy = length; if (!(rt->dst.dev->features&NETIF_F_SG) && skb_tailroom(skb) >= copy) { unsigned int off; off = skb->len; if (getfrag(from, skb_put(skb, copy), offset, copy, off, skb) < 0) { __skb_trim(skb, off); err = -EFAULT; goto error; } } else { int i = skb_shinfo(skb)->nr_frags; struct page_frag *pfrag = sk_page_frag(sk); err = -ENOMEM; if (!sk_page_frag_refill(sk, pfrag)) goto error; if (!skb_can_coalesce(skb, i, pfrag->page, pfrag->offset)) { err = -EMSGSIZE; if (i == MAX_SKB_FRAGS) goto error; __skb_fill_page_desc(skb, i, pfrag->page, pfrag->offset, 0); skb_shinfo(skb)->nr_frags = ++i; get_page(pfrag->page); } copy = min_t(int, copy, pfrag->size - pfrag->offset); if (getfrag(from, page_address(pfrag->page) + pfrag->offset, offset, copy, skb->len, skb) < 0) goto error_efault; pfrag->offset += copy; skb_frag_size_add(&skb_shinfo(skb)->frags[i - 1], copy); skb->len += copy; skb->data_len += copy; skb->truesize += copy; atomic_add(copy, &sk->sk_wmem_alloc); } offset += copy; length -= copy; } return 0; error_efault: err = -EFAULT; error: cork->length -= length; IP6_INC_STATS(sock_net(sk), rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); return err; } EXPORT_SYMBOL_GPL(ip6_append_data); static void ip6_cork_release(struct inet_sock *inet, struct ipv6_pinfo *np) { if (np->cork.opt) { kfree(np->cork.opt->dst0opt); kfree(np->cork.opt->dst1opt); kfree(np->cork.opt->hopopt); kfree(np->cork.opt->srcrt); kfree(np->cork.opt); np->cork.opt = NULL; } if (inet->cork.base.dst) { dst_release(inet->cork.base.dst); inet->cork.base.dst = NULL; inet->cork.base.flags &= ~IPCORK_ALLFRAG; } memset(&inet->cork.fl, 0, sizeof(inet->cork.fl)); } int ip6_push_pending_frames(struct sock *sk) { struct sk_buff *skb, *tmp_skb; struct sk_buff **tail_skb; struct in6_addr final_dst_buf, *final_dst = &final_dst_buf; struct inet_sock *inet = inet_sk(sk); struct ipv6_pinfo *np = inet6_sk(sk); struct net *net = sock_net(sk); struct ipv6hdr *hdr; struct ipv6_txoptions *opt = np->cork.opt; struct rt6_info *rt = (struct rt6_info *)inet->cork.base.dst; struct flowi6 *fl6 = &inet->cork.fl.u.ip6; unsigned char proto = fl6->flowi6_proto; int err = 0; if ((skb = __skb_dequeue(&sk->sk_write_queue)) == NULL) goto out; tail_skb = &(skb_shinfo(skb)->frag_list); /* move skb->data to ip header from ext header */ if (skb->data < skb_network_header(skb)) __skb_pull(skb, skb_network_offset(skb)); while ((tmp_skb = __skb_dequeue(&sk->sk_write_queue)) != NULL) { __skb_pull(tmp_skb, skb_network_header_len(skb)); *tail_skb = tmp_skb; tail_skb = &(tmp_skb->next); skb->len += tmp_skb->len; skb->data_len += tmp_skb->len; skb->truesize += tmp_skb->truesize; tmp_skb->destructor = NULL; tmp_skb->sk = NULL; } /* Allow local fragmentation. */ skb->ignore_df = ip6_sk_ignore_df(sk); *final_dst = fl6->daddr; __skb_pull(skb, skb_network_header_len(skb)); if (opt && opt->opt_flen) ipv6_push_frag_opts(skb, opt, &proto); if (opt && opt->opt_nflen) ipv6_push_nfrag_opts(skb, opt, &proto, &final_dst); skb_push(skb, sizeof(struct ipv6hdr)); skb_reset_network_header(skb); hdr = ipv6_hdr(skb); ip6_flow_hdr(hdr, np->cork.tclass, ip6_make_flowlabel(net, skb, fl6->flowlabel, np->autoflowlabel)); hdr->hop_limit = np->cork.hop_limit; hdr->nexthdr = proto; hdr->saddr = fl6->saddr; hdr->daddr = *final_dst; skb->priority = sk->sk_priority; skb->mark = sk->sk_mark; skb_dst_set(skb, dst_clone(&rt->dst)); IP6_UPD_PO_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUT, skb->len); if (proto == IPPROTO_ICMPV6) { struct inet6_dev *idev = ip6_dst_idev(skb_dst(skb)); ICMP6MSGOUT_INC_STATS(net, idev, icmp6_hdr(skb)->icmp6_type); ICMP6_INC_STATS(net, idev, ICMP6_MIB_OUTMSGS); } err = ip6_local_out(skb); if (err) { if (err > 0) err = net_xmit_errno(err); if (err) goto error; } out: ip6_cork_release(inet, np); return err; error: IP6_INC_STATS(net, rt->rt6i_idev, IPSTATS_MIB_OUTDISCARDS); goto out; } EXPORT_SYMBOL_GPL(ip6_push_pending_frames); void ip6_flush_pending_frames(struct sock *sk) { struct sk_buff *skb; while ((skb = __skb_dequeue_tail(&sk->sk_write_queue)) != NULL) { if (skb_dst(skb)) IP6_INC_STATS(sock_net(sk), ip6_dst_idev(skb_dst(skb)), IPSTATS_MIB_OUTDISCARDS); kfree_skb(skb); } ip6_cork_release(inet_sk(sk), inet6_sk(sk)); } EXPORT_SYMBOL_GPL(ip6_flush_pending_frames);
./CrossVul/dataset_final_sorted/CWE-200/c/good_759_1
crossvul-cpp_data_bad_5691_0
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Copyright Jonathan Naylor G4KLX (g4klx@g4klx.demon.co.uk) * Copyright Alan Cox GW4PTS (alan@lxorguk.ukuu.org.uk) * Copyright Darryl Miles G7LED (dlm@g7led.demon.co.uk) */ #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/capability.h> #include <linux/errno.h> #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/slab.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/timer.h> #include <linux/string.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/stat.h> #include <net/ax25.h> #include <linux/inet.h> #include <linux/netdevice.h> #include <linux/if_arp.h> #include <linux/skbuff.h> #include <net/net_namespace.h> #include <net/sock.h> #include <asm/uaccess.h> #include <linux/fcntl.h> #include <linux/termios.h> /* For TIOCINQ/OUTQ */ #include <linux/mm.h> #include <linux/interrupt.h> #include <linux/notifier.h> #include <net/netrom.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <net/ip.h> #include <net/tcp_states.h> #include <net/arp.h> #include <linux/init.h> static int nr_ndevs = 4; int sysctl_netrom_default_path_quality = NR_DEFAULT_QUAL; int sysctl_netrom_obsolescence_count_initialiser = NR_DEFAULT_OBS; int sysctl_netrom_network_ttl_initialiser = NR_DEFAULT_TTL; int sysctl_netrom_transport_timeout = NR_DEFAULT_T1; int sysctl_netrom_transport_maximum_tries = NR_DEFAULT_N2; int sysctl_netrom_transport_acknowledge_delay = NR_DEFAULT_T2; int sysctl_netrom_transport_busy_delay = NR_DEFAULT_T4; int sysctl_netrom_transport_requested_window_size = NR_DEFAULT_WINDOW; int sysctl_netrom_transport_no_activity_timeout = NR_DEFAULT_IDLE; int sysctl_netrom_routing_control = NR_DEFAULT_ROUTING; int sysctl_netrom_link_fails_count = NR_DEFAULT_FAILS; int sysctl_netrom_reset_circuit = NR_DEFAULT_RESET; static unsigned short circuit = 0x101; static HLIST_HEAD(nr_list); static DEFINE_SPINLOCK(nr_list_lock); static const struct proto_ops nr_proto_ops; /* * NETROM network devices are virtual network devices encapsulating NETROM * frames into AX.25 which will be sent through an AX.25 device, so form a * special "super class" of normal net devices; split their locks off into a * separate class since they always nest. */ static struct lock_class_key nr_netdev_xmit_lock_key; static struct lock_class_key nr_netdev_addr_lock_key; static void nr_set_lockdep_one(struct net_device *dev, struct netdev_queue *txq, void *_unused) { lockdep_set_class(&txq->_xmit_lock, &nr_netdev_xmit_lock_key); } static void nr_set_lockdep_key(struct net_device *dev) { lockdep_set_class(&dev->addr_list_lock, &nr_netdev_addr_lock_key); netdev_for_each_tx_queue(dev, nr_set_lockdep_one, NULL); } /* * Socket removal during an interrupt is now safe. */ static void nr_remove_socket(struct sock *sk) { spin_lock_bh(&nr_list_lock); sk_del_node_init(sk); spin_unlock_bh(&nr_list_lock); } /* * Kill all bound sockets on a dropped device. */ static void nr_kill_by_device(struct net_device *dev) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) if (nr_sk(s)->device == dev) nr_disconnect(s, ENETUNREACH); spin_unlock_bh(&nr_list_lock); } /* * Handle device status changes. */ static int nr_device_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = (struct net_device *)ptr; if (!net_eq(dev_net(dev), &init_net)) return NOTIFY_DONE; if (event != NETDEV_DOWN) return NOTIFY_DONE; nr_kill_by_device(dev); nr_rt_device_down(dev); return NOTIFY_DONE; } /* * Add a socket to the bound sockets list. */ static void nr_insert_socket(struct sock *sk) { spin_lock_bh(&nr_list_lock); sk_add_node(sk, &nr_list); spin_unlock_bh(&nr_list_lock); } /* * Find a socket that wants to accept the Connect Request we just * received. */ static struct sock *nr_find_listener(ax25_address *addr) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) if (!ax25cmp(&nr_sk(s)->source_addr, addr) && s->sk_state == TCP_LISTEN) { bh_lock_sock(s); goto found; } s = NULL; found: spin_unlock_bh(&nr_list_lock); return s; } /* * Find a connected NET/ROM socket given my circuit IDs. */ static struct sock *nr_find_socket(unsigned char index, unsigned char id) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) { struct nr_sock *nr = nr_sk(s); if (nr->my_index == index && nr->my_id == id) { bh_lock_sock(s); goto found; } } s = NULL; found: spin_unlock_bh(&nr_list_lock); return s; } /* * Find a connected NET/ROM socket given their circuit IDs. */ static struct sock *nr_find_peer(unsigned char index, unsigned char id, ax25_address *dest) { struct sock *s; spin_lock_bh(&nr_list_lock); sk_for_each(s, &nr_list) { struct nr_sock *nr = nr_sk(s); if (nr->your_index == index && nr->your_id == id && !ax25cmp(&nr->dest_addr, dest)) { bh_lock_sock(s); goto found; } } s = NULL; found: spin_unlock_bh(&nr_list_lock); return s; } /* * Find next free circuit ID. */ static unsigned short nr_find_next_circuit(void) { unsigned short id = circuit; unsigned char i, j; struct sock *sk; for (;;) { i = id / 256; j = id % 256; if (i != 0 && j != 0) { if ((sk=nr_find_socket(i, j)) == NULL) break; bh_unlock_sock(sk); } id++; } return id; } /* * Deferred destroy. */ void nr_destroy_socket(struct sock *); /* * Handler for deferred kills. */ static void nr_destroy_timer(unsigned long data) { struct sock *sk=(struct sock *)data; bh_lock_sock(sk); sock_hold(sk); nr_destroy_socket(sk); bh_unlock_sock(sk); sock_put(sk); } /* * This is called from user mode and the timers. Thus it protects itself * against interrupt users but doesn't worry about being called during * work. Once it is removed from the queue no interrupt or bottom half * will touch it and we are (fairly 8-) ) safe. */ void nr_destroy_socket(struct sock *sk) { struct sk_buff *skb; nr_remove_socket(sk); nr_stop_heartbeat(sk); nr_stop_t1timer(sk); nr_stop_t2timer(sk); nr_stop_t4timer(sk); nr_stop_idletimer(sk); nr_clear_queues(sk); /* Flush the queues */ while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) { if (skb->sk != sk) { /* A pending connection */ /* Queue the unaccepted socket for death */ sock_set_flag(skb->sk, SOCK_DEAD); nr_start_heartbeat(skb->sk); nr_sk(skb->sk)->state = NR_STATE_0; } kfree_skb(skb); } if (sk_has_allocations(sk)) { /* Defer: outstanding buffers */ sk->sk_timer.function = nr_destroy_timer; sk->sk_timer.expires = jiffies + 2 * HZ; add_timer(&sk->sk_timer); } else sock_put(sk); } /* * Handling for system calls applied via the various interfaces to a * NET/ROM socket object. */ static int nr_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); unsigned long opt; if (level != SOL_NETROM) return -ENOPROTOOPT; if (optlen < sizeof(unsigned int)) return -EINVAL; if (get_user(opt, (unsigned int __user *)optval)) return -EFAULT; switch (optname) { case NETROM_T1: if (opt < 1 || opt > ULONG_MAX / HZ) return -EINVAL; nr->t1 = opt * HZ; return 0; case NETROM_T2: if (opt < 1 || opt > ULONG_MAX / HZ) return -EINVAL; nr->t2 = opt * HZ; return 0; case NETROM_N2: if (opt < 1 || opt > 31) return -EINVAL; nr->n2 = opt; return 0; case NETROM_T4: if (opt < 1 || opt > ULONG_MAX / HZ) return -EINVAL; nr->t4 = opt * HZ; return 0; case NETROM_IDLE: if (opt > ULONG_MAX / (60 * HZ)) return -EINVAL; nr->idle = opt * 60 * HZ; return 0; default: return -ENOPROTOOPT; } } static int nr_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); int val = 0; int len; if (level != SOL_NETROM) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; switch (optname) { case NETROM_T1: val = nr->t1 / HZ; break; case NETROM_T2: val = nr->t2 / HZ; break; case NETROM_N2: val = nr->n2; break; case NETROM_T4: val = nr->t4 / HZ; break; case NETROM_IDLE: val = nr->idle / (60 * HZ); break; default: return -ENOPROTOOPT; } len = min_t(unsigned int, len, sizeof(int)); if (put_user(len, optlen)) return -EFAULT; return copy_to_user(optval, &val, len) ? -EFAULT : 0; } static int nr_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; lock_sock(sk); if (sk->sk_state != TCP_LISTEN) { memset(&nr_sk(sk)->user_addr, 0, AX25_ADDR_LEN); sk->sk_max_ack_backlog = backlog; sk->sk_state = TCP_LISTEN; release_sock(sk); return 0; } release_sock(sk); return -EOPNOTSUPP; } static struct proto nr_proto = { .name = "NETROM", .owner = THIS_MODULE, .obj_size = sizeof(struct nr_sock), }; static int nr_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; struct nr_sock *nr; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; if (sock->type != SOCK_SEQPACKET || protocol != 0) return -ESOCKTNOSUPPORT; sk = sk_alloc(net, PF_NETROM, GFP_ATOMIC, &nr_proto); if (sk == NULL) return -ENOMEM; nr = nr_sk(sk); sock_init_data(sock, sk); sock->ops = &nr_proto_ops; sk->sk_protocol = protocol; skb_queue_head_init(&nr->ack_queue); skb_queue_head_init(&nr->reseq_queue); skb_queue_head_init(&nr->frag_queue); nr_init_timers(sk); nr->t1 = msecs_to_jiffies(sysctl_netrom_transport_timeout); nr->t2 = msecs_to_jiffies(sysctl_netrom_transport_acknowledge_delay); nr->n2 = msecs_to_jiffies(sysctl_netrom_transport_maximum_tries); nr->t4 = msecs_to_jiffies(sysctl_netrom_transport_busy_delay); nr->idle = msecs_to_jiffies(sysctl_netrom_transport_no_activity_timeout); nr->window = sysctl_netrom_transport_requested_window_size; nr->bpqext = 1; nr->state = NR_STATE_0; return 0; } static struct sock *nr_make_new(struct sock *osk) { struct sock *sk; struct nr_sock *nr, *onr; if (osk->sk_type != SOCK_SEQPACKET) return NULL; sk = sk_alloc(sock_net(osk), PF_NETROM, GFP_ATOMIC, osk->sk_prot); if (sk == NULL) return NULL; nr = nr_sk(sk); sock_init_data(NULL, sk); sk->sk_type = osk->sk_type; sk->sk_priority = osk->sk_priority; sk->sk_protocol = osk->sk_protocol; sk->sk_rcvbuf = osk->sk_rcvbuf; sk->sk_sndbuf = osk->sk_sndbuf; sk->sk_state = TCP_ESTABLISHED; sock_copy_flags(sk, osk); skb_queue_head_init(&nr->ack_queue); skb_queue_head_init(&nr->reseq_queue); skb_queue_head_init(&nr->frag_queue); nr_init_timers(sk); onr = nr_sk(osk); nr->t1 = onr->t1; nr->t2 = onr->t2; nr->n2 = onr->n2; nr->t4 = onr->t4; nr->idle = onr->idle; nr->window = onr->window; nr->device = onr->device; nr->bpqext = onr->bpqext; return sk; } static int nr_release(struct socket *sock) { struct sock *sk = sock->sk; struct nr_sock *nr; if (sk == NULL) return 0; sock_hold(sk); sock_orphan(sk); lock_sock(sk); nr = nr_sk(sk); switch (nr->state) { case NR_STATE_0: case NR_STATE_1: case NR_STATE_2: nr_disconnect(sk, 0); nr_destroy_socket(sk); break; case NR_STATE_3: nr_clear_queues(sk); nr->n2count = 0; nr_write_internal(sk, NR_DISCREQ); nr_start_t1timer(sk); nr_stop_t2timer(sk); nr_stop_t4timer(sk); nr_stop_idletimer(sk); nr->state = NR_STATE_2; sk->sk_state = TCP_CLOSE; sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); sock_set_flag(sk, SOCK_DESTROY); break; default: break; } sock->sk = NULL; release_sock(sk); sock_put(sk); return 0; } static int nr_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); struct full_sockaddr_ax25 *addr = (struct full_sockaddr_ax25 *)uaddr; struct net_device *dev; ax25_uid_assoc *user; ax25_address *source; lock_sock(sk); if (!sock_flag(sk, SOCK_ZAPPED)) { release_sock(sk); return -EINVAL; } if (addr_len < sizeof(struct sockaddr_ax25) || addr_len > sizeof(struct full_sockaddr_ax25)) { release_sock(sk); return -EINVAL; } if (addr_len < (addr->fsa_ax25.sax25_ndigis * sizeof(ax25_address) + sizeof(struct sockaddr_ax25))) { release_sock(sk); return -EINVAL; } if (addr->fsa_ax25.sax25_family != AF_NETROM) { release_sock(sk); return -EINVAL; } if ((dev = nr_dev_get(&addr->fsa_ax25.sax25_call)) == NULL) { release_sock(sk); return -EADDRNOTAVAIL; } /* * Only the super user can set an arbitrary user callsign. */ if (addr->fsa_ax25.sax25_ndigis == 1) { if (!capable(CAP_NET_BIND_SERVICE)) { dev_put(dev); release_sock(sk); return -EPERM; } nr->user_addr = addr->fsa_digipeater[0]; nr->source_addr = addr->fsa_ax25.sax25_call; } else { source = &addr->fsa_ax25.sax25_call; user = ax25_findbyuid(current_euid()); if (user) { nr->user_addr = user->call; ax25_uid_put(user); } else { if (ax25_uid_policy && !capable(CAP_NET_BIND_SERVICE)) { release_sock(sk); dev_put(dev); return -EPERM; } nr->user_addr = *source; } nr->source_addr = *source; } nr->device = dev; nr_insert_socket(sk); sock_reset_flag(sk, SOCK_ZAPPED); dev_put(dev); release_sock(sk); return 0; } static int nr_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); struct sockaddr_ax25 *addr = (struct sockaddr_ax25 *)uaddr; ax25_address *source = NULL; ax25_uid_assoc *user; struct net_device *dev; int err = 0; lock_sock(sk); if (sk->sk_state == TCP_ESTABLISHED && sock->state == SS_CONNECTING) { sock->state = SS_CONNECTED; goto out_release; /* Connect completed during a ERESTARTSYS event */ } if (sk->sk_state == TCP_CLOSE && sock->state == SS_CONNECTING) { sock->state = SS_UNCONNECTED; err = -ECONNREFUSED; goto out_release; } if (sk->sk_state == TCP_ESTABLISHED) { err = -EISCONN; /* No reconnect on a seqpacket socket */ goto out_release; } sk->sk_state = TCP_CLOSE; sock->state = SS_UNCONNECTED; if (addr_len != sizeof(struct sockaddr_ax25) && addr_len != sizeof(struct full_sockaddr_ax25)) { err = -EINVAL; goto out_release; } if (addr->sax25_family != AF_NETROM) { err = -EINVAL; goto out_release; } if (sock_flag(sk, SOCK_ZAPPED)) { /* Must bind first - autobinding in this may or may not work */ sock_reset_flag(sk, SOCK_ZAPPED); if ((dev = nr_dev_first()) == NULL) { err = -ENETUNREACH; goto out_release; } source = (ax25_address *)dev->dev_addr; user = ax25_findbyuid(current_euid()); if (user) { nr->user_addr = user->call; ax25_uid_put(user); } else { if (ax25_uid_policy && !capable(CAP_NET_ADMIN)) { dev_put(dev); err = -EPERM; goto out_release; } nr->user_addr = *source; } nr->source_addr = *source; nr->device = dev; dev_put(dev); nr_insert_socket(sk); /* Finish the bind */ } nr->dest_addr = addr->sax25_call; release_sock(sk); circuit = nr_find_next_circuit(); lock_sock(sk); nr->my_index = circuit / 256; nr->my_id = circuit % 256; circuit++; /* Move to connecting socket, start sending Connect Requests */ sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; nr_establish_data_link(sk); nr->state = NR_STATE_1; nr_start_heartbeat(sk); /* Now the loop */ if (sk->sk_state != TCP_ESTABLISHED && (flags & O_NONBLOCK)) { err = -EINPROGRESS; goto out_release; } /* * A Connect Ack with Choke or timeout or failed routing will go to * closed. */ if (sk->sk_state == TCP_SYN_SENT) { DEFINE_WAIT(wait); for (;;) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk->sk_state != TCP_SYN_SENT) break; if (!signal_pending(current)) { release_sock(sk); schedule(); lock_sock(sk); continue; } err = -ERESTARTSYS; break; } finish_wait(sk_sleep(sk), &wait); if (err) goto out_release; } if (sk->sk_state != TCP_ESTABLISHED) { sock->state = SS_UNCONNECTED; err = sock_error(sk); /* Always set at this point */ goto out_release; } sock->state = SS_CONNECTED; out_release: release_sock(sk); return err; } static int nr_accept(struct socket *sock, struct socket *newsock, int flags) { struct sk_buff *skb; struct sock *newsk; DEFINE_WAIT(wait); struct sock *sk; int err = 0; if ((sk = sock->sk) == NULL) return -EINVAL; lock_sock(sk); if (sk->sk_type != SOCK_SEQPACKET) { err = -EOPNOTSUPP; goto out_release; } if (sk->sk_state != TCP_LISTEN) { err = -EINVAL; goto out_release; } /* * The write queue this time is holding sockets ready to use * hooked into the SABM we saved */ for (;;) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); skb = skb_dequeue(&sk->sk_receive_queue); if (skb) break; if (flags & O_NONBLOCK) { err = -EWOULDBLOCK; break; } if (!signal_pending(current)) { release_sock(sk); schedule(); lock_sock(sk); continue; } err = -ERESTARTSYS; break; } finish_wait(sk_sleep(sk), &wait); if (err) goto out_release; newsk = skb->sk; sock_graft(newsk, newsock); /* Now attach up the new socket */ kfree_skb(skb); sk_acceptq_removed(sk); out_release: release_sock(sk); return err; } static int nr_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddr_len, int peer) { struct full_sockaddr_ax25 *sax = (struct full_sockaddr_ax25 *)uaddr; struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); lock_sock(sk); if (peer != 0) { if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 1; sax->fsa_ax25.sax25_call = nr->user_addr; memset(sax->fsa_digipeater, 0, sizeof(sax->fsa_digipeater)); sax->fsa_digipeater[0] = nr->dest_addr; *uaddr_len = sizeof(struct full_sockaddr_ax25); } else { sax->fsa_ax25.sax25_family = AF_NETROM; sax->fsa_ax25.sax25_ndigis = 0; sax->fsa_ax25.sax25_call = nr->source_addr; *uaddr_len = sizeof(struct sockaddr_ax25); } release_sock(sk); return 0; } int nr_rx_frame(struct sk_buff *skb, struct net_device *dev) { struct sock *sk; struct sock *make; struct nr_sock *nr_make; ax25_address *src, *dest, *user; unsigned short circuit_index, circuit_id; unsigned short peer_circuit_index, peer_circuit_id; unsigned short frametype, flags, window, timeout; int ret; skb->sk = NULL; /* Initially we don't know who it's for */ /* * skb->data points to the netrom frame start */ src = (ax25_address *)(skb->data + 0); dest = (ax25_address *)(skb->data + 7); circuit_index = skb->data[15]; circuit_id = skb->data[16]; peer_circuit_index = skb->data[17]; peer_circuit_id = skb->data[18]; frametype = skb->data[19] & 0x0F; flags = skb->data[19] & 0xF0; /* * Check for an incoming IP over NET/ROM frame. */ if (frametype == NR_PROTOEXT && circuit_index == NR_PROTO_IP && circuit_id == NR_PROTO_IP) { skb_pull(skb, NR_NETWORK_LEN + NR_TRANSPORT_LEN); skb_reset_transport_header(skb); return nr_rx_ip(skb, dev); } /* * Find an existing socket connection, based on circuit ID, if it's * a Connect Request base it on their circuit ID. * * Circuit ID 0/0 is not valid but it could still be a "reset" for a * circuit that no longer exists at the other end ... */ sk = NULL; if (circuit_index == 0 && circuit_id == 0) { if (frametype == NR_CONNACK && flags == NR_CHOKE_FLAG) sk = nr_find_peer(peer_circuit_index, peer_circuit_id, src); } else { if (frametype == NR_CONNREQ) sk = nr_find_peer(circuit_index, circuit_id, src); else sk = nr_find_socket(circuit_index, circuit_id); } if (sk != NULL) { skb_reset_transport_header(skb); if (frametype == NR_CONNACK && skb->len == 22) nr_sk(sk)->bpqext = 1; else nr_sk(sk)->bpqext = 0; ret = nr_process_rx_frame(sk, skb); bh_unlock_sock(sk); return ret; } /* * Now it should be a CONNREQ. */ if (frametype != NR_CONNREQ) { /* * Here it would be nice to be able to send a reset but * NET/ROM doesn't have one. We've tried to extend the protocol * by sending NR_CONNACK | NR_CHOKE_FLAGS replies but that * apparently kills BPQ boxes... :-( * So now we try to follow the established behaviour of * G8PZT's Xrouter which is sending packets with command type 7 * as an extension of the protocol. */ if (sysctl_netrom_reset_circuit && (frametype != NR_RESET || flags != 0)) nr_transmit_reset(skb, 1); return 0; } sk = nr_find_listener(dest); user = (ax25_address *)(skb->data + 21); if (sk == NULL || sk_acceptq_is_full(sk) || (make = nr_make_new(sk)) == NULL) { nr_transmit_refusal(skb, 0); if (sk) bh_unlock_sock(sk); return 0; } window = skb->data[20]; skb->sk = make; make->sk_state = TCP_ESTABLISHED; /* Fill in his circuit details */ nr_make = nr_sk(make); nr_make->source_addr = *dest; nr_make->dest_addr = *src; nr_make->user_addr = *user; nr_make->your_index = circuit_index; nr_make->your_id = circuit_id; bh_unlock_sock(sk); circuit = nr_find_next_circuit(); bh_lock_sock(sk); nr_make->my_index = circuit / 256; nr_make->my_id = circuit % 256; circuit++; /* Window negotiation */ if (window < nr_make->window) nr_make->window = window; /* L4 timeout negotiation */ if (skb->len == 37) { timeout = skb->data[36] * 256 + skb->data[35]; if (timeout * HZ < nr_make->t1) nr_make->t1 = timeout * HZ; nr_make->bpqext = 1; } else { nr_make->bpqext = 0; } nr_write_internal(make, NR_CONNACK); nr_make->condition = 0x00; nr_make->vs = 0; nr_make->va = 0; nr_make->vr = 0; nr_make->vl = 0; nr_make->state = NR_STATE_3; sk_acceptq_added(sk); skb_queue_head(&sk->sk_receive_queue, skb); if (!sock_flag(sk, SOCK_DEAD)) sk->sk_data_ready(sk, skb->len); bh_unlock_sock(sk); nr_insert_socket(make); nr_start_heartbeat(make); nr_start_idletimer(make); return 1; } static int nr_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct nr_sock *nr = nr_sk(sk); struct sockaddr_ax25 *usax = (struct sockaddr_ax25 *)msg->msg_name; int err; struct sockaddr_ax25 sax; struct sk_buff *skb; unsigned char *asmptr; int size; if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_EOR|MSG_CMSG_COMPAT)) return -EINVAL; lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) { err = -EADDRNOTAVAIL; goto out; } if (sk->sk_shutdown & SEND_SHUTDOWN) { send_sig(SIGPIPE, current, 0); err = -EPIPE; goto out; } if (nr->device == NULL) { err = -ENETUNREACH; goto out; } if (usax) { if (msg->msg_namelen < sizeof(sax)) { err = -EINVAL; goto out; } sax = *usax; if (ax25cmp(&nr->dest_addr, &sax.sax25_call) != 0) { err = -EISCONN; goto out; } if (sax.sax25_family != AF_NETROM) { err = -EINVAL; goto out; } } else { if (sk->sk_state != TCP_ESTABLISHED) { err = -ENOTCONN; goto out; } sax.sax25_family = AF_NETROM; sax.sax25_call = nr->dest_addr; } /* Build a packet - the conventional user limit is 236 bytes. We can do ludicrously large NetROM frames but must not overflow */ if (len > 65536) { err = -EMSGSIZE; goto out; } size = len + NR_NETWORK_LEN + NR_TRANSPORT_LEN; if ((skb = sock_alloc_send_skb(sk, size, msg->msg_flags & MSG_DONTWAIT, &err)) == NULL) goto out; skb_reserve(skb, size - len); skb_reset_transport_header(skb); /* * Push down the NET/ROM header */ asmptr = skb_push(skb, NR_TRANSPORT_LEN); /* Build a NET/ROM Transport header */ *asmptr++ = nr->your_index; *asmptr++ = nr->your_id; *asmptr++ = 0; /* To be filled in later */ *asmptr++ = 0; /* Ditto */ *asmptr++ = NR_INFO; /* * Put the data on the end */ skb_put(skb, len); /* User data follows immediately after the NET/ROM transport header */ if (memcpy_fromiovec(skb_transport_header(skb), msg->msg_iov, len)) { kfree_skb(skb); err = -EFAULT; goto out; } if (sk->sk_state != TCP_ESTABLISHED) { kfree_skb(skb); err = -ENOTCONN; goto out; } nr_output(sk, skb); /* Shove it onto the queue */ err = len; out: release_sock(sk); return err; } static int nr_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t size, int flags) { struct sock *sk = sock->sk; struct sockaddr_ax25 *sax = (struct sockaddr_ax25 *)msg->msg_name; size_t copied; struct sk_buff *skb; int er; /* * This works for seqpacket too. The receiver has ordered the queue for * us! We do one quick check first though */ lock_sock(sk); if (sk->sk_state != TCP_ESTABLISHED) { release_sock(sk); return -ENOTCONN; } /* Now we can treat all alike */ if ((skb = skb_recv_datagram(sk, flags & ~MSG_DONTWAIT, flags & MSG_DONTWAIT, &er)) == NULL) { release_sock(sk); return er; } skb_reset_transport_header(skb); copied = skb->len; if (copied > size) { copied = size; msg->msg_flags |= MSG_TRUNC; } er = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); if (er < 0) { skb_free_datagram(sk, skb); release_sock(sk); return er; } if (sax != NULL) { sax->sax25_family = AF_NETROM; skb_copy_from_linear_data_offset(skb, 7, sax->sax25_call.ax25_call, AX25_ADDR_LEN); } msg->msg_namelen = sizeof(*sax); skb_free_datagram(sk, skb); release_sock(sk); return copied; } static int nr_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; void __user *argp = (void __user *)arg; int ret; switch (cmd) { case TIOCOUTQ: { long amount; lock_sock(sk); amount = sk->sk_sndbuf - sk_wmem_alloc_get(sk); if (amount < 0) amount = 0; release_sock(sk); return put_user(amount, (int __user *)argp); } case TIOCINQ: { struct sk_buff *skb; long amount = 0L; lock_sock(sk); /* These two are safe on a single CPU system as only user tasks fiddle here */ if ((skb = skb_peek(&sk->sk_receive_queue)) != NULL) amount = skb->len; release_sock(sk); return put_user(amount, (int __user *)argp); } case SIOCGSTAMP: lock_sock(sk); ret = sock_get_timestamp(sk, argp); release_sock(sk); return ret; case SIOCGSTAMPNS: lock_sock(sk); ret = sock_get_timestampns(sk, argp); release_sock(sk); return ret; case SIOCGIFADDR: case SIOCSIFADDR: case SIOCGIFDSTADDR: case SIOCSIFDSTADDR: case SIOCGIFBRDADDR: case SIOCSIFBRDADDR: case SIOCGIFNETMASK: case SIOCSIFNETMASK: case SIOCGIFMETRIC: case SIOCSIFMETRIC: return -EINVAL; case SIOCADDRT: case SIOCDELRT: case SIOCNRDECOBS: if (!capable(CAP_NET_ADMIN)) return -EPERM; return nr_rt_ioctl(cmd, argp); default: return -ENOIOCTLCMD; } return 0; } #ifdef CONFIG_PROC_FS static void *nr_info_start(struct seq_file *seq, loff_t *pos) { spin_lock_bh(&nr_list_lock); return seq_hlist_start_head(&nr_list, *pos); } static void *nr_info_next(struct seq_file *seq, void *v, loff_t *pos) { return seq_hlist_next(v, &nr_list, pos); } static void nr_info_stop(struct seq_file *seq, void *v) { spin_unlock_bh(&nr_list_lock); } static int nr_info_show(struct seq_file *seq, void *v) { struct sock *s = sk_entry(v); struct net_device *dev; struct nr_sock *nr; const char *devname; char buf[11]; if (v == SEQ_START_TOKEN) seq_puts(seq, "user_addr dest_node src_node dev my your st vs vr va t1 t2 t4 idle n2 wnd Snd-Q Rcv-Q inode\n"); else { bh_lock_sock(s); nr = nr_sk(s); if ((dev = nr->device) == NULL) devname = "???"; else devname = dev->name; seq_printf(seq, "%-9s ", ax2asc(buf, &nr->user_addr)); seq_printf(seq, "%-9s ", ax2asc(buf, &nr->dest_addr)); seq_printf(seq, "%-9s %-3s %02X/%02X %02X/%02X %2d %3d %3d %3d %3lu/%03lu %2lu/%02lu %3lu/%03lu %3lu/%03lu %2d/%02d %3d %5d %5d %ld\n", ax2asc(buf, &nr->source_addr), devname, nr->my_index, nr->my_id, nr->your_index, nr->your_id, nr->state, nr->vs, nr->vr, nr->va, ax25_display_timer(&nr->t1timer) / HZ, nr->t1 / HZ, ax25_display_timer(&nr->t2timer) / HZ, nr->t2 / HZ, ax25_display_timer(&nr->t4timer) / HZ, nr->t4 / HZ, ax25_display_timer(&nr->idletimer) / (60 * HZ), nr->idle / (60 * HZ), nr->n2count, nr->n2, nr->window, sk_wmem_alloc_get(s), sk_rmem_alloc_get(s), s->sk_socket ? SOCK_INODE(s->sk_socket)->i_ino : 0L); bh_unlock_sock(s); } return 0; } static const struct seq_operations nr_info_seqops = { .start = nr_info_start, .next = nr_info_next, .stop = nr_info_stop, .show = nr_info_show, }; static int nr_info_open(struct inode *inode, struct file *file) { return seq_open(file, &nr_info_seqops); } static const struct file_operations nr_info_fops = { .owner = THIS_MODULE, .open = nr_info_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; #endif /* CONFIG_PROC_FS */ static const struct net_proto_family nr_family_ops = { .family = PF_NETROM, .create = nr_create, .owner = THIS_MODULE, }; static const struct proto_ops nr_proto_ops = { .family = PF_NETROM, .owner = THIS_MODULE, .release = nr_release, .bind = nr_bind, .connect = nr_connect, .socketpair = sock_no_socketpair, .accept = nr_accept, .getname = nr_getname, .poll = datagram_poll, .ioctl = nr_ioctl, .listen = nr_listen, .shutdown = sock_no_shutdown, .setsockopt = nr_setsockopt, .getsockopt = nr_getsockopt, .sendmsg = nr_sendmsg, .recvmsg = nr_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static struct notifier_block nr_dev_notifier = { .notifier_call = nr_device_event, }; static struct net_device **dev_nr; static struct ax25_protocol nr_pid = { .pid = AX25_P_NETROM, .func = nr_route_frame }; static struct ax25_linkfail nr_linkfail_notifier = { .func = nr_link_failed, }; static int __init nr_proto_init(void) { int i; int rc = proto_register(&nr_proto, 0); if (rc != 0) goto out; if (nr_ndevs > 0x7fffffff/sizeof(struct net_device *)) { printk(KERN_ERR "NET/ROM: nr_proto_init - nr_ndevs parameter to large\n"); return -1; } dev_nr = kzalloc(nr_ndevs * sizeof(struct net_device *), GFP_KERNEL); if (dev_nr == NULL) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to allocate device array\n"); return -1; } for (i = 0; i < nr_ndevs; i++) { char name[IFNAMSIZ]; struct net_device *dev; sprintf(name, "nr%d", i); dev = alloc_netdev(0, name, nr_setup); if (!dev) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to allocate device structure\n"); goto fail; } dev->base_addr = i; if (register_netdev(dev)) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to register network device\n"); free_netdev(dev); goto fail; } nr_set_lockdep_key(dev); dev_nr[i] = dev; } if (sock_register(&nr_family_ops)) { printk(KERN_ERR "NET/ROM: nr_proto_init - unable to register socket family\n"); goto fail; } register_netdevice_notifier(&nr_dev_notifier); ax25_register_pid(&nr_pid); ax25_linkfail_register(&nr_linkfail_notifier); #ifdef CONFIG_SYSCTL nr_register_sysctl(); #endif nr_loopback_init(); proc_create("nr", S_IRUGO, init_net.proc_net, &nr_info_fops); proc_create("nr_neigh", S_IRUGO, init_net.proc_net, &nr_neigh_fops); proc_create("nr_nodes", S_IRUGO, init_net.proc_net, &nr_nodes_fops); out: return rc; fail: while (--i >= 0) { unregister_netdev(dev_nr[i]); free_netdev(dev_nr[i]); } kfree(dev_nr); proto_unregister(&nr_proto); rc = -1; goto out; } module_init(nr_proto_init); module_param(nr_ndevs, int, 0); MODULE_PARM_DESC(nr_ndevs, "number of NET/ROM devices"); MODULE_AUTHOR("Jonathan Naylor G4KLX <g4klx@g4klx.demon.co.uk>"); MODULE_DESCRIPTION("The amateur radio NET/ROM network and transport layer protocol"); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_NETROM); static void __exit nr_exit(void) { int i; remove_proc_entry("nr", init_net.proc_net); remove_proc_entry("nr_neigh", init_net.proc_net); remove_proc_entry("nr_nodes", init_net.proc_net); nr_loopback_clear(); nr_rt_free(); #ifdef CONFIG_SYSCTL nr_unregister_sysctl(); #endif ax25_linkfail_release(&nr_linkfail_notifier); ax25_protocol_release(AX25_P_NETROM); unregister_netdevice_notifier(&nr_dev_notifier); sock_unregister(PF_NETROM); for (i = 0; i < nr_ndevs; i++) { struct net_device *dev = dev_nr[i]; if (dev) { unregister_netdev(dev); free_netdev(dev); } } kfree(dev_nr); proto_unregister(&nr_proto); } module_exit(nr_exit);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5691_0
crossvul-cpp_data_good_5690_0
/* * af_llc.c - LLC User Interface SAPs * Description: * Functions in this module are implementation of socket based llc * communications for the Linux operating system. Support of llc class * one and class two is provided via SOCK_DGRAM and SOCK_STREAM * respectively. * * An llc2 connection is (mac + sap), only one llc2 sap connection * is allowed per mac. Though one sap may have multiple mac + sap * connections. * * Copyright (c) 2001 by Jay Schulist <jschlst@samba.org> * 2002-2003 by Arnaldo Carvalho de Melo <acme@conectiva.com.br> * * This program can be redistributed or modified under the terms of the * GNU General Public License as published by the Free Software Foundation. * This program is distributed without any warranty or implied warranty * of merchantability or fitness for a particular purpose. * * See the GNU General Public License for more details. */ #include <linux/compiler.h> #include <linux/kernel.h> #include <linux/module.h> #include <linux/rtnetlink.h> #include <linux/init.h> #include <linux/slab.h> #include <net/llc.h> #include <net/llc_sap.h> #include <net/llc_pdu.h> #include <net/llc_conn.h> #include <net/tcp_states.h> /* remember: uninitialized global data is zeroed because its in .bss */ static u16 llc_ui_sap_last_autoport = LLC_SAP_DYN_START; static u16 llc_ui_sap_link_no_max[256]; static struct sockaddr_llc llc_ui_addrnull; static const struct proto_ops llc_ui_ops; static int llc_ui_wait_for_conn(struct sock *sk, long timeout); static int llc_ui_wait_for_disc(struct sock *sk, long timeout); static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout); #if 0 #define dprintk(args...) printk(KERN_DEBUG args) #else #define dprintk(args...) #endif /* Maybe we'll add some more in the future. */ #define LLC_CMSG_PKTINFO 1 /** * llc_ui_next_link_no - return the next unused link number for a sap * @sap: Address of sap to get link number from. * * Return the next unused link number for a given sap. */ static inline u16 llc_ui_next_link_no(int sap) { return llc_ui_sap_link_no_max[sap]++; } /** * llc_proto_type - return eth protocol for ARP header type * @arphrd: ARP header type. * * Given an ARP header type return the corresponding ethernet protocol. */ static inline __be16 llc_proto_type(u16 arphrd) { return htons(ETH_P_802_2); } /** * llc_ui_addr_null - determines if a address structure is null * @addr: Address to test if null. */ static inline u8 llc_ui_addr_null(struct sockaddr_llc *addr) { return !memcmp(addr, &llc_ui_addrnull, sizeof(*addr)); } /** * llc_ui_header_len - return length of llc header based on operation * @sk: Socket which contains a valid llc socket type. * @addr: Complete sockaddr_llc structure received from the user. * * Provide the length of the llc header depending on what kind of * operation the user would like to perform and the type of socket. * Returns the correct llc header length. */ static inline u8 llc_ui_header_len(struct sock *sk, struct sockaddr_llc *addr) { u8 rc = LLC_PDU_LEN_U; if (addr->sllc_test || addr->sllc_xid) rc = LLC_PDU_LEN_U; else if (sk->sk_type == SOCK_STREAM) rc = LLC_PDU_LEN_I; return rc; } /** * llc_ui_send_data - send data via reliable llc2 connection * @sk: Connection the socket is using. * @skb: Data the user wishes to send. * @noblock: can we block waiting for data? * * Send data via reliable llc2 connection. * Returns 0 upon success, non-zero if action did not succeed. */ static int llc_ui_send_data(struct sock* sk, struct sk_buff *skb, int noblock) { struct llc_sock* llc = llc_sk(sk); int rc = 0; if (unlikely(llc_data_accept_state(llc->state) || llc->remote_busy_flag || llc->p_flag)) { long timeout = sock_sndtimeo(sk, noblock); rc = llc_ui_wait_for_busy_core(sk, timeout); } if (unlikely(!rc)) rc = llc_build_and_send_pkt(sk, skb); return rc; } static void llc_ui_sk_init(struct socket *sock, struct sock *sk) { sock_graft(sk, sock); sk->sk_type = sock->type; sock->ops = &llc_ui_ops; } static struct proto llc_proto = { .name = "LLC", .owner = THIS_MODULE, .obj_size = sizeof(struct llc_sock), .slab_flags = SLAB_DESTROY_BY_RCU, }; /** * llc_ui_create - alloc and init a new llc_ui socket * @net: network namespace (must be default network) * @sock: Socket to initialize and attach allocated sk to. * @protocol: Unused. * @kern: on behalf of kernel or userspace * * Allocate and initialize a new llc_ui socket, validate the user wants a * socket type we have available. * Returns 0 upon success, negative upon failure. */ static int llc_ui_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; int rc = -ESOCKTNOSUPPORT; if (!ns_capable(net->user_ns, CAP_NET_RAW)) return -EPERM; if (!net_eq(net, &init_net)) return -EAFNOSUPPORT; if (likely(sock->type == SOCK_DGRAM || sock->type == SOCK_STREAM)) { rc = -ENOMEM; sk = llc_sk_alloc(net, PF_LLC, GFP_KERNEL, &llc_proto); if (sk) { rc = 0; llc_ui_sk_init(sock, sk); } } return rc; } /** * llc_ui_release - shutdown socket * @sock: Socket to release. * * Shutdown and deallocate an existing socket. */ static int llc_ui_release(struct socket *sock) { struct sock *sk = sock->sk; struct llc_sock *llc; if (unlikely(sk == NULL)) goto out; sock_hold(sk); lock_sock(sk); llc = llc_sk(sk); dprintk("%s: closing local(%02X) remote(%02X)\n", __func__, llc->laddr.lsap, llc->daddr.lsap); if (!llc_send_disc(sk)) llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo); if (!sock_flag(sk, SOCK_ZAPPED)) llc_sap_remove_socket(llc->sap, sk); release_sock(sk); if (llc->dev) dev_put(llc->dev); sock_put(sk); llc_sk_free(sk); out: return 0; } /** * llc_ui_autoport - provide dynamically allocate SAP number * * Provide the caller with a dynamically allocated SAP number according * to the rules that are set in this function. Returns: 0, upon failure, * SAP number otherwise. */ static int llc_ui_autoport(void) { struct llc_sap *sap; int i, tries = 0; while (tries < LLC_SAP_DYN_TRIES) { for (i = llc_ui_sap_last_autoport; i < LLC_SAP_DYN_STOP; i += 2) { sap = llc_sap_find(i); if (!sap) { llc_ui_sap_last_autoport = i + 2; goto out; } llc_sap_put(sap); } llc_ui_sap_last_autoport = LLC_SAP_DYN_START; tries++; } i = 0; out: return i; } /** * llc_ui_autobind - automatically bind a socket to a sap * @sock: socket to bind * @addr: address to connect to * * Used by llc_ui_connect and llc_ui_sendmsg when the user hasn't * specifically used llc_ui_bind to bind to an specific address/sap * * Returns: 0 upon success, negative otherwise. */ static int llc_ui_autobind(struct socket *sock, struct sockaddr_llc *addr) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct llc_sap *sap; int rc = -EINVAL; if (!sock_flag(sk, SOCK_ZAPPED)) goto out; rc = -ENODEV; if (sk->sk_bound_dev_if) { llc->dev = dev_get_by_index(&init_net, sk->sk_bound_dev_if); if (llc->dev && addr->sllc_arphrd != llc->dev->type) { dev_put(llc->dev); llc->dev = NULL; } } else llc->dev = dev_getfirstbyhwtype(&init_net, addr->sllc_arphrd); if (!llc->dev) goto out; rc = -EUSERS; llc->laddr.lsap = llc_ui_autoport(); if (!llc->laddr.lsap) goto out; rc = -EBUSY; /* some other network layer is using the sap */ sap = llc_sap_open(llc->laddr.lsap, NULL); if (!sap) goto out; memcpy(llc->laddr.mac, llc->dev->dev_addr, IFHWADDRLEN); memcpy(&llc->addr, addr, sizeof(llc->addr)); /* assign new connection to its SAP */ llc_sap_add_socket(sap, sk); sock_reset_flag(sk, SOCK_ZAPPED); rc = 0; out: return rc; } /** * llc_ui_bind - bind a socket to a specific address. * @sock: Socket to bind an address to. * @uaddr: Address the user wants the socket bound to. * @addrlen: Length of the uaddr structure. * * Bind a socket to a specific address. For llc a user is able to bind to * a specific sap only or mac + sap. * If the user desires to bind to a specific mac + sap, it is possible to * have multiple sap connections via multiple macs. * Bind and autobind for that matter must enforce the correct sap usage * otherwise all hell will break loose. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_bind(struct socket *sock, struct sockaddr *uaddr, int addrlen) { struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct llc_sap *sap; int rc = -EINVAL; dprintk("%s: binding %02X\n", __func__, addr->sllc_sap); if (unlikely(!sock_flag(sk, SOCK_ZAPPED) || addrlen != sizeof(*addr))) goto out; rc = -EAFNOSUPPORT; if (unlikely(addr->sllc_family != AF_LLC)) goto out; rc = -ENODEV; rcu_read_lock(); if (sk->sk_bound_dev_if) { llc->dev = dev_get_by_index_rcu(&init_net, sk->sk_bound_dev_if); if (llc->dev) { if (!addr->sllc_arphrd) addr->sllc_arphrd = llc->dev->type; if (llc_mac_null(addr->sllc_mac)) memcpy(addr->sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); if (addr->sllc_arphrd != llc->dev->type || !llc_mac_match(addr->sllc_mac, llc->dev->dev_addr)) { rc = -EINVAL; llc->dev = NULL; } } } else llc->dev = dev_getbyhwaddr_rcu(&init_net, addr->sllc_arphrd, addr->sllc_mac); if (llc->dev) dev_hold(llc->dev); rcu_read_unlock(); if (!llc->dev) goto out; if (!addr->sllc_sap) { rc = -EUSERS; addr->sllc_sap = llc_ui_autoport(); if (!addr->sllc_sap) goto out; } sap = llc_sap_find(addr->sllc_sap); if (!sap) { sap = llc_sap_open(addr->sllc_sap, NULL); rc = -EBUSY; /* some other network layer is using the sap */ if (!sap) goto out; } else { struct llc_addr laddr, daddr; struct sock *ask; memset(&laddr, 0, sizeof(laddr)); memset(&daddr, 0, sizeof(daddr)); /* * FIXME: check if the address is multicast, * only SOCK_DGRAM can do this. */ memcpy(laddr.mac, addr->sllc_mac, IFHWADDRLEN); laddr.lsap = addr->sllc_sap; rc = -EADDRINUSE; /* mac + sap clash. */ ask = llc_lookup_established(sap, &daddr, &laddr); if (ask) { sock_put(ask); goto out_put; } } llc->laddr.lsap = addr->sllc_sap; memcpy(llc->laddr.mac, addr->sllc_mac, IFHWADDRLEN); memcpy(&llc->addr, addr, sizeof(llc->addr)); /* assign new connection to its SAP */ llc_sap_add_socket(sap, sk); sock_reset_flag(sk, SOCK_ZAPPED); rc = 0; out_put: llc_sap_put(sap); out: return rc; } /** * llc_ui_shutdown - shutdown a connect llc2 socket. * @sock: Socket to shutdown. * @how: What part of the socket to shutdown. * * Shutdown a connected llc2 socket. Currently this function only supports * shutting down both sends and receives (2), we could probably make this * function such that a user can shutdown only half the connection but not * right now. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; int rc = -ENOTCONN; lock_sock(sk); if (unlikely(sk->sk_state != TCP_ESTABLISHED)) goto out; rc = -EINVAL; if (how != 2) goto out; rc = llc_send_disc(sk); if (!rc) rc = llc_ui_wait_for_disc(sk, sk->sk_rcvtimeo); /* Wake up anyone sleeping in poll */ sk->sk_state_change(sk); out: release_sock(sk); return rc; } /** * llc_ui_connect - Connect to a remote llc2 mac + sap. * @sock: Socket which will be connected to the remote destination. * @uaddr: Remote and possibly the local address of the new connection. * @addrlen: Size of uaddr structure. * @flags: Operational flags specified by the user. * * Connect to a remote llc2 mac + sap. The caller must specify the * destination mac and address to connect to. If the user hasn't previously * called bind(2) with a smac the address of the first interface of the * specified arp type will be used. * This function will autobind if user did not previously call bind. * Returns: 0 upon success, negative otherwise. */ static int llc_ui_connect(struct socket *sock, struct sockaddr *uaddr, int addrlen, int flags) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct sockaddr_llc *addr = (struct sockaddr_llc *)uaddr; int rc = -EINVAL; lock_sock(sk); if (unlikely(addrlen != sizeof(*addr))) goto out; rc = -EAFNOSUPPORT; if (unlikely(addr->sllc_family != AF_LLC)) goto out; if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EALREADY; if (unlikely(sock->state == SS_CONNECTING)) goto out; /* bind connection to sap if user hasn't done it. */ if (sock_flag(sk, SOCK_ZAPPED)) { /* bind to sap with null dev, exclusive */ rc = llc_ui_autobind(sock, addr); if (rc) goto out; } llc->daddr.lsap = addr->sllc_sap; memcpy(llc->daddr.mac, addr->sllc_mac, IFHWADDRLEN); sock->state = SS_CONNECTING; sk->sk_state = TCP_SYN_SENT; llc->link = llc_ui_next_link_no(llc->sap->laddr.lsap); rc = llc_establish_connection(sk, llc->dev->dev_addr, addr->sllc_mac, addr->sllc_sap); if (rc) { dprintk("%s: llc_ui_send_conn failed :-(\n", __func__); sock->state = SS_UNCONNECTED; sk->sk_state = TCP_CLOSE; goto out; } if (sk->sk_state == TCP_SYN_SENT) { const long timeo = sock_sndtimeo(sk, flags & O_NONBLOCK); if (!timeo || !llc_ui_wait_for_conn(sk, timeo)) goto out; rc = sock_intr_errno(timeo); if (signal_pending(current)) goto out; } if (sk->sk_state == TCP_CLOSE) goto sock_error; sock->state = SS_CONNECTED; rc = 0; out: release_sock(sk); return rc; sock_error: rc = sock_error(sk) ? : -ECONNABORTED; sock->state = SS_UNCONNECTED; goto out; } /** * llc_ui_listen - allow a normal socket to accept incoming connections * @sock: Socket to allow incoming connections on. * @backlog: Number of connections to queue. * * Allow a normal socket to accept incoming connections. * Returns 0 upon success, negative otherwise. */ static int llc_ui_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int rc = -EINVAL; lock_sock(sk); if (unlikely(sock->state != SS_UNCONNECTED)) goto out; rc = -EOPNOTSUPP; if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EAGAIN; if (sock_flag(sk, SOCK_ZAPPED)) goto out; rc = 0; if (!(unsigned int)backlog) /* BSDism */ backlog = 1; sk->sk_max_ack_backlog = backlog; if (sk->sk_state != TCP_LISTEN) { sk->sk_ack_backlog = 0; sk->sk_state = TCP_LISTEN; } sk->sk_socket->flags |= __SO_ACCEPTCON; out: release_sock(sk); return rc; } static int llc_ui_wait_for_disc(struct sock *sk, long timeout) { DEFINE_WAIT(wait); int rc = 0; while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk_wait_event(sk, &timeout, sk->sk_state == TCP_CLOSE)) break; rc = -ERESTARTSYS; if (signal_pending(current)) break; rc = -EAGAIN; if (!timeout) break; rc = 0; } finish_wait(sk_sleep(sk), &wait); return rc; } static int llc_ui_wait_for_conn(struct sock *sk, long timeout) { DEFINE_WAIT(wait); while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); if (sk_wait_event(sk, &timeout, sk->sk_state != TCP_SYN_SENT)) break; if (signal_pending(current) || !timeout) break; } finish_wait(sk_sleep(sk), &wait); return timeout; } static int llc_ui_wait_for_busy_core(struct sock *sk, long timeout) { DEFINE_WAIT(wait); struct llc_sock *llc = llc_sk(sk); int rc; while (1) { prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE); rc = 0; if (sk_wait_event(sk, &timeout, (sk->sk_shutdown & RCV_SHUTDOWN) || (!llc_data_accept_state(llc->state) && !llc->remote_busy_flag && !llc->p_flag))) break; rc = -ERESTARTSYS; if (signal_pending(current)) break; rc = -EAGAIN; if (!timeout) break; } finish_wait(sk_sleep(sk), &wait); return rc; } static int llc_wait_data(struct sock *sk, long timeo) { int rc; while (1) { /* * POSIX 1003.1g mandates this order. */ rc = sock_error(sk); if (rc) break; rc = 0; if (sk->sk_shutdown & RCV_SHUTDOWN) break; rc = -EAGAIN; if (!timeo) break; rc = sock_intr_errno(timeo); if (signal_pending(current)) break; rc = 0; if (sk_wait_data(sk, &timeo)) break; } return rc; } static void llc_cmsg_rcv(struct msghdr *msg, struct sk_buff *skb) { struct llc_sock *llc = llc_sk(skb->sk); if (llc->cmsg_flags & LLC_CMSG_PKTINFO) { struct llc_pktinfo info; info.lpi_ifindex = llc_sk(skb->sk)->dev->ifindex; llc_pdu_decode_dsap(skb, &info.lpi_sap); llc_pdu_decode_da(skb, info.lpi_mac); put_cmsg(msg, SOL_LLC, LLC_OPT_PKTINFO, sizeof(info), &info); } } /** * llc_ui_accept - accept a new incoming connection. * @sock: Socket which connections arrive on. * @newsock: Socket to move incoming connection to. * @flags: User specified operational flags. * * Accept a new incoming connection. * Returns 0 upon success, negative otherwise. */ static int llc_ui_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk, *newsk; struct llc_sock *llc, *newllc; struct sk_buff *skb; int rc = -EOPNOTSUPP; dprintk("%s: accepting on %02X\n", __func__, llc_sk(sk)->laddr.lsap); lock_sock(sk); if (unlikely(sk->sk_type != SOCK_STREAM)) goto out; rc = -EINVAL; if (unlikely(sock->state != SS_UNCONNECTED || sk->sk_state != TCP_LISTEN)) goto out; /* wait for a connection to arrive. */ if (skb_queue_empty(&sk->sk_receive_queue)) { rc = llc_wait_data(sk, sk->sk_rcvtimeo); if (rc) goto out; } dprintk("%s: got a new connection on %02X\n", __func__, llc_sk(sk)->laddr.lsap); skb = skb_dequeue(&sk->sk_receive_queue); rc = -EINVAL; if (!skb->sk) goto frees; rc = 0; newsk = skb->sk; /* attach connection to a new socket. */ llc_ui_sk_init(newsock, newsk); sock_reset_flag(newsk, SOCK_ZAPPED); newsk->sk_state = TCP_ESTABLISHED; newsock->state = SS_CONNECTED; llc = llc_sk(sk); newllc = llc_sk(newsk); memcpy(&newllc->addr, &llc->addr, sizeof(newllc->addr)); newllc->link = llc_ui_next_link_no(newllc->laddr.lsap); /* put original socket back into a clean listen state. */ sk->sk_state = TCP_LISTEN; sk->sk_ack_backlog--; dprintk("%s: ok success on %02X, client on %02X\n", __func__, llc_sk(sk)->addr.sllc_sap, newllc->daddr.lsap); frees: kfree_skb(skb); out: release_sock(sk); return rc; } /** * llc_ui_recvmsg - copy received data to the socket user. * @sock: Socket to copy data from. * @msg: Various user space related information. * @len: Size of user buffer. * @flags: User specified flags. * * Copy received data to the socket user. * Returns non-negative upon success, negative otherwise. */ static int llc_ui_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sockaddr_llc *uaddr = (struct sockaddr_llc *)msg->msg_name; const int nonblock = flags & MSG_DONTWAIT; struct sk_buff *skb = NULL; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned long cpu_flags; size_t copied = 0; u32 peek_seq = 0; u32 *seq; unsigned long used; int target; /* Read at least this many bytes */ long timeo; msg->msg_namelen = 0; lock_sock(sk); copied = -ENOTCONN; if (unlikely(sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_LISTEN)) goto out; timeo = sock_rcvtimeo(sk, nonblock); seq = &llc->copied_seq; if (flags & MSG_PEEK) { peek_seq = llc->copied_seq; seq = &peek_seq; } target = sock_rcvlowat(sk, flags & MSG_WAITALL, len); copied = 0; do { u32 offset; /* * We need to check signals first, to get correct SIGURG * handling. FIXME: Need to check this doesn't impact 1003.1g * and move it down to the bottom of the loop */ if (signal_pending(current)) { if (copied) break; copied = timeo ? sock_intr_errno(timeo) : -EAGAIN; break; } /* Next get a buffer. */ skb = skb_peek(&sk->sk_receive_queue); if (skb) { offset = *seq; goto found_ok_skb; } /* Well, if we have backlog, try to process it now yet. */ if (copied >= target && !sk->sk_backlog.tail) break; if (copied) { if (sk->sk_err || sk->sk_state == TCP_CLOSE || (sk->sk_shutdown & RCV_SHUTDOWN) || !timeo || (flags & MSG_PEEK)) break; } else { if (sock_flag(sk, SOCK_DONE)) break; if (sk->sk_err) { copied = sock_error(sk); break; } if (sk->sk_shutdown & RCV_SHUTDOWN) break; if (sk->sk_type == SOCK_STREAM && sk->sk_state == TCP_CLOSE) { if (!sock_flag(sk, SOCK_DONE)) { /* * This occurs when user tries to read * from never connected socket. */ copied = -ENOTCONN; break; } break; } if (!timeo) { copied = -EAGAIN; break; } } if (copied >= target) { /* Do not sleep, just process backlog. */ release_sock(sk); lock_sock(sk); } else sk_wait_data(sk, &timeo); if ((flags & MSG_PEEK) && peek_seq != llc->copied_seq) { net_dbg_ratelimited("LLC(%s:%d): Application bug, race in MSG_PEEK\n", current->comm, task_pid_nr(current)); peek_seq = llc->copied_seq; } continue; found_ok_skb: /* Ok so how much can we use? */ used = skb->len - offset; if (len < used) used = len; if (!(flags & MSG_TRUNC)) { int rc = skb_copy_datagram_iovec(skb, offset, msg->msg_iov, used); if (rc) { /* Exception. Bailout! */ if (!copied) copied = -EFAULT; break; } } *seq += used; copied += used; len -= used; /* For non stream protcols we get one packet per recvmsg call */ if (sk->sk_type != SOCK_STREAM) goto copy_uaddr; if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } /* Partial read */ if (used + offset < skb->len) continue; } while (len > 0); out: release_sock(sk); return copied; copy_uaddr: if (uaddr != NULL && skb != NULL) { memcpy(uaddr, llc_ui_skb_cb(skb), sizeof(*uaddr)); msg->msg_namelen = sizeof(*uaddr); } if (llc_sk(sk)->cmsg_flags) llc_cmsg_rcv(msg, skb); if (!(flags & MSG_PEEK)) { spin_lock_irqsave(&sk->sk_receive_queue.lock, cpu_flags); sk_eat_skb(sk, skb, false); spin_unlock_irqrestore(&sk->sk_receive_queue.lock, cpu_flags); *seq = 0; } goto out; } /** * llc_ui_sendmsg - Transmit data provided by the socket user. * @sock: Socket to transmit data from. * @msg: Various user related information. * @len: Length of data to transmit. * * Transmit data provided by the socket user. * Returns non-negative upon success, negative otherwise. */ static int llc_ui_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); struct sockaddr_llc *addr = (struct sockaddr_llc *)msg->msg_name; int flags = msg->msg_flags; int noblock = flags & MSG_DONTWAIT; struct sk_buff *skb; size_t size = 0; int rc = -EINVAL, copied = 0, hdrlen; dprintk("%s: sending from %02X to %02X\n", __func__, llc->laddr.lsap, llc->daddr.lsap); lock_sock(sk); if (addr) { if (msg->msg_namelen < sizeof(*addr)) goto release; } else { if (llc_ui_addr_null(&llc->addr)) goto release; addr = &llc->addr; } /* must bind connection to sap if user hasn't done it. */ if (sock_flag(sk, SOCK_ZAPPED)) { /* bind to sap with null dev, exclusive. */ rc = llc_ui_autobind(sock, addr); if (rc) goto release; } hdrlen = llc->dev->hard_header_len + llc_ui_header_len(sk, addr); size = hdrlen + len; if (size > llc->dev->mtu) size = llc->dev->mtu; copied = size - hdrlen; release_sock(sk); skb = sock_alloc_send_skb(sk, size, noblock, &rc); lock_sock(sk); if (!skb) goto release; skb->dev = llc->dev; skb->protocol = llc_proto_type(addr->sllc_arphrd); skb_reserve(skb, hdrlen); rc = memcpy_fromiovec(skb_put(skb, copied), msg->msg_iov, copied); if (rc) goto out; if (sk->sk_type == SOCK_DGRAM || addr->sllc_ua) { llc_build_and_send_ui_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } if (addr->sllc_test) { llc_build_and_send_test_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } if (addr->sllc_xid) { llc_build_and_send_xid_pkt(llc->sap, skb, addr->sllc_mac, addr->sllc_sap); goto out; } rc = -ENOPROTOOPT; if (!(sk->sk_type == SOCK_STREAM && !addr->sllc_ua)) goto out; rc = llc_ui_send_data(sk, skb, noblock); out: if (rc) { kfree_skb(skb); release: dprintk("%s: failed sending from %02X to %02X: %d\n", __func__, llc->laddr.lsap, llc->daddr.lsap, rc); } release_sock(sk); return rc ? : copied; } /** * llc_ui_getname - return the address info of a socket * @sock: Socket to get address of. * @uaddr: Address structure to return information. * @uaddrlen: Length of address structure. * @peer: Does user want local or remote address information. * * Return the address information of a socket. */ static int llc_ui_getname(struct socket *sock, struct sockaddr *uaddr, int *uaddrlen, int peer) { struct sockaddr_llc sllc; struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int rc = -EBADF; memset(&sllc, 0, sizeof(sllc)); lock_sock(sk); if (sock_flag(sk, SOCK_ZAPPED)) goto out; *uaddrlen = sizeof(sllc); if (peer) { rc = -ENOTCONN; if (sk->sk_state != TCP_ESTABLISHED) goto out; if(llc->dev) sllc.sllc_arphrd = llc->dev->type; sllc.sllc_sap = llc->daddr.lsap; memcpy(&sllc.sllc_mac, &llc->daddr.mac, IFHWADDRLEN); } else { rc = -EINVAL; if (!llc->sap) goto out; sllc.sllc_sap = llc->sap->laddr.lsap; if (llc->dev) { sllc.sllc_arphrd = llc->dev->type; memcpy(&sllc.sllc_mac, llc->dev->dev_addr, IFHWADDRLEN); } } rc = 0; sllc.sllc_family = AF_LLC; memcpy(uaddr, &sllc, sizeof(sllc)); out: release_sock(sk); return rc; } /** * llc_ui_ioctl - io controls for PF_LLC * @sock: Socket to get/set info * @cmd: command * @arg: optional argument for cmd * * get/set info on llc sockets */ static int llc_ui_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { return -ENOIOCTLCMD; } /** * llc_ui_setsockopt - set various connection specific parameters. * @sock: Socket to set options on. * @level: Socket level user is requesting operations on. * @optname: Operation name. * @optval: User provided operation data. * @optlen: Length of optval. * * Set various connection specific parameters. */ static int llc_ui_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); unsigned int opt; int rc = -EINVAL; lock_sock(sk); if (unlikely(level != SOL_LLC || optlen != sizeof(int))) goto out; rc = get_user(opt, (int __user *)optval); if (rc) goto out; rc = -EINVAL; switch (optname) { case LLC_OPT_RETRY: if (opt > LLC_OPT_MAX_RETRY) goto out; llc->n2 = opt; break; case LLC_OPT_SIZE: if (opt > LLC_OPT_MAX_SIZE) goto out; llc->n1 = opt; break; case LLC_OPT_ACK_TMR_EXP: if (opt > LLC_OPT_MAX_ACK_TMR_EXP) goto out; llc->ack_timer.expire = opt * HZ; break; case LLC_OPT_P_TMR_EXP: if (opt > LLC_OPT_MAX_P_TMR_EXP) goto out; llc->pf_cycle_timer.expire = opt * HZ; break; case LLC_OPT_REJ_TMR_EXP: if (opt > LLC_OPT_MAX_REJ_TMR_EXP) goto out; llc->rej_sent_timer.expire = opt * HZ; break; case LLC_OPT_BUSY_TMR_EXP: if (opt > LLC_OPT_MAX_BUSY_TMR_EXP) goto out; llc->busy_state_timer.expire = opt * HZ; break; case LLC_OPT_TX_WIN: if (opt > LLC_OPT_MAX_WIN) goto out; llc->k = opt; break; case LLC_OPT_RX_WIN: if (opt > LLC_OPT_MAX_WIN) goto out; llc->rw = opt; break; case LLC_OPT_PKTINFO: if (opt) llc->cmsg_flags |= LLC_CMSG_PKTINFO; else llc->cmsg_flags &= ~LLC_CMSG_PKTINFO; break; default: rc = -ENOPROTOOPT; goto out; } rc = 0; out: release_sock(sk); return rc; } /** * llc_ui_getsockopt - get connection specific socket info * @sock: Socket to get information from. * @level: Socket level user is requesting operations on. * @optname: Operation name. * @optval: Variable to return operation data in. * @optlen: Length of optval. * * Get connection specific socket information. */ static int llc_ui_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct llc_sock *llc = llc_sk(sk); int val = 0, len = 0, rc = -EINVAL; lock_sock(sk); if (unlikely(level != SOL_LLC)) goto out; rc = get_user(len, optlen); if (rc) goto out; rc = -EINVAL; if (len != sizeof(int)) goto out; switch (optname) { case LLC_OPT_RETRY: val = llc->n2; break; case LLC_OPT_SIZE: val = llc->n1; break; case LLC_OPT_ACK_TMR_EXP: val = llc->ack_timer.expire / HZ; break; case LLC_OPT_P_TMR_EXP: val = llc->pf_cycle_timer.expire / HZ; break; case LLC_OPT_REJ_TMR_EXP: val = llc->rej_sent_timer.expire / HZ; break; case LLC_OPT_BUSY_TMR_EXP: val = llc->busy_state_timer.expire / HZ; break; case LLC_OPT_TX_WIN: val = llc->k; break; case LLC_OPT_RX_WIN: val = llc->rw; break; case LLC_OPT_PKTINFO: val = (llc->cmsg_flags & LLC_CMSG_PKTINFO) != 0; break; default: rc = -ENOPROTOOPT; goto out; } rc = 0; if (put_user(len, optlen) || copy_to_user(optval, &val, len)) rc = -EFAULT; out: release_sock(sk); return rc; } static const struct net_proto_family llc_ui_family_ops = { .family = PF_LLC, .create = llc_ui_create, .owner = THIS_MODULE, }; static const struct proto_ops llc_ui_ops = { .family = PF_LLC, .owner = THIS_MODULE, .release = llc_ui_release, .bind = llc_ui_bind, .connect = llc_ui_connect, .socketpair = sock_no_socketpair, .accept = llc_ui_accept, .getname = llc_ui_getname, .poll = datagram_poll, .ioctl = llc_ui_ioctl, .listen = llc_ui_listen, .shutdown = llc_ui_shutdown, .setsockopt = llc_ui_setsockopt, .getsockopt = llc_ui_getsockopt, .sendmsg = llc_ui_sendmsg, .recvmsg = llc_ui_recvmsg, .mmap = sock_no_mmap, .sendpage = sock_no_sendpage, }; static const char llc_proc_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the proc_fs entries\n"; static const char llc_sysctl_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the sysctl entries\n"; static const char llc_sock_err_msg[] __initconst = KERN_CRIT "LLC: Unable to register the network family\n"; static int __init llc2_init(void) { int rc = proto_register(&llc_proto, 0); if (rc != 0) goto out; llc_build_offset_table(); llc_station_init(); llc_ui_sap_last_autoport = LLC_SAP_DYN_START; rc = llc_proc_init(); if (rc != 0) { printk(llc_proc_err_msg); goto out_station; } rc = llc_sysctl_init(); if (rc) { printk(llc_sysctl_err_msg); goto out_proc; } rc = sock_register(&llc_ui_family_ops); if (rc) { printk(llc_sock_err_msg); goto out_sysctl; } llc_add_pack(LLC_DEST_SAP, llc_sap_handler); llc_add_pack(LLC_DEST_CONN, llc_conn_handler); out: return rc; out_sysctl: llc_sysctl_exit(); out_proc: llc_proc_exit(); out_station: llc_station_exit(); proto_unregister(&llc_proto); goto out; } static void __exit llc2_exit(void) { llc_station_exit(); llc_remove_pack(LLC_DEST_SAP); llc_remove_pack(LLC_DEST_CONN); sock_unregister(PF_LLC); llc_proc_exit(); llc_sysctl_exit(); proto_unregister(&llc_proto); } module_init(llc2_init); module_exit(llc2_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("Procom 1997, Jay Schullist 2001, Arnaldo C. Melo 2001-2003"); MODULE_DESCRIPTION("IEEE 802.2 PF_LLC support"); MODULE_ALIAS_NETPROTO(PF_LLC);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5690_0
crossvul-cpp_data_bad_2075_0
/* * Media device * * Copyright (C) 2010 Nokia Corporation * * Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com> * Sakari Ailus <sakari.ailus@iki.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/compat.h> #include <linux/export.h> #include <linux/ioctl.h> #include <linux/media.h> #include <linux/types.h> #include <media/media-device.h> #include <media/media-devnode.h> #include <media/media-entity.h> /* ----------------------------------------------------------------------------- * Userspace API */ static int media_device_open(struct file *filp) { return 0; } static int media_device_close(struct file *filp) { return 0; } static int media_device_get_info(struct media_device *dev, struct media_device_info __user *__info) { struct media_device_info info; memset(&info, 0, sizeof(info)); strlcpy(info.driver, dev->dev->driver->name, sizeof(info.driver)); strlcpy(info.model, dev->model, sizeof(info.model)); strlcpy(info.serial, dev->serial, sizeof(info.serial)); strlcpy(info.bus_info, dev->bus_info, sizeof(info.bus_info)); info.media_version = MEDIA_API_VERSION; info.hw_revision = dev->hw_revision; info.driver_version = dev->driver_version; if (copy_to_user(__info, &info, sizeof(*__info))) return -EFAULT; return 0; } static struct media_entity *find_entity(struct media_device *mdev, u32 id) { struct media_entity *entity; int next = id & MEDIA_ENT_ID_FLAG_NEXT; id &= ~MEDIA_ENT_ID_FLAG_NEXT; spin_lock(&mdev->lock); media_device_for_each_entity(entity, mdev) { if ((entity->id == id && !next) || (entity->id > id && next)) { spin_unlock(&mdev->lock); return entity; } } spin_unlock(&mdev->lock); return NULL; } static long media_device_enum_entities(struct media_device *mdev, struct media_entity_desc __user *uent) { struct media_entity *ent; struct media_entity_desc u_ent; if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id))) return -EFAULT; ent = find_entity(mdev, u_ent.id); if (ent == NULL) return -EINVAL; u_ent.id = ent->id; if (ent->name) { strncpy(u_ent.name, ent->name, sizeof(u_ent.name)); u_ent.name[sizeof(u_ent.name) - 1] = '\0'; } else { memset(u_ent.name, 0, sizeof(u_ent.name)); } u_ent.type = ent->type; u_ent.revision = ent->revision; u_ent.flags = ent->flags; u_ent.group_id = ent->group_id; u_ent.pads = ent->num_pads; u_ent.links = ent->num_links - ent->num_backlinks; memcpy(&u_ent.raw, &ent->info, sizeof(ent->info)); if (copy_to_user(uent, &u_ent, sizeof(u_ent))) return -EFAULT; return 0; } static void media_device_kpad_to_upad(const struct media_pad *kpad, struct media_pad_desc *upad) { upad->entity = kpad->entity->id; upad->index = kpad->index; upad->flags = kpad->flags; } static long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; memset(&pad, 0, sizeof(pad)); media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; memset(&link, 0, sizeof(link)); media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; } static long media_device_enum_links(struct media_device *mdev, struct media_links_enum __user *ulinks) { struct media_links_enum links; int rval; if (copy_from_user(&links, ulinks, sizeof(links))) return -EFAULT; rval = __media_device_enum_links(mdev, &links); if (rval < 0) return rval; if (copy_to_user(ulinks, &links, sizeof(*ulinks))) return -EFAULT; return 0; } static long media_device_setup_link(struct media_device *mdev, struct media_link_desc __user *_ulink) { struct media_link *link = NULL; struct media_link_desc ulink; struct media_entity *source; struct media_entity *sink; int ret; if (copy_from_user(&ulink, _ulink, sizeof(ulink))) return -EFAULT; /* Find the source and sink entities and link. */ source = find_entity(mdev, ulink.source.entity); sink = find_entity(mdev, ulink.sink.entity); if (source == NULL || sink == NULL) return -EINVAL; if (ulink.source.index >= source->num_pads || ulink.sink.index >= sink->num_pads) return -EINVAL; link = media_entity_find_link(&source->pads[ulink.source.index], &sink->pads[ulink.sink.index]); if (link == NULL) return -EINVAL; /* Setup the link on both entities. */ ret = __media_entity_setup_link(link, ulink.flags); if (copy_to_user(_ulink, &ulink, sizeof(ulink))) return -EFAULT; return ret; } static long media_device_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: ret = media_device_get_info(dev, (struct media_device_info __user *)arg); break; case MEDIA_IOC_ENUM_ENTITIES: ret = media_device_enum_entities(dev, (struct media_entity_desc __user *)arg); break; case MEDIA_IOC_ENUM_LINKS: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links(dev, (struct media_links_enum __user *)arg); mutex_unlock(&dev->graph_mutex); break; case MEDIA_IOC_SETUP_LINK: mutex_lock(&dev->graph_mutex); ret = media_device_setup_link(dev, (struct media_link_desc __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #ifdef CONFIG_COMPAT struct media_links_enum32 { __u32 entity; compat_uptr_t pads; /* struct media_pad_desc * */ compat_uptr_t links; /* struct media_link_desc * */ __u32 reserved[4]; }; static long media_device_enum_links32(struct media_device *mdev, struct media_links_enum32 __user *ulinks) { struct media_links_enum links; compat_uptr_t pads_ptr, links_ptr; memset(&links, 0, sizeof(links)); if (get_user(links.entity, &ulinks->entity) || get_user(pads_ptr, &ulinks->pads) || get_user(links_ptr, &ulinks->links)) return -EFAULT; links.pads = compat_ptr(pads_ptr); links.links = compat_ptr(links_ptr); return __media_device_enum_links(mdev, &links); } #define MEDIA_IOC_ENUM_LINKS32 _IOWR('|', 0x02, struct media_links_enum32) static long media_device_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: case MEDIA_IOC_ENUM_ENTITIES: case MEDIA_IOC_SETUP_LINK: return media_device_ioctl(filp, cmd, arg); case MEDIA_IOC_ENUM_LINKS32: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links32(dev, (struct media_links_enum32 __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #endif /* CONFIG_COMPAT */ static const struct media_file_operations media_device_fops = { .owner = THIS_MODULE, .open = media_device_open, .ioctl = media_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = media_device_compat_ioctl, #endif /* CONFIG_COMPAT */ .release = media_device_close, }; /* ----------------------------------------------------------------------------- * sysfs */ static ssize_t show_model(struct device *cd, struct device_attribute *attr, char *buf) { struct media_device *mdev = to_media_device(to_media_devnode(cd)); return sprintf(buf, "%.*s\n", (int)sizeof(mdev->model), mdev->model); } static DEVICE_ATTR(model, S_IRUGO, show_model, NULL); /* ----------------------------------------------------------------------------- * Registration/unregistration */ static void media_device_release(struct media_devnode *mdev) { } /** * media_device_register - register a media device * @mdev: The media device * * The caller is responsible for initializing the media device before * registration. The following fields must be set: * * - dev must point to the parent device * - model must be filled with the device model name */ int __must_check media_device_register(struct media_device *mdev) { int ret; if (WARN_ON(mdev->dev == NULL || mdev->model[0] == 0)) return -EINVAL; mdev->entity_id = 1; INIT_LIST_HEAD(&mdev->entities); spin_lock_init(&mdev->lock); mutex_init(&mdev->graph_mutex); /* Register the device node. */ mdev->devnode.fops = &media_device_fops; mdev->devnode.parent = mdev->dev; mdev->devnode.release = media_device_release; ret = media_devnode_register(&mdev->devnode); if (ret < 0) return ret; ret = device_create_file(&mdev->devnode.dev, &dev_attr_model); if (ret < 0) { media_devnode_unregister(&mdev->devnode); return ret; } return 0; } EXPORT_SYMBOL_GPL(media_device_register); /** * media_device_unregister - unregister a media device * @mdev: The media device * */ void media_device_unregister(struct media_device *mdev) { struct media_entity *entity; struct media_entity *next; list_for_each_entry_safe(entity, next, &mdev->entities, list) media_device_unregister_entity(entity); device_remove_file(&mdev->devnode.dev, &dev_attr_model); media_devnode_unregister(&mdev->devnode); } EXPORT_SYMBOL_GPL(media_device_unregister); /** * media_device_register_entity - Register an entity with a media device * @mdev: The media device * @entity: The entity */ int __must_check media_device_register_entity(struct media_device *mdev, struct media_entity *entity) { /* Warn if we apparently re-register an entity */ WARN_ON(entity->parent != NULL); entity->parent = mdev; spin_lock(&mdev->lock); if (entity->id == 0) entity->id = mdev->entity_id++; else mdev->entity_id = max(entity->id + 1, mdev->entity_id); list_add_tail(&entity->list, &mdev->entities); spin_unlock(&mdev->lock); return 0; } EXPORT_SYMBOL_GPL(media_device_register_entity); /** * media_device_unregister_entity - Unregister an entity * @entity: The entity * * If the entity has never been registered this function will return * immediately. */ void media_device_unregister_entity(struct media_entity *entity) { struct media_device *mdev = entity->parent; if (mdev == NULL) return; spin_lock(&mdev->lock); list_del(&entity->list); spin_unlock(&mdev->lock); entity->parent = NULL; } EXPORT_SYMBOL_GPL(media_device_unregister_entity);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2075_0
crossvul-cpp_data_good_5696_0
/* * VMware vSockets Driver * * Copyright (C) 2007-2013 VMware, Inc. All rights reserved. * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation version 2 and no later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. */ #include <linux/types.h> #include <linux/bitops.h> #include <linux/cred.h> #include <linux/init.h> #include <linux/io.h> #include <linux/kernel.h> #include <linux/kmod.h> #include <linux/list.h> #include <linux/miscdevice.h> #include <linux/module.h> #include <linux/mutex.h> #include <linux/net.h> #include <linux/poll.h> #include <linux/skbuff.h> #include <linux/smp.h> #include <linux/socket.h> #include <linux/stddef.h> #include <linux/unistd.h> #include <linux/wait.h> #include <linux/workqueue.h> #include <net/sock.h> #include "af_vsock.h" #include "vmci_transport_notify.h" static int vmci_transport_recv_dgram_cb(void *data, struct vmci_datagram *dg); static int vmci_transport_recv_stream_cb(void *data, struct vmci_datagram *dg); static void vmci_transport_peer_attach_cb(u32 sub_id, const struct vmci_event_data *ed, void *client_data); static void vmci_transport_peer_detach_cb(u32 sub_id, const struct vmci_event_data *ed, void *client_data); static void vmci_transport_recv_pkt_work(struct work_struct *work); static int vmci_transport_recv_listen(struct sock *sk, struct vmci_transport_packet *pkt); static int vmci_transport_recv_connecting_server( struct sock *sk, struct sock *pending, struct vmci_transport_packet *pkt); static int vmci_transport_recv_connecting_client( struct sock *sk, struct vmci_transport_packet *pkt); static int vmci_transport_recv_connecting_client_negotiate( struct sock *sk, struct vmci_transport_packet *pkt); static int vmci_transport_recv_connecting_client_invalid( struct sock *sk, struct vmci_transport_packet *pkt); static int vmci_transport_recv_connected(struct sock *sk, struct vmci_transport_packet *pkt); static bool vmci_transport_old_proto_override(bool *old_pkt_proto); static u16 vmci_transport_new_proto_supported_versions(void); static bool vmci_transport_proto_to_notify_struct(struct sock *sk, u16 *proto, bool old_pkt_proto); struct vmci_transport_recv_pkt_info { struct work_struct work; struct sock *sk; struct vmci_transport_packet pkt; }; static struct vmci_handle vmci_transport_stream_handle = { VMCI_INVALID_ID, VMCI_INVALID_ID }; static u32 vmci_transport_qp_resumed_sub_id = VMCI_INVALID_ID; static int PROTOCOL_OVERRIDE = -1; #define VMCI_TRANSPORT_DEFAULT_QP_SIZE_MIN 128 #define VMCI_TRANSPORT_DEFAULT_QP_SIZE 262144 #define VMCI_TRANSPORT_DEFAULT_QP_SIZE_MAX 262144 /* The default peer timeout indicates how long we will wait for a peer response * to a control message. */ #define VSOCK_DEFAULT_CONNECT_TIMEOUT (2 * HZ) #define SS_LISTEN 255 /* Helper function to convert from a VMCI error code to a VSock error code. */ static s32 vmci_transport_error_to_vsock_error(s32 vmci_error) { int err; switch (vmci_error) { case VMCI_ERROR_NO_MEM: err = ENOMEM; break; case VMCI_ERROR_DUPLICATE_ENTRY: case VMCI_ERROR_ALREADY_EXISTS: err = EADDRINUSE; break; case VMCI_ERROR_NO_ACCESS: err = EPERM; break; case VMCI_ERROR_NO_RESOURCES: err = ENOBUFS; break; case VMCI_ERROR_INVALID_RESOURCE: err = EHOSTUNREACH; break; case VMCI_ERROR_INVALID_ARGS: default: err = EINVAL; } return err > 0 ? -err : err; } static inline void vmci_transport_packet_init(struct vmci_transport_packet *pkt, struct sockaddr_vm *src, struct sockaddr_vm *dst, u8 type, u64 size, u64 mode, struct vmci_transport_waiting_info *wait, u16 proto, struct vmci_handle handle) { /* We register the stream control handler as an any cid handle so we * must always send from a source address of VMADDR_CID_ANY */ pkt->dg.src = vmci_make_handle(VMADDR_CID_ANY, VMCI_TRANSPORT_PACKET_RID); pkt->dg.dst = vmci_make_handle(dst->svm_cid, VMCI_TRANSPORT_PACKET_RID); pkt->dg.payload_size = sizeof(*pkt) - sizeof(pkt->dg); pkt->version = VMCI_TRANSPORT_PACKET_VERSION; pkt->type = type; pkt->src_port = src->svm_port; pkt->dst_port = dst->svm_port; memset(&pkt->proto, 0, sizeof(pkt->proto)); memset(&pkt->_reserved2, 0, sizeof(pkt->_reserved2)); switch (pkt->type) { case VMCI_TRANSPORT_PACKET_TYPE_INVALID: pkt->u.size = 0; break; case VMCI_TRANSPORT_PACKET_TYPE_REQUEST: case VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE: pkt->u.size = size; break; case VMCI_TRANSPORT_PACKET_TYPE_OFFER: case VMCI_TRANSPORT_PACKET_TYPE_ATTACH: pkt->u.handle = handle; break; case VMCI_TRANSPORT_PACKET_TYPE_WROTE: case VMCI_TRANSPORT_PACKET_TYPE_READ: case VMCI_TRANSPORT_PACKET_TYPE_RST: pkt->u.size = 0; break; case VMCI_TRANSPORT_PACKET_TYPE_SHUTDOWN: pkt->u.mode = mode; break; case VMCI_TRANSPORT_PACKET_TYPE_WAITING_READ: case VMCI_TRANSPORT_PACKET_TYPE_WAITING_WRITE: memcpy(&pkt->u.wait, wait, sizeof(pkt->u.wait)); break; case VMCI_TRANSPORT_PACKET_TYPE_REQUEST2: case VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE2: pkt->u.size = size; pkt->proto = proto; break; } } static inline void vmci_transport_packet_get_addresses(struct vmci_transport_packet *pkt, struct sockaddr_vm *local, struct sockaddr_vm *remote) { vsock_addr_init(local, pkt->dg.dst.context, pkt->dst_port); vsock_addr_init(remote, pkt->dg.src.context, pkt->src_port); } static int __vmci_transport_send_control_pkt(struct vmci_transport_packet *pkt, struct sockaddr_vm *src, struct sockaddr_vm *dst, enum vmci_transport_packet_type type, u64 size, u64 mode, struct vmci_transport_waiting_info *wait, u16 proto, struct vmci_handle handle, bool convert_error) { int err; vmci_transport_packet_init(pkt, src, dst, type, size, mode, wait, proto, handle); err = vmci_datagram_send(&pkt->dg); if (convert_error && (err < 0)) return vmci_transport_error_to_vsock_error(err); return err; } static int vmci_transport_reply_control_pkt_fast(struct vmci_transport_packet *pkt, enum vmci_transport_packet_type type, u64 size, u64 mode, struct vmci_transport_waiting_info *wait, struct vmci_handle handle) { struct vmci_transport_packet reply; struct sockaddr_vm src, dst; if (pkt->type == VMCI_TRANSPORT_PACKET_TYPE_RST) { return 0; } else { vmci_transport_packet_get_addresses(pkt, &src, &dst); return __vmci_transport_send_control_pkt(&reply, &src, &dst, type, size, mode, wait, VSOCK_PROTO_INVALID, handle, true); } } static int vmci_transport_send_control_pkt_bh(struct sockaddr_vm *src, struct sockaddr_vm *dst, enum vmci_transport_packet_type type, u64 size, u64 mode, struct vmci_transport_waiting_info *wait, struct vmci_handle handle) { /* Note that it is safe to use a single packet across all CPUs since * two tasklets of the same type are guaranteed to not ever run * simultaneously. If that ever changes, or VMCI stops using tasklets, * we can use per-cpu packets. */ static struct vmci_transport_packet pkt; return __vmci_transport_send_control_pkt(&pkt, src, dst, type, size, mode, wait, VSOCK_PROTO_INVALID, handle, false); } static int vmci_transport_send_control_pkt(struct sock *sk, enum vmci_transport_packet_type type, u64 size, u64 mode, struct vmci_transport_waiting_info *wait, u16 proto, struct vmci_handle handle) { struct vmci_transport_packet *pkt; struct vsock_sock *vsk; int err; vsk = vsock_sk(sk); if (!vsock_addr_bound(&vsk->local_addr)) return -EINVAL; if (!vsock_addr_bound(&vsk->remote_addr)) return -EINVAL; pkt = kmalloc(sizeof(*pkt), GFP_KERNEL); if (!pkt) return -ENOMEM; err = __vmci_transport_send_control_pkt(pkt, &vsk->local_addr, &vsk->remote_addr, type, size, mode, wait, proto, handle, true); kfree(pkt); return err; } static int vmci_transport_send_reset_bh(struct sockaddr_vm *dst, struct sockaddr_vm *src, struct vmci_transport_packet *pkt) { if (pkt->type == VMCI_TRANSPORT_PACKET_TYPE_RST) return 0; return vmci_transport_send_control_pkt_bh( dst, src, VMCI_TRANSPORT_PACKET_TYPE_RST, 0, 0, NULL, VMCI_INVALID_HANDLE); } static int vmci_transport_send_reset(struct sock *sk, struct vmci_transport_packet *pkt) { if (pkt->type == VMCI_TRANSPORT_PACKET_TYPE_RST) return 0; return vmci_transport_send_control_pkt(sk, VMCI_TRANSPORT_PACKET_TYPE_RST, 0, 0, NULL, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } static int vmci_transport_send_negotiate(struct sock *sk, size_t size) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE, size, 0, NULL, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } static int vmci_transport_send_negotiate2(struct sock *sk, size_t size, u16 version) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE2, size, 0, NULL, version, VMCI_INVALID_HANDLE); } static int vmci_transport_send_qp_offer(struct sock *sk, struct vmci_handle handle) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_OFFER, 0, 0, NULL, VSOCK_PROTO_INVALID, handle); } static int vmci_transport_send_attach(struct sock *sk, struct vmci_handle handle) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_ATTACH, 0, 0, NULL, VSOCK_PROTO_INVALID, handle); } static int vmci_transport_reply_reset(struct vmci_transport_packet *pkt) { return vmci_transport_reply_control_pkt_fast( pkt, VMCI_TRANSPORT_PACKET_TYPE_RST, 0, 0, NULL, VMCI_INVALID_HANDLE); } static int vmci_transport_send_invalid_bh(struct sockaddr_vm *dst, struct sockaddr_vm *src) { return vmci_transport_send_control_pkt_bh( dst, src, VMCI_TRANSPORT_PACKET_TYPE_INVALID, 0, 0, NULL, VMCI_INVALID_HANDLE); } int vmci_transport_send_wrote_bh(struct sockaddr_vm *dst, struct sockaddr_vm *src) { return vmci_transport_send_control_pkt_bh( dst, src, VMCI_TRANSPORT_PACKET_TYPE_WROTE, 0, 0, NULL, VMCI_INVALID_HANDLE); } int vmci_transport_send_read_bh(struct sockaddr_vm *dst, struct sockaddr_vm *src) { return vmci_transport_send_control_pkt_bh( dst, src, VMCI_TRANSPORT_PACKET_TYPE_READ, 0, 0, NULL, VMCI_INVALID_HANDLE); } int vmci_transport_send_wrote(struct sock *sk) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_WROTE, 0, 0, NULL, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } int vmci_transport_send_read(struct sock *sk) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_READ, 0, 0, NULL, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } int vmci_transport_send_waiting_write(struct sock *sk, struct vmci_transport_waiting_info *wait) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_WAITING_WRITE, 0, 0, wait, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } int vmci_transport_send_waiting_read(struct sock *sk, struct vmci_transport_waiting_info *wait) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_WAITING_READ, 0, 0, wait, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } static int vmci_transport_shutdown(struct vsock_sock *vsk, int mode) { return vmci_transport_send_control_pkt( &vsk->sk, VMCI_TRANSPORT_PACKET_TYPE_SHUTDOWN, 0, mode, NULL, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } static int vmci_transport_send_conn_request(struct sock *sk, size_t size) { return vmci_transport_send_control_pkt(sk, VMCI_TRANSPORT_PACKET_TYPE_REQUEST, size, 0, NULL, VSOCK_PROTO_INVALID, VMCI_INVALID_HANDLE); } static int vmci_transport_send_conn_request2(struct sock *sk, size_t size, u16 version) { return vmci_transport_send_control_pkt( sk, VMCI_TRANSPORT_PACKET_TYPE_REQUEST2, size, 0, NULL, version, VMCI_INVALID_HANDLE); } static struct sock *vmci_transport_get_pending( struct sock *listener, struct vmci_transport_packet *pkt) { struct vsock_sock *vlistener; struct vsock_sock *vpending; struct sock *pending; struct sockaddr_vm src; vsock_addr_init(&src, pkt->dg.src.context, pkt->src_port); vlistener = vsock_sk(listener); list_for_each_entry(vpending, &vlistener->pending_links, pending_links) { if (vsock_addr_equals_addr(&src, &vpending->remote_addr) && pkt->dst_port == vpending->local_addr.svm_port) { pending = sk_vsock(vpending); sock_hold(pending); goto found; } } pending = NULL; found: return pending; } static void vmci_transport_release_pending(struct sock *pending) { sock_put(pending); } /* We allow two kinds of sockets to communicate with a restricted VM: 1) * trusted sockets 2) sockets from applications running as the same user as the * VM (this is only true for the host side and only when using hosted products) */ static bool vmci_transport_is_trusted(struct vsock_sock *vsock, u32 peer_cid) { return vsock->trusted || vmci_is_context_owner(peer_cid, vsock->owner->uid); } /* We allow sending datagrams to and receiving datagrams from a restricted VM * only if it is trusted as described in vmci_transport_is_trusted. */ static bool vmci_transport_allow_dgram(struct vsock_sock *vsock, u32 peer_cid) { if (vsock->cached_peer != peer_cid) { vsock->cached_peer = peer_cid; if (!vmci_transport_is_trusted(vsock, peer_cid) && (vmci_context_get_priv_flags(peer_cid) & VMCI_PRIVILEGE_FLAG_RESTRICTED)) { vsock->cached_peer_allow_dgram = false; } else { vsock->cached_peer_allow_dgram = true; } } return vsock->cached_peer_allow_dgram; } static int vmci_transport_queue_pair_alloc(struct vmci_qp **qpair, struct vmci_handle *handle, u64 produce_size, u64 consume_size, u32 peer, u32 flags, bool trusted) { int err = 0; if (trusted) { /* Try to allocate our queue pair as trusted. This will only * work if vsock is running in the host. */ err = vmci_qpair_alloc(qpair, handle, produce_size, consume_size, peer, flags, VMCI_PRIVILEGE_FLAG_TRUSTED); if (err != VMCI_ERROR_NO_ACCESS) goto out; } err = vmci_qpair_alloc(qpair, handle, produce_size, consume_size, peer, flags, VMCI_NO_PRIVILEGE_FLAGS); out: if (err < 0) { pr_err("Could not attach to queue pair with %d\n", err); err = vmci_transport_error_to_vsock_error(err); } return err; } static int vmci_transport_datagram_create_hnd(u32 resource_id, u32 flags, vmci_datagram_recv_cb recv_cb, void *client_data, struct vmci_handle *out_handle) { int err = 0; /* Try to allocate our datagram handler as trusted. This will only work * if vsock is running in the host. */ err = vmci_datagram_create_handle_priv(resource_id, flags, VMCI_PRIVILEGE_FLAG_TRUSTED, recv_cb, client_data, out_handle); if (err == VMCI_ERROR_NO_ACCESS) err = vmci_datagram_create_handle(resource_id, flags, recv_cb, client_data, out_handle); return err; } /* This is invoked as part of a tasklet that's scheduled when the VMCI * interrupt fires. This is run in bottom-half context and if it ever needs to * sleep it should defer that work to a work queue. */ static int vmci_transport_recv_dgram_cb(void *data, struct vmci_datagram *dg) { struct sock *sk; size_t size; struct sk_buff *skb; struct vsock_sock *vsk; sk = (struct sock *)data; /* This handler is privileged when this module is running on the host. * We will get datagrams from all endpoints (even VMs that are in a * restricted context). If we get one from a restricted context then * the destination socket must be trusted. * * NOTE: We access the socket struct without holding the lock here. * This is ok because the field we are interested is never modified * outside of the create and destruct socket functions. */ vsk = vsock_sk(sk); if (!vmci_transport_allow_dgram(vsk, dg->src.context)) return VMCI_ERROR_NO_ACCESS; size = VMCI_DG_SIZE(dg); /* Attach the packet to the socket's receive queue as an sk_buff. */ skb = alloc_skb(size, GFP_ATOMIC); if (skb) { /* sk_receive_skb() will do a sock_put(), so hold here. */ sock_hold(sk); skb_put(skb, size); memcpy(skb->data, dg, size); sk_receive_skb(sk, skb, 0); } return VMCI_SUCCESS; } static bool vmci_transport_stream_allow(u32 cid, u32 port) { static const u32 non_socket_contexts[] = { VMADDR_CID_HYPERVISOR, VMADDR_CID_RESERVED, }; int i; BUILD_BUG_ON(sizeof(cid) != sizeof(*non_socket_contexts)); for (i = 0; i < ARRAY_SIZE(non_socket_contexts); i++) { if (cid == non_socket_contexts[i]) return false; } return true; } /* This is invoked as part of a tasklet that's scheduled when the VMCI * interrupt fires. This is run in bottom-half context but it defers most of * its work to the packet handling work queue. */ static int vmci_transport_recv_stream_cb(void *data, struct vmci_datagram *dg) { struct sock *sk; struct sockaddr_vm dst; struct sockaddr_vm src; struct vmci_transport_packet *pkt; struct vsock_sock *vsk; bool bh_process_pkt; int err; sk = NULL; err = VMCI_SUCCESS; bh_process_pkt = false; /* Ignore incoming packets from contexts without sockets, or resources * that aren't vsock implementations. */ if (!vmci_transport_stream_allow(dg->src.context, -1) || VMCI_TRANSPORT_PACKET_RID != dg->src.resource) return VMCI_ERROR_NO_ACCESS; if (VMCI_DG_SIZE(dg) < sizeof(*pkt)) /* Drop datagrams that do not contain full VSock packets. */ return VMCI_ERROR_INVALID_ARGS; pkt = (struct vmci_transport_packet *)dg; /* Find the socket that should handle this packet. First we look for a * connected socket and if there is none we look for a socket bound to * the destintation address. */ vsock_addr_init(&src, pkt->dg.src.context, pkt->src_port); vsock_addr_init(&dst, pkt->dg.dst.context, pkt->dst_port); sk = vsock_find_connected_socket(&src, &dst); if (!sk) { sk = vsock_find_bound_socket(&dst); if (!sk) { /* We could not find a socket for this specified * address. If this packet is a RST, we just drop it. * If it is another packet, we send a RST. Note that * we do not send a RST reply to RSTs so that we do not * continually send RSTs between two endpoints. * * Note that since this is a reply, dst is src and src * is dst. */ if (vmci_transport_send_reset_bh(&dst, &src, pkt) < 0) pr_err("unable to send reset\n"); err = VMCI_ERROR_NOT_FOUND; goto out; } } /* If the received packet type is beyond all types known to this * implementation, reply with an invalid message. Hopefully this will * help when implementing backwards compatibility in the future. */ if (pkt->type >= VMCI_TRANSPORT_PACKET_TYPE_MAX) { vmci_transport_send_invalid_bh(&dst, &src); err = VMCI_ERROR_INVALID_ARGS; goto out; } /* This handler is privileged when this module is running on the host. * We will get datagram connect requests from all endpoints (even VMs * that are in a restricted context). If we get one from a restricted * context then the destination socket must be trusted. * * NOTE: We access the socket struct without holding the lock here. * This is ok because the field we are interested is never modified * outside of the create and destruct socket functions. */ vsk = vsock_sk(sk); if (!vmci_transport_allow_dgram(vsk, pkt->dg.src.context)) { err = VMCI_ERROR_NO_ACCESS; goto out; } /* We do most everything in a work queue, but let's fast path the * notification of reads and writes to help data transfer performance. * We can only do this if there is no process context code executing * for this socket since that may change the state. */ bh_lock_sock(sk); if (!sock_owned_by_user(sk)) { /* The local context ID may be out of date, update it. */ vsk->local_addr.svm_cid = dst.svm_cid; if (sk->sk_state == SS_CONNECTED) vmci_trans(vsk)->notify_ops->handle_notify_pkt( sk, pkt, true, &dst, &src, &bh_process_pkt); } bh_unlock_sock(sk); if (!bh_process_pkt) { struct vmci_transport_recv_pkt_info *recv_pkt_info; recv_pkt_info = kmalloc(sizeof(*recv_pkt_info), GFP_ATOMIC); if (!recv_pkt_info) { if (vmci_transport_send_reset_bh(&dst, &src, pkt) < 0) pr_err("unable to send reset\n"); err = VMCI_ERROR_NO_MEM; goto out; } recv_pkt_info->sk = sk; memcpy(&recv_pkt_info->pkt, pkt, sizeof(recv_pkt_info->pkt)); INIT_WORK(&recv_pkt_info->work, vmci_transport_recv_pkt_work); schedule_work(&recv_pkt_info->work); /* Clear sk so that the reference count incremented by one of * the Find functions above is not decremented below. We need * that reference count for the packet handler we've scheduled * to run. */ sk = NULL; } out: if (sk) sock_put(sk); return err; } static void vmci_transport_peer_attach_cb(u32 sub_id, const struct vmci_event_data *e_data, void *client_data) { struct sock *sk = client_data; const struct vmci_event_payload_qp *e_payload; struct vsock_sock *vsk; e_payload = vmci_event_data_const_payload(e_data); vsk = vsock_sk(sk); /* We don't ask for delayed CBs when we subscribe to this event (we * pass 0 as flags to vmci_event_subscribe()). VMCI makes no * guarantees in that case about what context we might be running in, * so it could be BH or process, blockable or non-blockable. So we * need to account for all possible contexts here. */ local_bh_disable(); bh_lock_sock(sk); /* XXX This is lame, we should provide a way to lookup sockets by * qp_handle. */ if (vmci_handle_is_equal(vmci_trans(vsk)->qp_handle, e_payload->handle)) { /* XXX This doesn't do anything, but in the future we may want * to set a flag here to verify the attach really did occur and * we weren't just sent a datagram claiming it was. */ goto out; } out: bh_unlock_sock(sk); local_bh_enable(); } static void vmci_transport_handle_detach(struct sock *sk) { struct vsock_sock *vsk; vsk = vsock_sk(sk); if (!vmci_handle_is_invalid(vmci_trans(vsk)->qp_handle)) { sock_set_flag(sk, SOCK_DONE); /* On a detach the peer will not be sending or receiving * anymore. */ vsk->peer_shutdown = SHUTDOWN_MASK; /* We should not be sending anymore since the peer won't be * there to receive, but we can still receive if there is data * left in our consume queue. */ if (vsock_stream_has_data(vsk) <= 0) { if (sk->sk_state == SS_CONNECTING) { /* The peer may detach from a queue pair while * we are still in the connecting state, i.e., * if the peer VM is killed after attaching to * a queue pair, but before we complete the * handshake. In that case, we treat the detach * event like a reset. */ sk->sk_state = SS_UNCONNECTED; sk->sk_err = ECONNRESET; sk->sk_error_report(sk); return; } sk->sk_state = SS_UNCONNECTED; } sk->sk_state_change(sk); } } static void vmci_transport_peer_detach_cb(u32 sub_id, const struct vmci_event_data *e_data, void *client_data) { struct sock *sk = client_data; const struct vmci_event_payload_qp *e_payload; struct vsock_sock *vsk; e_payload = vmci_event_data_const_payload(e_data); vsk = vsock_sk(sk); if (vmci_handle_is_invalid(e_payload->handle)) return; /* Same rules for locking as for peer_attach_cb(). */ local_bh_disable(); bh_lock_sock(sk); /* XXX This is lame, we should provide a way to lookup sockets by * qp_handle. */ if (vmci_handle_is_equal(vmci_trans(vsk)->qp_handle, e_payload->handle)) vmci_transport_handle_detach(sk); bh_unlock_sock(sk); local_bh_enable(); } static void vmci_transport_qp_resumed_cb(u32 sub_id, const struct vmci_event_data *e_data, void *client_data) { vsock_for_each_connected_socket(vmci_transport_handle_detach); } static void vmci_transport_recv_pkt_work(struct work_struct *work) { struct vmci_transport_recv_pkt_info *recv_pkt_info; struct vmci_transport_packet *pkt; struct sock *sk; recv_pkt_info = container_of(work, struct vmci_transport_recv_pkt_info, work); sk = recv_pkt_info->sk; pkt = &recv_pkt_info->pkt; lock_sock(sk); /* The local context ID may be out of date. */ vsock_sk(sk)->local_addr.svm_cid = pkt->dg.dst.context; switch (sk->sk_state) { case SS_LISTEN: vmci_transport_recv_listen(sk, pkt); break; case SS_CONNECTING: /* Processing of pending connections for servers goes through * the listening socket, so see vmci_transport_recv_listen() * for that path. */ vmci_transport_recv_connecting_client(sk, pkt); break; case SS_CONNECTED: vmci_transport_recv_connected(sk, pkt); break; default: /* Because this function does not run in the same context as * vmci_transport_recv_stream_cb it is possible that the * socket has closed. We need to let the other side know or it * could be sitting in a connect and hang forever. Send a * reset to prevent that. */ vmci_transport_send_reset(sk, pkt); goto out; } out: release_sock(sk); kfree(recv_pkt_info); /* Release reference obtained in the stream callback when we fetched * this socket out of the bound or connected list. */ sock_put(sk); } static int vmci_transport_recv_listen(struct sock *sk, struct vmci_transport_packet *pkt) { struct sock *pending; struct vsock_sock *vpending; int err; u64 qp_size; bool old_request = false; bool old_pkt_proto = false; err = 0; /* Because we are in the listen state, we could be receiving a packet * for ourself or any previous connection requests that we received. * If it's the latter, we try to find a socket in our list of pending * connections and, if we do, call the appropriate handler for the * state that that socket is in. Otherwise we try to service the * connection request. */ pending = vmci_transport_get_pending(sk, pkt); if (pending) { lock_sock(pending); /* The local context ID may be out of date. */ vsock_sk(pending)->local_addr.svm_cid = pkt->dg.dst.context; switch (pending->sk_state) { case SS_CONNECTING: err = vmci_transport_recv_connecting_server(sk, pending, pkt); break; default: vmci_transport_send_reset(pending, pkt); err = -EINVAL; } if (err < 0) vsock_remove_pending(sk, pending); release_sock(pending); vmci_transport_release_pending(pending); return err; } /* The listen state only accepts connection requests. Reply with a * reset unless we received a reset. */ if (!(pkt->type == VMCI_TRANSPORT_PACKET_TYPE_REQUEST || pkt->type == VMCI_TRANSPORT_PACKET_TYPE_REQUEST2)) { vmci_transport_reply_reset(pkt); return -EINVAL; } if (pkt->u.size == 0) { vmci_transport_reply_reset(pkt); return -EINVAL; } /* If this socket can't accommodate this connection request, we send a * reset. Otherwise we create and initialize a child socket and reply * with a connection negotiation. */ if (sk->sk_ack_backlog >= sk->sk_max_ack_backlog) { vmci_transport_reply_reset(pkt); return -ECONNREFUSED; } pending = __vsock_create(sock_net(sk), NULL, sk, GFP_KERNEL, sk->sk_type); if (!pending) { vmci_transport_send_reset(sk, pkt); return -ENOMEM; } vpending = vsock_sk(pending); vsock_addr_init(&vpending->local_addr, pkt->dg.dst.context, pkt->dst_port); vsock_addr_init(&vpending->remote_addr, pkt->dg.src.context, pkt->src_port); /* If the proposed size fits within our min/max, accept it. Otherwise * propose our own size. */ if (pkt->u.size >= vmci_trans(vpending)->queue_pair_min_size && pkt->u.size <= vmci_trans(vpending)->queue_pair_max_size) { qp_size = pkt->u.size; } else { qp_size = vmci_trans(vpending)->queue_pair_size; } /* Figure out if we are using old or new requests based on the * overrides pkt types sent by our peer. */ if (vmci_transport_old_proto_override(&old_pkt_proto)) { old_request = old_pkt_proto; } else { if (pkt->type == VMCI_TRANSPORT_PACKET_TYPE_REQUEST) old_request = true; else if (pkt->type == VMCI_TRANSPORT_PACKET_TYPE_REQUEST2) old_request = false; } if (old_request) { /* Handle a REQUEST (or override) */ u16 version = VSOCK_PROTO_INVALID; if (vmci_transport_proto_to_notify_struct( pending, &version, true)) err = vmci_transport_send_negotiate(pending, qp_size); else err = -EINVAL; } else { /* Handle a REQUEST2 (or override) */ int proto_int = pkt->proto; int pos; u16 active_proto_version = 0; /* The list of possible protocols is the intersection of all * protocols the client supports ... plus all the protocols we * support. */ proto_int &= vmci_transport_new_proto_supported_versions(); /* We choose the highest possible protocol version and use that * one. */ pos = fls(proto_int); if (pos) { active_proto_version = (1 << (pos - 1)); if (vmci_transport_proto_to_notify_struct( pending, &active_proto_version, false)) err = vmci_transport_send_negotiate2(pending, qp_size, active_proto_version); else err = -EINVAL; } else { err = -EINVAL; } } if (err < 0) { vmci_transport_send_reset(sk, pkt); sock_put(pending); err = vmci_transport_error_to_vsock_error(err); goto out; } vsock_add_pending(sk, pending); sk->sk_ack_backlog++; pending->sk_state = SS_CONNECTING; vmci_trans(vpending)->produce_size = vmci_trans(vpending)->consume_size = qp_size; vmci_trans(vpending)->queue_pair_size = qp_size; vmci_trans(vpending)->notify_ops->process_request(pending); /* We might never receive another message for this socket and it's not * connected to any process, so we have to ensure it gets cleaned up * ourself. Our delayed work function will take care of that. Note * that we do not ever cancel this function since we have few * guarantees about its state when calling cancel_delayed_work(). * Instead we hold a reference on the socket for that function and make * it capable of handling cases where it needs to do nothing but * release that reference. */ vpending->listener = sk; sock_hold(sk); sock_hold(pending); INIT_DELAYED_WORK(&vpending->dwork, vsock_pending_work); schedule_delayed_work(&vpending->dwork, HZ); out: return err; } static int vmci_transport_recv_connecting_server(struct sock *listener, struct sock *pending, struct vmci_transport_packet *pkt) { struct vsock_sock *vpending; struct vmci_handle handle; struct vmci_qp *qpair; bool is_local; u32 flags; u32 detach_sub_id; int err; int skerr; vpending = vsock_sk(pending); detach_sub_id = VMCI_INVALID_ID; switch (pkt->type) { case VMCI_TRANSPORT_PACKET_TYPE_OFFER: if (vmci_handle_is_invalid(pkt->u.handle)) { vmci_transport_send_reset(pending, pkt); skerr = EPROTO; err = -EINVAL; goto destroy; } break; default: /* Close and cleanup the connection. */ vmci_transport_send_reset(pending, pkt); skerr = EPROTO; err = pkt->type == VMCI_TRANSPORT_PACKET_TYPE_RST ? 0 : -EINVAL; goto destroy; } /* In order to complete the connection we need to attach to the offered * queue pair and send an attach notification. We also subscribe to the * detach event so we know when our peer goes away, and we do that * before attaching so we don't miss an event. If all this succeeds, * we update our state and wakeup anything waiting in accept() for a * connection. */ /* We don't care about attach since we ensure the other side has * attached by specifying the ATTACH_ONLY flag below. */ err = vmci_event_subscribe(VMCI_EVENT_QP_PEER_DETACH, vmci_transport_peer_detach_cb, pending, &detach_sub_id); if (err < VMCI_SUCCESS) { vmci_transport_send_reset(pending, pkt); err = vmci_transport_error_to_vsock_error(err); skerr = -err; goto destroy; } vmci_trans(vpending)->detach_sub_id = detach_sub_id; /* Now attach to the queue pair the client created. */ handle = pkt->u.handle; /* vpending->local_addr always has a context id so we do not need to * worry about VMADDR_CID_ANY in this case. */ is_local = vpending->remote_addr.svm_cid == vpending->local_addr.svm_cid; flags = VMCI_QPFLAG_ATTACH_ONLY; flags |= is_local ? VMCI_QPFLAG_LOCAL : 0; err = vmci_transport_queue_pair_alloc( &qpair, &handle, vmci_trans(vpending)->produce_size, vmci_trans(vpending)->consume_size, pkt->dg.src.context, flags, vmci_transport_is_trusted( vpending, vpending->remote_addr.svm_cid)); if (err < 0) { vmci_transport_send_reset(pending, pkt); skerr = -err; goto destroy; } vmci_trans(vpending)->qp_handle = handle; vmci_trans(vpending)->qpair = qpair; /* When we send the attach message, we must be ready to handle incoming * control messages on the newly connected socket. So we move the * pending socket to the connected state before sending the attach * message. Otherwise, an incoming packet triggered by the attach being * received by the peer may be processed concurrently with what happens * below after sending the attach message, and that incoming packet * will find the listening socket instead of the (currently) pending * socket. Note that enqueueing the socket increments the reference * count, so even if a reset comes before the connection is accepted, * the socket will be valid until it is removed from the queue. * * If we fail sending the attach below, we remove the socket from the * connected list and move the socket to SS_UNCONNECTED before * releasing the lock, so a pending slow path processing of an incoming * packet will not see the socket in the connected state in that case. */ pending->sk_state = SS_CONNECTED; vsock_insert_connected(vpending); /* Notify our peer of our attach. */ err = vmci_transport_send_attach(pending, handle); if (err < 0) { vsock_remove_connected(vpending); pr_err("Could not send attach\n"); vmci_transport_send_reset(pending, pkt); err = vmci_transport_error_to_vsock_error(err); skerr = -err; goto destroy; } /* We have a connection. Move the now connected socket from the * listener's pending list to the accept queue so callers of accept() * can find it. */ vsock_remove_pending(listener, pending); vsock_enqueue_accept(listener, pending); /* Callers of accept() will be be waiting on the listening socket, not * the pending socket. */ listener->sk_state_change(listener); return 0; destroy: pending->sk_err = skerr; pending->sk_state = SS_UNCONNECTED; /* As long as we drop our reference, all necessary cleanup will handle * when the cleanup function drops its reference and our destruct * implementation is called. Note that since the listen handler will * remove pending from the pending list upon our failure, the cleanup * function won't drop the additional reference, which is why we do it * here. */ sock_put(pending); return err; } static int vmci_transport_recv_connecting_client(struct sock *sk, struct vmci_transport_packet *pkt) { struct vsock_sock *vsk; int err; int skerr; vsk = vsock_sk(sk); switch (pkt->type) { case VMCI_TRANSPORT_PACKET_TYPE_ATTACH: if (vmci_handle_is_invalid(pkt->u.handle) || !vmci_handle_is_equal(pkt->u.handle, vmci_trans(vsk)->qp_handle)) { skerr = EPROTO; err = -EINVAL; goto destroy; } /* Signify the socket is connected and wakeup the waiter in * connect(). Also place the socket in the connected table for * accounting (it can already be found since it's in the bound * table). */ sk->sk_state = SS_CONNECTED; sk->sk_socket->state = SS_CONNECTED; vsock_insert_connected(vsk); sk->sk_state_change(sk); break; case VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE: case VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE2: if (pkt->u.size == 0 || pkt->dg.src.context != vsk->remote_addr.svm_cid || pkt->src_port != vsk->remote_addr.svm_port || !vmci_handle_is_invalid(vmci_trans(vsk)->qp_handle) || vmci_trans(vsk)->qpair || vmci_trans(vsk)->produce_size != 0 || vmci_trans(vsk)->consume_size != 0 || vmci_trans(vsk)->attach_sub_id != VMCI_INVALID_ID || vmci_trans(vsk)->detach_sub_id != VMCI_INVALID_ID) { skerr = EPROTO; err = -EINVAL; goto destroy; } err = vmci_transport_recv_connecting_client_negotiate(sk, pkt); if (err) { skerr = -err; goto destroy; } break; case VMCI_TRANSPORT_PACKET_TYPE_INVALID: err = vmci_transport_recv_connecting_client_invalid(sk, pkt); if (err) { skerr = -err; goto destroy; } break; case VMCI_TRANSPORT_PACKET_TYPE_RST: /* Older versions of the linux code (WS 6.5 / ESX 4.0) used to * continue processing here after they sent an INVALID packet. * This meant that we got a RST after the INVALID. We ignore a * RST after an INVALID. The common code doesn't send the RST * ... so we can hang if an old version of the common code * fails between getting a REQUEST and sending an OFFER back. * Not much we can do about it... except hope that it doesn't * happen. */ if (vsk->ignore_connecting_rst) { vsk->ignore_connecting_rst = false; } else { skerr = ECONNRESET; err = 0; goto destroy; } break; default: /* Close and cleanup the connection. */ skerr = EPROTO; err = -EINVAL; goto destroy; } return 0; destroy: vmci_transport_send_reset(sk, pkt); sk->sk_state = SS_UNCONNECTED; sk->sk_err = skerr; sk->sk_error_report(sk); return err; } static int vmci_transport_recv_connecting_client_negotiate( struct sock *sk, struct vmci_transport_packet *pkt) { int err; struct vsock_sock *vsk; struct vmci_handle handle; struct vmci_qp *qpair; u32 attach_sub_id; u32 detach_sub_id; bool is_local; u32 flags; bool old_proto = true; bool old_pkt_proto; u16 version; vsk = vsock_sk(sk); handle = VMCI_INVALID_HANDLE; attach_sub_id = VMCI_INVALID_ID; detach_sub_id = VMCI_INVALID_ID; /* If we have gotten here then we should be past the point where old * linux vsock could have sent the bogus rst. */ vsk->sent_request = false; vsk->ignore_connecting_rst = false; /* Verify that we're OK with the proposed queue pair size */ if (pkt->u.size < vmci_trans(vsk)->queue_pair_min_size || pkt->u.size > vmci_trans(vsk)->queue_pair_max_size) { err = -EINVAL; goto destroy; } /* At this point we know the CID the peer is using to talk to us. */ if (vsk->local_addr.svm_cid == VMADDR_CID_ANY) vsk->local_addr.svm_cid = pkt->dg.dst.context; /* Setup the notify ops to be the highest supported version that both * the server and the client support. */ if (vmci_transport_old_proto_override(&old_pkt_proto)) { old_proto = old_pkt_proto; } else { if (pkt->type == VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE) old_proto = true; else if (pkt->type == VMCI_TRANSPORT_PACKET_TYPE_NEGOTIATE2) old_proto = false; } if (old_proto) version = VSOCK_PROTO_INVALID; else version = pkt->proto; if (!vmci_transport_proto_to_notify_struct(sk, &version, old_proto)) { err = -EINVAL; goto destroy; } /* Subscribe to attach and detach events first. * * XXX We attach once for each queue pair created for now so it is easy * to find the socket (it's provided), but later we should only * subscribe once and add a way to lookup sockets by queue pair handle. */ err = vmci_event_subscribe(VMCI_EVENT_QP_PEER_ATTACH, vmci_transport_peer_attach_cb, sk, &attach_sub_id); if (err < VMCI_SUCCESS) { err = vmci_transport_error_to_vsock_error(err); goto destroy; } err = vmci_event_subscribe(VMCI_EVENT_QP_PEER_DETACH, vmci_transport_peer_detach_cb, sk, &detach_sub_id); if (err < VMCI_SUCCESS) { err = vmci_transport_error_to_vsock_error(err); goto destroy; } /* Make VMCI select the handle for us. */ handle = VMCI_INVALID_HANDLE; is_local = vsk->remote_addr.svm_cid == vsk->local_addr.svm_cid; flags = is_local ? VMCI_QPFLAG_LOCAL : 0; err = vmci_transport_queue_pair_alloc(&qpair, &handle, pkt->u.size, pkt->u.size, vsk->remote_addr.svm_cid, flags, vmci_transport_is_trusted( vsk, vsk-> remote_addr.svm_cid)); if (err < 0) goto destroy; err = vmci_transport_send_qp_offer(sk, handle); if (err < 0) { err = vmci_transport_error_to_vsock_error(err); goto destroy; } vmci_trans(vsk)->qp_handle = handle; vmci_trans(vsk)->qpair = qpair; vmci_trans(vsk)->produce_size = vmci_trans(vsk)->consume_size = pkt->u.size; vmci_trans(vsk)->attach_sub_id = attach_sub_id; vmci_trans(vsk)->detach_sub_id = detach_sub_id; vmci_trans(vsk)->notify_ops->process_negotiate(sk); return 0; destroy: if (attach_sub_id != VMCI_INVALID_ID) vmci_event_unsubscribe(attach_sub_id); if (detach_sub_id != VMCI_INVALID_ID) vmci_event_unsubscribe(detach_sub_id); if (!vmci_handle_is_invalid(handle)) vmci_qpair_detach(&qpair); return err; } static int vmci_transport_recv_connecting_client_invalid(struct sock *sk, struct vmci_transport_packet *pkt) { int err = 0; struct vsock_sock *vsk = vsock_sk(sk); if (vsk->sent_request) { vsk->sent_request = false; vsk->ignore_connecting_rst = true; err = vmci_transport_send_conn_request( sk, vmci_trans(vsk)->queue_pair_size); if (err < 0) err = vmci_transport_error_to_vsock_error(err); else err = 0; } return err; } static int vmci_transport_recv_connected(struct sock *sk, struct vmci_transport_packet *pkt) { struct vsock_sock *vsk; bool pkt_processed = false; /* In cases where we are closing the connection, it's sufficient to * mark the state change (and maybe error) and wake up any waiting * threads. Since this is a connected socket, it's owned by a user * process and will be cleaned up when the failure is passed back on * the current or next system call. Our system call implementations * must therefore check for error and state changes on entry and when * being awoken. */ switch (pkt->type) { case VMCI_TRANSPORT_PACKET_TYPE_SHUTDOWN: if (pkt->u.mode) { vsk = vsock_sk(sk); vsk->peer_shutdown |= pkt->u.mode; sk->sk_state_change(sk); } break; case VMCI_TRANSPORT_PACKET_TYPE_RST: vsk = vsock_sk(sk); /* It is possible that we sent our peer a message (e.g a * WAITING_READ) right before we got notified that the peer had * detached. If that happens then we can get a RST pkt back * from our peer even though there is data available for us to * read. In that case, don't shutdown the socket completely but * instead allow the local client to finish reading data off * the queuepair. Always treat a RST pkt in connected mode like * a clean shutdown. */ sock_set_flag(sk, SOCK_DONE); vsk->peer_shutdown = SHUTDOWN_MASK; if (vsock_stream_has_data(vsk) <= 0) sk->sk_state = SS_DISCONNECTING; sk->sk_state_change(sk); break; default: vsk = vsock_sk(sk); vmci_trans(vsk)->notify_ops->handle_notify_pkt( sk, pkt, false, NULL, NULL, &pkt_processed); if (!pkt_processed) return -EINVAL; break; } return 0; } static int vmci_transport_socket_init(struct vsock_sock *vsk, struct vsock_sock *psk) { vsk->trans = kmalloc(sizeof(struct vmci_transport), GFP_KERNEL); if (!vsk->trans) return -ENOMEM; vmci_trans(vsk)->dg_handle = VMCI_INVALID_HANDLE; vmci_trans(vsk)->qp_handle = VMCI_INVALID_HANDLE; vmci_trans(vsk)->qpair = NULL; vmci_trans(vsk)->produce_size = vmci_trans(vsk)->consume_size = 0; vmci_trans(vsk)->attach_sub_id = vmci_trans(vsk)->detach_sub_id = VMCI_INVALID_ID; vmci_trans(vsk)->notify_ops = NULL; if (psk) { vmci_trans(vsk)->queue_pair_size = vmci_trans(psk)->queue_pair_size; vmci_trans(vsk)->queue_pair_min_size = vmci_trans(psk)->queue_pair_min_size; vmci_trans(vsk)->queue_pair_max_size = vmci_trans(psk)->queue_pair_max_size; } else { vmci_trans(vsk)->queue_pair_size = VMCI_TRANSPORT_DEFAULT_QP_SIZE; vmci_trans(vsk)->queue_pair_min_size = VMCI_TRANSPORT_DEFAULT_QP_SIZE_MIN; vmci_trans(vsk)->queue_pair_max_size = VMCI_TRANSPORT_DEFAULT_QP_SIZE_MAX; } return 0; } static void vmci_transport_destruct(struct vsock_sock *vsk) { if (vmci_trans(vsk)->attach_sub_id != VMCI_INVALID_ID) { vmci_event_unsubscribe(vmci_trans(vsk)->attach_sub_id); vmci_trans(vsk)->attach_sub_id = VMCI_INVALID_ID; } if (vmci_trans(vsk)->detach_sub_id != VMCI_INVALID_ID) { vmci_event_unsubscribe(vmci_trans(vsk)->detach_sub_id); vmci_trans(vsk)->detach_sub_id = VMCI_INVALID_ID; } if (!vmci_handle_is_invalid(vmci_trans(vsk)->qp_handle)) { vmci_qpair_detach(&vmci_trans(vsk)->qpair); vmci_trans(vsk)->qp_handle = VMCI_INVALID_HANDLE; vmci_trans(vsk)->produce_size = 0; vmci_trans(vsk)->consume_size = 0; } if (vmci_trans(vsk)->notify_ops) vmci_trans(vsk)->notify_ops->socket_destruct(vsk); kfree(vsk->trans); vsk->trans = NULL; } static void vmci_transport_release(struct vsock_sock *vsk) { if (!vmci_handle_is_invalid(vmci_trans(vsk)->dg_handle)) { vmci_datagram_destroy_handle(vmci_trans(vsk)->dg_handle); vmci_trans(vsk)->dg_handle = VMCI_INVALID_HANDLE; } } static int vmci_transport_dgram_bind(struct vsock_sock *vsk, struct sockaddr_vm *addr) { u32 port; u32 flags; int err; /* VMCI will select a resource ID for us if we provide * VMCI_INVALID_ID. */ port = addr->svm_port == VMADDR_PORT_ANY ? VMCI_INVALID_ID : addr->svm_port; if (port <= LAST_RESERVED_PORT && !capable(CAP_NET_BIND_SERVICE)) return -EACCES; flags = addr->svm_cid == VMADDR_CID_ANY ? VMCI_FLAG_ANYCID_DG_HND : 0; err = vmci_transport_datagram_create_hnd(port, flags, vmci_transport_recv_dgram_cb, &vsk->sk, &vmci_trans(vsk)->dg_handle); if (err < VMCI_SUCCESS) return vmci_transport_error_to_vsock_error(err); vsock_addr_init(&vsk->local_addr, addr->svm_cid, vmci_trans(vsk)->dg_handle.resource); return 0; } static int vmci_transport_dgram_enqueue( struct vsock_sock *vsk, struct sockaddr_vm *remote_addr, struct iovec *iov, size_t len) { int err; struct vmci_datagram *dg; if (len > VMCI_MAX_DG_PAYLOAD_SIZE) return -EMSGSIZE; if (!vmci_transport_allow_dgram(vsk, remote_addr->svm_cid)) return -EPERM; /* Allocate a buffer for the user's message and our packet header. */ dg = kmalloc(len + sizeof(*dg), GFP_KERNEL); if (!dg) return -ENOMEM; memcpy_fromiovec(VMCI_DG_PAYLOAD(dg), iov, len); dg->dst = vmci_make_handle(remote_addr->svm_cid, remote_addr->svm_port); dg->src = vmci_make_handle(vsk->local_addr.svm_cid, vsk->local_addr.svm_port); dg->payload_size = len; err = vmci_datagram_send(dg); kfree(dg); if (err < 0) return vmci_transport_error_to_vsock_error(err); return err - sizeof(*dg); } static int vmci_transport_dgram_dequeue(struct kiocb *kiocb, struct vsock_sock *vsk, struct msghdr *msg, size_t len, int flags) { int err; int noblock; struct vmci_datagram *dg; size_t payload_len; struct sk_buff *skb; noblock = flags & MSG_DONTWAIT; if (flags & MSG_OOB || flags & MSG_ERRQUEUE) return -EOPNOTSUPP; msg->msg_namelen = 0; /* Retrieve the head sk_buff from the socket's receive queue. */ err = 0; skb = skb_recv_datagram(&vsk->sk, flags, noblock, &err); if (err) return err; if (!skb) return -EAGAIN; dg = (struct vmci_datagram *)skb->data; if (!dg) /* err is 0, meaning we read zero bytes. */ goto out; payload_len = dg->payload_size; /* Ensure the sk_buff matches the payload size claimed in the packet. */ if (payload_len != skb->len - sizeof(*dg)) { err = -EINVAL; goto out; } if (payload_len > len) { payload_len = len; msg->msg_flags |= MSG_TRUNC; } /* Place the datagram payload in the user's iovec. */ err = skb_copy_datagram_iovec(skb, sizeof(*dg), msg->msg_iov, payload_len); if (err) goto out; if (msg->msg_name) { struct sockaddr_vm *vm_addr; /* Provide the address of the sender. */ vm_addr = (struct sockaddr_vm *)msg->msg_name; vsock_addr_init(vm_addr, dg->src.context, dg->src.resource); msg->msg_namelen = sizeof(*vm_addr); } err = payload_len; out: skb_free_datagram(&vsk->sk, skb); return err; } static bool vmci_transport_dgram_allow(u32 cid, u32 port) { if (cid == VMADDR_CID_HYPERVISOR) { /* Registrations of PBRPC Servers do not modify VMX/Hypervisor * state and are allowed. */ return port == VMCI_UNITY_PBRPC_REGISTER; } return true; } static int vmci_transport_connect(struct vsock_sock *vsk) { int err; bool old_pkt_proto = false; struct sock *sk = &vsk->sk; if (vmci_transport_old_proto_override(&old_pkt_proto) && old_pkt_proto) { err = vmci_transport_send_conn_request( sk, vmci_trans(vsk)->queue_pair_size); if (err < 0) { sk->sk_state = SS_UNCONNECTED; return err; } } else { int supported_proto_versions = vmci_transport_new_proto_supported_versions(); err = vmci_transport_send_conn_request2( sk, vmci_trans(vsk)->queue_pair_size, supported_proto_versions); if (err < 0) { sk->sk_state = SS_UNCONNECTED; return err; } vsk->sent_request = true; } return err; } static ssize_t vmci_transport_stream_dequeue( struct vsock_sock *vsk, struct iovec *iov, size_t len, int flags) { if (flags & MSG_PEEK) return vmci_qpair_peekv(vmci_trans(vsk)->qpair, iov, len, 0); else return vmci_qpair_dequev(vmci_trans(vsk)->qpair, iov, len, 0); } static ssize_t vmci_transport_stream_enqueue( struct vsock_sock *vsk, struct iovec *iov, size_t len) { return vmci_qpair_enquev(vmci_trans(vsk)->qpair, iov, len, 0); } static s64 vmci_transport_stream_has_data(struct vsock_sock *vsk) { return vmci_qpair_consume_buf_ready(vmci_trans(vsk)->qpair); } static s64 vmci_transport_stream_has_space(struct vsock_sock *vsk) { return vmci_qpair_produce_free_space(vmci_trans(vsk)->qpair); } static u64 vmci_transport_stream_rcvhiwat(struct vsock_sock *vsk) { return vmci_trans(vsk)->consume_size; } static bool vmci_transport_stream_is_active(struct vsock_sock *vsk) { return !vmci_handle_is_invalid(vmci_trans(vsk)->qp_handle); } static u64 vmci_transport_get_buffer_size(struct vsock_sock *vsk) { return vmci_trans(vsk)->queue_pair_size; } static u64 vmci_transport_get_min_buffer_size(struct vsock_sock *vsk) { return vmci_trans(vsk)->queue_pair_min_size; } static u64 vmci_transport_get_max_buffer_size(struct vsock_sock *vsk) { return vmci_trans(vsk)->queue_pair_max_size; } static void vmci_transport_set_buffer_size(struct vsock_sock *vsk, u64 val) { if (val < vmci_trans(vsk)->queue_pair_min_size) vmci_trans(vsk)->queue_pair_min_size = val; if (val > vmci_trans(vsk)->queue_pair_max_size) vmci_trans(vsk)->queue_pair_max_size = val; vmci_trans(vsk)->queue_pair_size = val; } static void vmci_transport_set_min_buffer_size(struct vsock_sock *vsk, u64 val) { if (val > vmci_trans(vsk)->queue_pair_size) vmci_trans(vsk)->queue_pair_size = val; vmci_trans(vsk)->queue_pair_min_size = val; } static void vmci_transport_set_max_buffer_size(struct vsock_sock *vsk, u64 val) { if (val < vmci_trans(vsk)->queue_pair_size) vmci_trans(vsk)->queue_pair_size = val; vmci_trans(vsk)->queue_pair_max_size = val; } static int vmci_transport_notify_poll_in( struct vsock_sock *vsk, size_t target, bool *data_ready_now) { return vmci_trans(vsk)->notify_ops->poll_in( &vsk->sk, target, data_ready_now); } static int vmci_transport_notify_poll_out( struct vsock_sock *vsk, size_t target, bool *space_available_now) { return vmci_trans(vsk)->notify_ops->poll_out( &vsk->sk, target, space_available_now); } static int vmci_transport_notify_recv_init( struct vsock_sock *vsk, size_t target, struct vsock_transport_recv_notify_data *data) { return vmci_trans(vsk)->notify_ops->recv_init( &vsk->sk, target, (struct vmci_transport_recv_notify_data *)data); } static int vmci_transport_notify_recv_pre_block( struct vsock_sock *vsk, size_t target, struct vsock_transport_recv_notify_data *data) { return vmci_trans(vsk)->notify_ops->recv_pre_block( &vsk->sk, target, (struct vmci_transport_recv_notify_data *)data); } static int vmci_transport_notify_recv_pre_dequeue( struct vsock_sock *vsk, size_t target, struct vsock_transport_recv_notify_data *data) { return vmci_trans(vsk)->notify_ops->recv_pre_dequeue( &vsk->sk, target, (struct vmci_transport_recv_notify_data *)data); } static int vmci_transport_notify_recv_post_dequeue( struct vsock_sock *vsk, size_t target, ssize_t copied, bool data_read, struct vsock_transport_recv_notify_data *data) { return vmci_trans(vsk)->notify_ops->recv_post_dequeue( &vsk->sk, target, copied, data_read, (struct vmci_transport_recv_notify_data *)data); } static int vmci_transport_notify_send_init( struct vsock_sock *vsk, struct vsock_transport_send_notify_data *data) { return vmci_trans(vsk)->notify_ops->send_init( &vsk->sk, (struct vmci_transport_send_notify_data *)data); } static int vmci_transport_notify_send_pre_block( struct vsock_sock *vsk, struct vsock_transport_send_notify_data *data) { return vmci_trans(vsk)->notify_ops->send_pre_block( &vsk->sk, (struct vmci_transport_send_notify_data *)data); } static int vmci_transport_notify_send_pre_enqueue( struct vsock_sock *vsk, struct vsock_transport_send_notify_data *data) { return vmci_trans(vsk)->notify_ops->send_pre_enqueue( &vsk->sk, (struct vmci_transport_send_notify_data *)data); } static int vmci_transport_notify_send_post_enqueue( struct vsock_sock *vsk, ssize_t written, struct vsock_transport_send_notify_data *data) { return vmci_trans(vsk)->notify_ops->send_post_enqueue( &vsk->sk, written, (struct vmci_transport_send_notify_data *)data); } static bool vmci_transport_old_proto_override(bool *old_pkt_proto) { if (PROTOCOL_OVERRIDE != -1) { if (PROTOCOL_OVERRIDE == 0) *old_pkt_proto = true; else *old_pkt_proto = false; pr_info("Proto override in use\n"); return true; } return false; } static bool vmci_transport_proto_to_notify_struct(struct sock *sk, u16 *proto, bool old_pkt_proto) { struct vsock_sock *vsk = vsock_sk(sk); if (old_pkt_proto) { if (*proto != VSOCK_PROTO_INVALID) { pr_err("Can't set both an old and new protocol\n"); return false; } vmci_trans(vsk)->notify_ops = &vmci_transport_notify_pkt_ops; goto exit; } switch (*proto) { case VSOCK_PROTO_PKT_ON_NOTIFY: vmci_trans(vsk)->notify_ops = &vmci_transport_notify_pkt_q_state_ops; break; default: pr_err("Unknown notify protocol version\n"); return false; } exit: vmci_trans(vsk)->notify_ops->socket_init(sk); return true; } static u16 vmci_transport_new_proto_supported_versions(void) { if (PROTOCOL_OVERRIDE != -1) return PROTOCOL_OVERRIDE; return VSOCK_PROTO_ALL_SUPPORTED; } static u32 vmci_transport_get_local_cid(void) { return vmci_get_context_id(); } static struct vsock_transport vmci_transport = { .init = vmci_transport_socket_init, .destruct = vmci_transport_destruct, .release = vmci_transport_release, .connect = vmci_transport_connect, .dgram_bind = vmci_transport_dgram_bind, .dgram_dequeue = vmci_transport_dgram_dequeue, .dgram_enqueue = vmci_transport_dgram_enqueue, .dgram_allow = vmci_transport_dgram_allow, .stream_dequeue = vmci_transport_stream_dequeue, .stream_enqueue = vmci_transport_stream_enqueue, .stream_has_data = vmci_transport_stream_has_data, .stream_has_space = vmci_transport_stream_has_space, .stream_rcvhiwat = vmci_transport_stream_rcvhiwat, .stream_is_active = vmci_transport_stream_is_active, .stream_allow = vmci_transport_stream_allow, .notify_poll_in = vmci_transport_notify_poll_in, .notify_poll_out = vmci_transport_notify_poll_out, .notify_recv_init = vmci_transport_notify_recv_init, .notify_recv_pre_block = vmci_transport_notify_recv_pre_block, .notify_recv_pre_dequeue = vmci_transport_notify_recv_pre_dequeue, .notify_recv_post_dequeue = vmci_transport_notify_recv_post_dequeue, .notify_send_init = vmci_transport_notify_send_init, .notify_send_pre_block = vmci_transport_notify_send_pre_block, .notify_send_pre_enqueue = vmci_transport_notify_send_pre_enqueue, .notify_send_post_enqueue = vmci_transport_notify_send_post_enqueue, .shutdown = vmci_transport_shutdown, .set_buffer_size = vmci_transport_set_buffer_size, .set_min_buffer_size = vmci_transport_set_min_buffer_size, .set_max_buffer_size = vmci_transport_set_max_buffer_size, .get_buffer_size = vmci_transport_get_buffer_size, .get_min_buffer_size = vmci_transport_get_min_buffer_size, .get_max_buffer_size = vmci_transport_get_max_buffer_size, .get_local_cid = vmci_transport_get_local_cid, }; static int __init vmci_transport_init(void) { int err; /* Create the datagram handle that we will use to send and receive all * VSocket control messages for this context. */ err = vmci_transport_datagram_create_hnd(VMCI_TRANSPORT_PACKET_RID, VMCI_FLAG_ANYCID_DG_HND, vmci_transport_recv_stream_cb, NULL, &vmci_transport_stream_handle); if (err < VMCI_SUCCESS) { pr_err("Unable to create datagram handle. (%d)\n", err); return vmci_transport_error_to_vsock_error(err); } err = vmci_event_subscribe(VMCI_EVENT_QP_RESUMED, vmci_transport_qp_resumed_cb, NULL, &vmci_transport_qp_resumed_sub_id); if (err < VMCI_SUCCESS) { pr_err("Unable to subscribe to resumed event. (%d)\n", err); err = vmci_transport_error_to_vsock_error(err); vmci_transport_qp_resumed_sub_id = VMCI_INVALID_ID; goto err_destroy_stream_handle; } err = vsock_core_init(&vmci_transport); if (err < 0) goto err_unsubscribe; return 0; err_unsubscribe: vmci_event_unsubscribe(vmci_transport_qp_resumed_sub_id); err_destroy_stream_handle: vmci_datagram_destroy_handle(vmci_transport_stream_handle); return err; } module_init(vmci_transport_init); static void __exit vmci_transport_exit(void) { if (!vmci_handle_is_invalid(vmci_transport_stream_handle)) { if (vmci_datagram_destroy_handle( vmci_transport_stream_handle) != VMCI_SUCCESS) pr_err("Couldn't destroy datagram handle\n"); vmci_transport_stream_handle = VMCI_INVALID_HANDLE; } if (vmci_transport_qp_resumed_sub_id != VMCI_INVALID_ID) { vmci_event_unsubscribe(vmci_transport_qp_resumed_sub_id); vmci_transport_qp_resumed_sub_id = VMCI_INVALID_ID; } vsock_core_exit(); } module_exit(vmci_transport_exit); MODULE_AUTHOR("VMware, Inc."); MODULE_DESCRIPTION("VMCI transport for Virtual Sockets"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("vmware_vsock"); MODULE_ALIAS_NETPROTO(PF_VSOCK);
./CrossVul/dataset_final_sorted/CWE-200/c/good_5696_0
crossvul-cpp_data_good_3840_0
/* * TUN - Universal TUN/TAP device driver. * Copyright (C) 1999-2002 Maxim Krasnyansky <maxk@qualcomm.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * $Id: tun.c,v 1.15 2002/03/01 02:44:24 maxk Exp $ */ /* * Changes: * * Mike Kershaw <dragorn@kismetwireless.net> 2005/08/14 * Add TUNSETLINK ioctl to set the link encapsulation * * Mark Smith <markzzzsmith@yahoo.com.au> * Use eth_random_addr() for tap MAC address. * * Harald Roelle <harald.roelle@ifi.lmu.de> 2004/04/20 * Fixes in packet dropping, queue length setting and queue wakeup. * Increased default tx queue length. * Added ethtool API. * Minor cleanups * * Daniel Podlejski <underley@underley.eu.org> * Modifications for 2.3.99-pre5 kernel. */ #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt #define DRV_NAME "tun" #define DRV_VERSION "1.6" #define DRV_DESCRIPTION "Universal TUN/TAP device driver" #define DRV_COPYRIGHT "(C) 1999-2004 Max Krasnyansky <maxk@qualcomm.com>" #include <linux/module.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/major.h> #include <linux/slab.h> #include <linux/poll.h> #include <linux/fcntl.h> #include <linux/init.h> #include <linux/skbuff.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/miscdevice.h> #include <linux/ethtool.h> #include <linux/rtnetlink.h> #include <linux/compat.h> #include <linux/if.h> #include <linux/if_arp.h> #include <linux/if_ether.h> #include <linux/if_tun.h> #include <linux/crc32.h> #include <linux/nsproxy.h> #include <linux/virtio_net.h> #include <linux/rcupdate.h> #include <net/net_namespace.h> #include <net/netns/generic.h> #include <net/rtnetlink.h> #include <net/sock.h> #include <asm/uaccess.h> /* Uncomment to enable debugging */ /* #define TUN_DEBUG 1 */ #ifdef TUN_DEBUG static int debug; #define tun_debug(level, tun, fmt, args...) \ do { \ if (tun->debug) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (debug == 2) \ printk(level fmt, ##args); \ } while (0) #else #define tun_debug(level, tun, fmt, args...) \ do { \ if (0) \ netdev_printk(level, tun->dev, fmt, ##args); \ } while (0) #define DBG1(level, fmt, args...) \ do { \ if (0) \ printk(level fmt, ##args); \ } while (0) #endif #define GOODCOPY_LEN 128 #define FLT_EXACT_COUNT 8 struct tap_filter { unsigned int count; /* Number of addrs. Zero means disabled */ u32 mask[2]; /* Mask of the hashed addrs */ unsigned char addr[FLT_EXACT_COUNT][ETH_ALEN]; }; struct tun_file { atomic_t count; struct tun_struct *tun; struct net *net; }; struct tun_sock; struct tun_struct { struct tun_file *tfile; unsigned int flags; uid_t owner; gid_t group; struct net_device *dev; netdev_features_t set_features; #define TUN_USER_FEATURES (NETIF_F_HW_CSUM|NETIF_F_TSO_ECN|NETIF_F_TSO| \ NETIF_F_TSO6|NETIF_F_UFO) struct fasync_struct *fasync; struct tap_filter txflt; struct socket socket; struct socket_wq wq; int vnet_hdr_sz; #ifdef TUN_DEBUG int debug; #endif }; struct tun_sock { struct sock sk; struct tun_struct *tun; }; static inline struct tun_sock *tun_sk(struct sock *sk) { return container_of(sk, struct tun_sock, sk); } static int tun_attach(struct tun_struct *tun, struct file *file) { struct tun_file *tfile = file->private_data; int err; ASSERT_RTNL(); netif_tx_lock_bh(tun->dev); err = -EINVAL; if (tfile->tun) goto out; err = -EBUSY; if (tun->tfile) goto out; err = 0; tfile->tun = tun; tun->tfile = tfile; tun->socket.file = file; netif_carrier_on(tun->dev); dev_hold(tun->dev); sock_hold(tun->socket.sk); atomic_inc(&tfile->count); out: netif_tx_unlock_bh(tun->dev); return err; } static void __tun_detach(struct tun_struct *tun) { /* Detach from net device */ netif_tx_lock_bh(tun->dev); netif_carrier_off(tun->dev); tun->tfile = NULL; tun->socket.file = NULL; netif_tx_unlock_bh(tun->dev); /* Drop read queue */ skb_queue_purge(&tun->socket.sk->sk_receive_queue); /* Drop the extra count on the net device */ dev_put(tun->dev); } static void tun_detach(struct tun_struct *tun) { rtnl_lock(); __tun_detach(tun); rtnl_unlock(); } static struct tun_struct *__tun_get(struct tun_file *tfile) { struct tun_struct *tun = NULL; if (atomic_inc_not_zero(&tfile->count)) tun = tfile->tun; return tun; } static struct tun_struct *tun_get(struct file *file) { return __tun_get(file->private_data); } static void tun_put(struct tun_struct *tun) { struct tun_file *tfile = tun->tfile; if (atomic_dec_and_test(&tfile->count)) tun_detach(tfile->tun); } /* TAP filtering */ static void addr_hash_set(u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; mask[n >> 5] |= (1 << (n & 31)); } static unsigned int addr_hash_test(const u32 *mask, const u8 *addr) { int n = ether_crc(ETH_ALEN, addr) >> 26; return mask[n >> 5] & (1 << (n & 31)); } static int update_filter(struct tap_filter *filter, void __user *arg) { struct { u8 u[ETH_ALEN]; } *addr; struct tun_filter uf; int err, alen, n, nexact; if (copy_from_user(&uf, arg, sizeof(uf))) return -EFAULT; if (!uf.count) { /* Disabled */ filter->count = 0; return 0; } alen = ETH_ALEN * uf.count; addr = kmalloc(alen, GFP_KERNEL); if (!addr) return -ENOMEM; if (copy_from_user(addr, arg + sizeof(uf), alen)) { err = -EFAULT; goto done; } /* The filter is updated without holding any locks. Which is * perfectly safe. We disable it first and in the worst * case we'll accept a few undesired packets. */ filter->count = 0; wmb(); /* Use first set of addresses as an exact filter */ for (n = 0; n < uf.count && n < FLT_EXACT_COUNT; n++) memcpy(filter->addr[n], addr[n].u, ETH_ALEN); nexact = n; /* Remaining multicast addresses are hashed, * unicast will leave the filter disabled. */ memset(filter->mask, 0, sizeof(filter->mask)); for (; n < uf.count; n++) { if (!is_multicast_ether_addr(addr[n].u)) { err = 0; /* no filter */ goto done; } addr_hash_set(filter->mask, addr[n].u); } /* For ALLMULTI just set the mask to all ones. * This overrides the mask populated above. */ if ((uf.flags & TUN_FLT_ALLMULTI)) memset(filter->mask, ~0, sizeof(filter->mask)); /* Now enable the filter */ wmb(); filter->count = nexact; /* Return the number of exact filters */ err = nexact; done: kfree(addr); return err; } /* Returns: 0 - drop, !=0 - accept */ static int run_filter(struct tap_filter *filter, const struct sk_buff *skb) { /* Cannot use eth_hdr(skb) here because skb_mac_hdr() is incorrect * at this point. */ struct ethhdr *eh = (struct ethhdr *) skb->data; int i; /* Exact match */ for (i = 0; i < filter->count; i++) if (ether_addr_equal(eh->h_dest, filter->addr[i])) return 1; /* Inexact match (multicast only) */ if (is_multicast_ether_addr(eh->h_dest)) return addr_hash_test(filter->mask, eh->h_dest); return 0; } /* * Checks whether the packet is accepted or not. * Returns: 0 - drop, !=0 - accept */ static int check_filter(struct tap_filter *filter, const struct sk_buff *skb) { if (!filter->count) return 1; return run_filter(filter, skb); } /* Network device part of the driver */ static const struct ethtool_ops tun_ethtool_ops; /* Net device detach from fd. */ static void tun_net_uninit(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); struct tun_file *tfile = tun->tfile; /* Inform the methods they need to stop using the dev. */ if (tfile) { wake_up_all(&tun->wq.wait); if (atomic_dec_and_test(&tfile->count)) __tun_detach(tun); } } static void tun_free_netdev(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); BUG_ON(!test_bit(SOCK_EXTERNALLY_ALLOCATED, &tun->socket.flags)); sk_release_kernel(tun->socket.sk); } /* Net device open. */ static int tun_net_open(struct net_device *dev) { netif_start_queue(dev); return 0; } /* Net device close. */ static int tun_net_close(struct net_device *dev) { netif_stop_queue(dev); return 0; } /* Net device start xmit */ static netdev_tx_t tun_net_xmit(struct sk_buff *skb, struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); tun_debug(KERN_INFO, tun, "tun_net_xmit %d\n", skb->len); /* Drop packet if interface is not attached */ if (!tun->tfile) goto drop; /* Drop if the filter does not like it. * This is a noop if the filter is disabled. * Filter can be enabled only for the TAP devices. */ if (!check_filter(&tun->txflt, skb)) goto drop; if (tun->socket.sk->sk_filter && sk_filter(tun->socket.sk, skb)) goto drop; if (skb_queue_len(&tun->socket.sk->sk_receive_queue) >= dev->tx_queue_len) { if (!(tun->flags & TUN_ONE_QUEUE)) { /* Normal queueing mode. */ /* Packet scheduler handles dropping of further packets. */ netif_stop_queue(dev); /* We won't see all dropped packets individually, so overrun * error is more appropriate. */ dev->stats.tx_fifo_errors++; } else { /* Single queue mode. * Driver handles dropping of all packets itself. */ goto drop; } } /* Orphan the skb - required as we might hang on to it * for indefinite time. */ if (unlikely(skb_orphan_frags(skb, GFP_ATOMIC))) goto drop; skb_orphan(skb); /* Enqueue packet */ skb_queue_tail(&tun->socket.sk->sk_receive_queue, skb); /* Notify and wake up reader process */ if (tun->flags & TUN_FASYNC) kill_fasync(&tun->fasync, SIGIO, POLL_IN); wake_up_interruptible_poll(&tun->wq.wait, POLLIN | POLLRDNORM | POLLRDBAND); return NETDEV_TX_OK; drop: dev->stats.tx_dropped++; kfree_skb(skb); return NETDEV_TX_OK; } static void tun_net_mclist(struct net_device *dev) { /* * This callback is supposed to deal with mc filter in * _rx_ path and has nothing to do with the _tx_ path. * In rx path we always accept everything userspace gives us. */ } #define MIN_MTU 68 #define MAX_MTU 65535 static int tun_net_change_mtu(struct net_device *dev, int new_mtu) { if (new_mtu < MIN_MTU || new_mtu + dev->hard_header_len > MAX_MTU) return -EINVAL; dev->mtu = new_mtu; return 0; } static netdev_features_t tun_net_fix_features(struct net_device *dev, netdev_features_t features) { struct tun_struct *tun = netdev_priv(dev); return (features & tun->set_features) | (features & ~TUN_USER_FEATURES); } #ifdef CONFIG_NET_POLL_CONTROLLER static void tun_poll_controller(struct net_device *dev) { /* * Tun only receives frames when: * 1) the char device endpoint gets data from user space * 2) the tun socket gets a sendmsg call from user space * Since both of those are syncronous operations, we are guaranteed * never to have pending data when we poll for it * so theres nothing to do here but return. * We need this though so netpoll recognizes us as an interface that * supports polling, which enables bridge devices in virt setups to * still use netconsole */ return; } #endif static const struct net_device_ops tun_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_change_mtu = tun_net_change_mtu, .ndo_fix_features = tun_net_fix_features, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif }; static const struct net_device_ops tap_netdev_ops = { .ndo_uninit = tun_net_uninit, .ndo_open = tun_net_open, .ndo_stop = tun_net_close, .ndo_start_xmit = tun_net_xmit, .ndo_change_mtu = tun_net_change_mtu, .ndo_fix_features = tun_net_fix_features, .ndo_set_rx_mode = tun_net_mclist, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, #ifdef CONFIG_NET_POLL_CONTROLLER .ndo_poll_controller = tun_poll_controller, #endif }; /* Initialize net device. */ static void tun_net_init(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: dev->netdev_ops = &tun_netdev_ops; /* Point-to-Point TUN Device */ dev->hard_header_len = 0; dev->addr_len = 0; dev->mtu = 1500; /* Zero header length */ dev->type = ARPHRD_NONE; dev->flags = IFF_POINTOPOINT | IFF_NOARP | IFF_MULTICAST; dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; case TUN_TAP_DEV: dev->netdev_ops = &tap_netdev_ops; /* Ethernet TAP Device */ ether_setup(dev); dev->priv_flags &= ~IFF_TX_SKB_SHARING; eth_hw_addr_random(dev); dev->tx_queue_len = TUN_READQ_SIZE; /* We prefer our own queue length */ break; } } /* Character device part */ /* Poll */ static unsigned int tun_chr_poll(struct file *file, poll_table * wait) { struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); struct sock *sk; unsigned int mask = 0; if (!tun) return POLLERR; sk = tun->socket.sk; tun_debug(KERN_INFO, tun, "tun_chr_poll\n"); poll_wait(file, &tun->wq.wait, wait); if (!skb_queue_empty(&sk->sk_receive_queue)) mask |= POLLIN | POLLRDNORM; if (sock_writeable(sk) || (!test_and_set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags) && sock_writeable(sk))) mask |= POLLOUT | POLLWRNORM; if (tun->dev->reg_state != NETREG_REGISTERED) mask = POLLERR; tun_put(tun); return mask; } /* prepad is the amount to reserve at front. len is length after that. * linear is a hint as to how much to copy (usually headers). */ static struct sk_buff *tun_alloc_skb(struct tun_struct *tun, size_t prepad, size_t len, size_t linear, int noblock) { struct sock *sk = tun->socket.sk; struct sk_buff *skb; int err; sock_update_classid(sk); /* Under a page? Don't bother with paged skb. */ if (prepad + len < PAGE_SIZE || !linear) linear = len; skb = sock_alloc_send_pskb(sk, prepad + linear, len - linear, noblock, &err); if (!skb) return ERR_PTR(err); skb_reserve(skb, prepad); skb_put(skb, linear); skb->data_len = len - linear; skb->len += len - linear; return skb; } /* set skb frags from iovec, this can move to core network code for reuse */ static int zerocopy_sg_from_iovec(struct sk_buff *skb, const struct iovec *from, int offset, size_t count) { int len = iov_length(from, count) - offset; int copy = skb_headlen(skb); int size, offset1 = 0; int i = 0; /* Skip over from offset */ while (count && (offset >= from->iov_len)) { offset -= from->iov_len; ++from; --count; } /* copy up to skb headlen */ while (count && (copy > 0)) { size = min_t(unsigned int, copy, from->iov_len - offset); if (copy_from_user(skb->data + offset1, from->iov_base + offset, size)) return -EFAULT; if (copy > size) { ++from; --count; offset = 0; } else offset += size; copy -= size; offset1 += size; } if (len == offset1) return 0; while (count--) { struct page *page[MAX_SKB_FRAGS]; int num_pages; unsigned long base; unsigned long truesize; len = from->iov_len - offset; if (!len) { offset = 0; ++from; continue; } base = (unsigned long)from->iov_base + offset; size = ((base & ~PAGE_MASK) + len + ~PAGE_MASK) >> PAGE_SHIFT; if (i + size > MAX_SKB_FRAGS) return -EMSGSIZE; num_pages = get_user_pages_fast(base, size, 0, &page[i]); if (num_pages != size) { for (i = 0; i < num_pages; i++) put_page(page[i]); return -EFAULT; } truesize = size * PAGE_SIZE; skb->data_len += len; skb->len += len; skb->truesize += truesize; atomic_add(truesize, &skb->sk->sk_wmem_alloc); while (len) { int off = base & ~PAGE_MASK; int size = min_t(int, len, PAGE_SIZE - off); __skb_fill_page_desc(skb, i, page[i], off, size); skb_shinfo(skb)->nr_frags++; /* increase sk_wmem_alloc */ base += size; len -= size; i++; } offset = 0; ++from; } return 0; } /* Get packet from user space buffer */ static ssize_t tun_get_user(struct tun_struct *tun, void *msg_control, const struct iovec *iv, size_t total_len, size_t count, int noblock) { struct tun_pi pi = { 0, cpu_to_be16(ETH_P_IP) }; struct sk_buff *skb; size_t len = total_len, align = NET_SKB_PAD; struct virtio_net_hdr gso = { 0 }; int offset = 0; int copylen; bool zerocopy = false; int err; if (!(tun->flags & TUN_NO_PI)) { if ((len -= sizeof(pi)) > total_len) return -EINVAL; if (memcpy_fromiovecend((void *)&pi, iv, 0, sizeof(pi))) return -EFAULT; offset += sizeof(pi); } if (tun->flags & TUN_VNET_HDR) { if ((len -= tun->vnet_hdr_sz) > total_len) return -EINVAL; if (memcpy_fromiovecend((void *)&gso, iv, offset, sizeof(gso))) return -EFAULT; if ((gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) && gso.csum_start + gso.csum_offset + 2 > gso.hdr_len) gso.hdr_len = gso.csum_start + gso.csum_offset + 2; if (gso.hdr_len > len) return -EINVAL; offset += tun->vnet_hdr_sz; } if ((tun->flags & TUN_TYPE_MASK) == TUN_TAP_DEV) { align += NET_IP_ALIGN; if (unlikely(len < ETH_HLEN || (gso.hdr_len && gso.hdr_len < ETH_HLEN))) return -EINVAL; } if (msg_control) zerocopy = true; if (zerocopy) { /* Userspace may produce vectors with count greater than * MAX_SKB_FRAGS, so we need to linearize parts of the skb * to let the rest of data to be fit in the frags. */ if (count > MAX_SKB_FRAGS) { copylen = iov_length(iv, count - MAX_SKB_FRAGS); if (copylen < offset) copylen = 0; else copylen -= offset; } else copylen = 0; /* There are 256 bytes to be copied in skb, so there is enough * room for skb expand head in case it is used. * The rest of the buffer is mapped from userspace. */ if (copylen < gso.hdr_len) copylen = gso.hdr_len; if (!copylen) copylen = GOODCOPY_LEN; } else copylen = len; skb = tun_alloc_skb(tun, align, copylen, gso.hdr_len, noblock); if (IS_ERR(skb)) { if (PTR_ERR(skb) != -EAGAIN) tun->dev->stats.rx_dropped++; return PTR_ERR(skb); } if (zerocopy) err = zerocopy_sg_from_iovec(skb, iv, offset, count); else err = skb_copy_datagram_from_iovec(skb, 0, iv, offset, len); if (err) { tun->dev->stats.rx_dropped++; kfree_skb(skb); return -EFAULT; } if (gso.flags & VIRTIO_NET_HDR_F_NEEDS_CSUM) { if (!skb_partial_csum_set(skb, gso.csum_start, gso.csum_offset)) { tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } } switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: if (tun->flags & TUN_NO_PI) { switch (skb->data[0] & 0xf0) { case 0x40: pi.proto = htons(ETH_P_IP); break; case 0x60: pi.proto = htons(ETH_P_IPV6); break; default: tun->dev->stats.rx_dropped++; kfree_skb(skb); return -EINVAL; } } skb_reset_mac_header(skb); skb->protocol = pi.proto; skb->dev = tun->dev; break; case TUN_TAP_DEV: skb->protocol = eth_type_trans(skb, tun->dev); break; } if (gso.gso_type != VIRTIO_NET_HDR_GSO_NONE) { pr_debug("GSO!\n"); switch (gso.gso_type & ~VIRTIO_NET_HDR_GSO_ECN) { case VIRTIO_NET_HDR_GSO_TCPV4: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV4; break; case VIRTIO_NET_HDR_GSO_TCPV6: skb_shinfo(skb)->gso_type = SKB_GSO_TCPV6; break; case VIRTIO_NET_HDR_GSO_UDP: skb_shinfo(skb)->gso_type = SKB_GSO_UDP; break; default: tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } if (gso.gso_type & VIRTIO_NET_HDR_GSO_ECN) skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; skb_shinfo(skb)->gso_size = gso.gso_size; if (skb_shinfo(skb)->gso_size == 0) { tun->dev->stats.rx_frame_errors++; kfree_skb(skb); return -EINVAL; } /* Header must be checked, and gso_segs computed. */ skb_shinfo(skb)->gso_type |= SKB_GSO_DODGY; skb_shinfo(skb)->gso_segs = 0; } /* copy skb_ubuf_info for callback when skb has no error */ if (zerocopy) { skb_shinfo(skb)->destructor_arg = msg_control; skb_shinfo(skb)->tx_flags |= SKBTX_DEV_ZEROCOPY; } netif_rx_ni(skb); tun->dev->stats.rx_packets++; tun->dev->stats.rx_bytes += len; return total_len; } static ssize_t tun_chr_aio_write(struct kiocb *iocb, const struct iovec *iv, unsigned long count, loff_t pos) { struct file *file = iocb->ki_filp; struct tun_struct *tun = tun_get(file); ssize_t result; if (!tun) return -EBADFD; tun_debug(KERN_INFO, tun, "tun_chr_write %ld\n", count); result = tun_get_user(tun, NULL, iv, iov_length(iv, count), count, file->f_flags & O_NONBLOCK); tun_put(tun); return result; } /* Put packet to the user space buffer */ static ssize_t tun_put_user(struct tun_struct *tun, struct sk_buff *skb, const struct iovec *iv, int len) { struct tun_pi pi = { 0, skb->protocol }; ssize_t total = 0; if (!(tun->flags & TUN_NO_PI)) { if ((len -= sizeof(pi)) < 0) return -EINVAL; if (len < skb->len) { /* Packet will be striped */ pi.flags |= TUN_PKT_STRIP; } if (memcpy_toiovecend(iv, (void *) &pi, 0, sizeof(pi))) return -EFAULT; total += sizeof(pi); } if (tun->flags & TUN_VNET_HDR) { struct virtio_net_hdr gso = { 0 }; /* no info leak */ if ((len -= tun->vnet_hdr_sz) < 0) return -EINVAL; if (skb_is_gso(skb)) { struct skb_shared_info *sinfo = skb_shinfo(skb); /* This is a hint as to how much should be linear. */ gso.hdr_len = skb_headlen(skb); gso.gso_size = sinfo->gso_size; if (sinfo->gso_type & SKB_GSO_TCPV4) gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV4; else if (sinfo->gso_type & SKB_GSO_TCPV6) gso.gso_type = VIRTIO_NET_HDR_GSO_TCPV6; else if (sinfo->gso_type & SKB_GSO_UDP) gso.gso_type = VIRTIO_NET_HDR_GSO_UDP; else { pr_err("unexpected GSO type: " "0x%x, gso_size %d, hdr_len %d\n", sinfo->gso_type, gso.gso_size, gso.hdr_len); print_hex_dump(KERN_ERR, "tun: ", DUMP_PREFIX_NONE, 16, 1, skb->head, min((int)gso.hdr_len, 64), true); WARN_ON_ONCE(1); return -EINVAL; } if (sinfo->gso_type & SKB_GSO_TCP_ECN) gso.gso_type |= VIRTIO_NET_HDR_GSO_ECN; } else gso.gso_type = VIRTIO_NET_HDR_GSO_NONE; if (skb->ip_summed == CHECKSUM_PARTIAL) { gso.flags = VIRTIO_NET_HDR_F_NEEDS_CSUM; gso.csum_start = skb_checksum_start_offset(skb); gso.csum_offset = skb->csum_offset; } else if (skb->ip_summed == CHECKSUM_UNNECESSARY) { gso.flags = VIRTIO_NET_HDR_F_DATA_VALID; } /* else everything is zero */ if (unlikely(memcpy_toiovecend(iv, (void *)&gso, total, sizeof(gso)))) return -EFAULT; total += tun->vnet_hdr_sz; } len = min_t(int, skb->len, len); skb_copy_datagram_const_iovec(skb, 0, iv, total, len); total += skb->len; tun->dev->stats.tx_packets++; tun->dev->stats.tx_bytes += len; return total; } static ssize_t tun_do_read(struct tun_struct *tun, struct kiocb *iocb, const struct iovec *iv, ssize_t len, int noblock) { DECLARE_WAITQUEUE(wait, current); struct sk_buff *skb; ssize_t ret = 0; tun_debug(KERN_INFO, tun, "tun_chr_read\n"); if (unlikely(!noblock)) add_wait_queue(&tun->wq.wait, &wait); while (len) { current->state = TASK_INTERRUPTIBLE; /* Read frames from the queue */ if (!(skb=skb_dequeue(&tun->socket.sk->sk_receive_queue))) { if (noblock) { ret = -EAGAIN; break; } if (signal_pending(current)) { ret = -ERESTARTSYS; break; } if (tun->dev->reg_state != NETREG_REGISTERED) { ret = -EIO; break; } /* Nothing to read, let's sleep */ schedule(); continue; } netif_wake_queue(tun->dev); ret = tun_put_user(tun, skb, iv, len); kfree_skb(skb); break; } current->state = TASK_RUNNING; if (unlikely(!noblock)) remove_wait_queue(&tun->wq.wait, &wait); return ret; } static ssize_t tun_chr_aio_read(struct kiocb *iocb, const struct iovec *iv, unsigned long count, loff_t pos) { struct file *file = iocb->ki_filp; struct tun_file *tfile = file->private_data; struct tun_struct *tun = __tun_get(tfile); ssize_t len, ret; if (!tun) return -EBADFD; len = iov_length(iv, count); if (len < 0) { ret = -EINVAL; goto out; } ret = tun_do_read(tun, iocb, iv, len, file->f_flags & O_NONBLOCK); ret = min_t(ssize_t, ret, len); out: tun_put(tun); return ret; } static void tun_setup(struct net_device *dev) { struct tun_struct *tun = netdev_priv(dev); tun->owner = -1; tun->group = -1; dev->ethtool_ops = &tun_ethtool_ops; dev->destructor = tun_free_netdev; } /* Trivial set of netlink ops to allow deleting tun or tap * device with netlink. */ static int tun_validate(struct nlattr *tb[], struct nlattr *data[]) { return -EINVAL; } static struct rtnl_link_ops tun_link_ops __read_mostly = { .kind = DRV_NAME, .priv_size = sizeof(struct tun_struct), .setup = tun_setup, .validate = tun_validate, }; static void tun_sock_write_space(struct sock *sk) { struct tun_struct *tun; wait_queue_head_t *wqueue; if (!sock_writeable(sk)) return; if (!test_and_clear_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags)) return; wqueue = sk_sleep(sk); if (wqueue && waitqueue_active(wqueue)) wake_up_interruptible_sync_poll(wqueue, POLLOUT | POLLWRNORM | POLLWRBAND); tun = tun_sk(sk)->tun; kill_fasync(&tun->fasync, SIGIO, POLL_OUT); } static void tun_sock_destruct(struct sock *sk) { free_netdev(tun_sk(sk)->tun->dev); } static int tun_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len) { struct tun_struct *tun = container_of(sock, struct tun_struct, socket); return tun_get_user(tun, m->msg_control, m->msg_iov, total_len, m->msg_iovlen, m->msg_flags & MSG_DONTWAIT); } static int tun_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *m, size_t total_len, int flags) { struct tun_struct *tun = container_of(sock, struct tun_struct, socket); int ret; if (flags & ~(MSG_DONTWAIT|MSG_TRUNC)) return -EINVAL; ret = tun_do_read(tun, iocb, m->msg_iov, total_len, flags & MSG_DONTWAIT); if (ret > total_len) { m->msg_flags |= MSG_TRUNC; ret = flags & MSG_TRUNC ? ret : total_len; } return ret; } static int tun_release(struct socket *sock) { if (sock->sk) sock_put(sock->sk); return 0; } /* Ops structure to mimic raw sockets with tun */ static const struct proto_ops tun_socket_ops = { .sendmsg = tun_sendmsg, .recvmsg = tun_recvmsg, .release = tun_release, }; static struct proto tun_proto = { .name = "tun", .owner = THIS_MODULE, .obj_size = sizeof(struct tun_sock), }; static int tun_flags(struct tun_struct *tun) { int flags = 0; if (tun->flags & TUN_TUN_DEV) flags |= IFF_TUN; else flags |= IFF_TAP; if (tun->flags & TUN_NO_PI) flags |= IFF_NO_PI; if (tun->flags & TUN_ONE_QUEUE) flags |= IFF_ONE_QUEUE; if (tun->flags & TUN_VNET_HDR) flags |= IFF_VNET_HDR; return flags; } static ssize_t tun_show_flags(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "0x%x\n", tun_flags(tun)); } static ssize_t tun_show_owner(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "%d\n", tun->owner); } static ssize_t tun_show_group(struct device *dev, struct device_attribute *attr, char *buf) { struct tun_struct *tun = netdev_priv(to_net_dev(dev)); return sprintf(buf, "%d\n", tun->group); } static DEVICE_ATTR(tun_flags, 0444, tun_show_flags, NULL); static DEVICE_ATTR(owner, 0444, tun_show_owner, NULL); static DEVICE_ATTR(group, 0444, tun_show_group, NULL); static int tun_set_iff(struct net *net, struct file *file, struct ifreq *ifr) { struct sock *sk; struct tun_struct *tun; struct net_device *dev; int err; dev = __dev_get_by_name(net, ifr->ifr_name); if (dev) { const struct cred *cred = current_cred(); if (ifr->ifr_flags & IFF_TUN_EXCL) return -EBUSY; if ((ifr->ifr_flags & IFF_TUN) && dev->netdev_ops == &tun_netdev_ops) tun = netdev_priv(dev); else if ((ifr->ifr_flags & IFF_TAP) && dev->netdev_ops == &tap_netdev_ops) tun = netdev_priv(dev); else return -EINVAL; if (((tun->owner != -1 && cred->euid != tun->owner) || (tun->group != -1 && !in_egroup_p(tun->group))) && !capable(CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_attach(tun->socket.sk); if (err < 0) return err; err = tun_attach(tun, file); if (err < 0) return err; } else { char *name; unsigned long flags = 0; if (!capable(CAP_NET_ADMIN)) return -EPERM; err = security_tun_dev_create(); if (err < 0) return err; /* Set dev type */ if (ifr->ifr_flags & IFF_TUN) { /* TUN device */ flags |= TUN_TUN_DEV; name = "tun%d"; } else if (ifr->ifr_flags & IFF_TAP) { /* TAP device */ flags |= TUN_TAP_DEV; name = "tap%d"; } else return -EINVAL; if (*ifr->ifr_name) name = ifr->ifr_name; dev = alloc_netdev(sizeof(struct tun_struct), name, tun_setup); if (!dev) return -ENOMEM; dev_net_set(dev, net); dev->rtnl_link_ops = &tun_link_ops; tun = netdev_priv(dev); tun->dev = dev; tun->flags = flags; tun->txflt.count = 0; tun->vnet_hdr_sz = sizeof(struct virtio_net_hdr); set_bit(SOCK_EXTERNALLY_ALLOCATED, &tun->socket.flags); err = -ENOMEM; sk = sk_alloc(&init_net, AF_UNSPEC, GFP_KERNEL, &tun_proto); if (!sk) goto err_free_dev; sk_change_net(sk, net); tun->socket.wq = &tun->wq; init_waitqueue_head(&tun->wq.wait); tun->socket.ops = &tun_socket_ops; sock_init_data(&tun->socket, sk); sk->sk_write_space = tun_sock_write_space; sk->sk_sndbuf = INT_MAX; sock_set_flag(sk, SOCK_ZEROCOPY); tun_sk(sk)->tun = tun; security_tun_dev_post_create(sk); tun_net_init(dev); dev->hw_features = NETIF_F_SG | NETIF_F_FRAGLIST | TUN_USER_FEATURES; dev->features = dev->hw_features; err = register_netdevice(tun->dev); if (err < 0) goto err_free_sk; if (device_create_file(&tun->dev->dev, &dev_attr_tun_flags) || device_create_file(&tun->dev->dev, &dev_attr_owner) || device_create_file(&tun->dev->dev, &dev_attr_group)) pr_err("Failed to create tun sysfs files\n"); sk->sk_destruct = tun_sock_destruct; err = tun_attach(tun, file); if (err < 0) goto failed; } tun_debug(KERN_INFO, tun, "tun_set_iff\n"); if (ifr->ifr_flags & IFF_NO_PI) tun->flags |= TUN_NO_PI; else tun->flags &= ~TUN_NO_PI; if (ifr->ifr_flags & IFF_ONE_QUEUE) tun->flags |= TUN_ONE_QUEUE; else tun->flags &= ~TUN_ONE_QUEUE; if (ifr->ifr_flags & IFF_VNET_HDR) tun->flags |= TUN_VNET_HDR; else tun->flags &= ~TUN_VNET_HDR; /* Make sure persistent devices do not get stuck in * xoff state. */ if (netif_running(tun->dev)) netif_wake_queue(tun->dev); strcpy(ifr->ifr_name, tun->dev->name); return 0; err_free_sk: tun_free_netdev(dev); err_free_dev: free_netdev(dev); failed: return err; } static int tun_get_iff(struct net *net, struct tun_struct *tun, struct ifreq *ifr) { tun_debug(KERN_INFO, tun, "tun_get_iff\n"); strcpy(ifr->ifr_name, tun->dev->name); ifr->ifr_flags = tun_flags(tun); return 0; } /* This is like a cut-down ethtool ops, except done via tun fd so no * privs required. */ static int set_offload(struct tun_struct *tun, unsigned long arg) { netdev_features_t features = 0; if (arg & TUN_F_CSUM) { features |= NETIF_F_HW_CSUM; arg &= ~TUN_F_CSUM; if (arg & (TUN_F_TSO4|TUN_F_TSO6)) { if (arg & TUN_F_TSO_ECN) { features |= NETIF_F_TSO_ECN; arg &= ~TUN_F_TSO_ECN; } if (arg & TUN_F_TSO4) features |= NETIF_F_TSO; if (arg & TUN_F_TSO6) features |= NETIF_F_TSO6; arg &= ~(TUN_F_TSO4|TUN_F_TSO6); } if (arg & TUN_F_UFO) { features |= NETIF_F_UFO; arg &= ~TUN_F_UFO; } } /* This gives the user a way to test for new features in future by * trying to set them. */ if (arg) return -EINVAL; tun->set_features = features; netdev_update_features(tun->dev); return 0; } static long __tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg, int ifreq_len) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; void __user* argp = (void __user*)arg; struct sock_fprog fprog; struct ifreq ifr; int sndbuf; int vnet_hdr_sz; int ret; if (cmd == TUNSETIFF || _IOC_TYPE(cmd) == 0x89) { if (copy_from_user(&ifr, argp, ifreq_len)) return -EFAULT; } else memset(&ifr, 0, sizeof(ifr)); if (cmd == TUNGETFEATURES) { /* Currently this just means: "what IFF flags are valid?". * This is needed because we never checked for invalid flags on * TUNSETIFF. */ return put_user(IFF_TUN | IFF_TAP | IFF_NO_PI | IFF_ONE_QUEUE | IFF_VNET_HDR, (unsigned int __user*)argp); } rtnl_lock(); tun = __tun_get(tfile); if (cmd == TUNSETIFF && !tun) { ifr.ifr_name[IFNAMSIZ-1] = '\0'; ret = tun_set_iff(tfile->net, file, &ifr); if (ret) goto unlock; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; goto unlock; } ret = -EBADFD; if (!tun) goto unlock; tun_debug(KERN_INFO, tun, "tun_chr_ioctl cmd %d\n", cmd); ret = 0; switch (cmd) { case TUNGETIFF: ret = tun_get_iff(current->nsproxy->net_ns, tun, &ifr); if (ret) break; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case TUNSETNOCSUM: /* Disable/Enable checksum */ /* [unimplemented] */ tun_debug(KERN_INFO, tun, "ignored: set checksum %s\n", arg ? "disabled" : "enabled"); break; case TUNSETPERSIST: /* Disable/Enable persist mode */ if (arg) tun->flags |= TUN_PERSIST; else tun->flags &= ~TUN_PERSIST; tun_debug(KERN_INFO, tun, "persist %s\n", arg ? "enabled" : "disabled"); break; case TUNSETOWNER: /* Set owner of the device */ tun->owner = (uid_t) arg; tun_debug(KERN_INFO, tun, "owner set to %d\n", tun->owner); break; case TUNSETGROUP: /* Set group of the device */ tun->group= (gid_t) arg; tun_debug(KERN_INFO, tun, "group set to %d\n", tun->group); break; case TUNSETLINK: /* Only allow setting the type when the interface is down */ if (tun->dev->flags & IFF_UP) { tun_debug(KERN_INFO, tun, "Linktype set failed because interface is up\n"); ret = -EBUSY; } else { tun->dev->type = (int) arg; tun_debug(KERN_INFO, tun, "linktype set to %d\n", tun->dev->type); ret = 0; } break; #ifdef TUN_DEBUG case TUNSETDEBUG: tun->debug = arg; break; #endif case TUNSETOFFLOAD: ret = set_offload(tun, arg); break; case TUNSETTXFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV) break; ret = update_filter(&tun->txflt, (void __user *)arg); break; case SIOCGIFHWADDR: /* Get hw address */ memcpy(ifr.ifr_hwaddr.sa_data, tun->dev->dev_addr, ETH_ALEN); ifr.ifr_hwaddr.sa_family = tun->dev->type; if (copy_to_user(argp, &ifr, ifreq_len)) ret = -EFAULT; break; case SIOCSIFHWADDR: /* Set hw address */ tun_debug(KERN_DEBUG, tun, "set hw address: %pM\n", ifr.ifr_hwaddr.sa_data); ret = dev_set_mac_address(tun->dev, &ifr.ifr_hwaddr); break; case TUNGETSNDBUF: sndbuf = tun->socket.sk->sk_sndbuf; if (copy_to_user(argp, &sndbuf, sizeof(sndbuf))) ret = -EFAULT; break; case TUNSETSNDBUF: if (copy_from_user(&sndbuf, argp, sizeof(sndbuf))) { ret = -EFAULT; break; } tun->socket.sk->sk_sndbuf = sndbuf; break; case TUNGETVNETHDRSZ: vnet_hdr_sz = tun->vnet_hdr_sz; if (copy_to_user(argp, &vnet_hdr_sz, sizeof(vnet_hdr_sz))) ret = -EFAULT; break; case TUNSETVNETHDRSZ: if (copy_from_user(&vnet_hdr_sz, argp, sizeof(vnet_hdr_sz))) { ret = -EFAULT; break; } if (vnet_hdr_sz < (int)sizeof(struct virtio_net_hdr)) { ret = -EINVAL; break; } tun->vnet_hdr_sz = vnet_hdr_sz; break; case TUNATTACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV) break; ret = -EFAULT; if (copy_from_user(&fprog, argp, sizeof(fprog))) break; ret = sk_attach_filter(&fprog, tun->socket.sk); break; case TUNDETACHFILTER: /* Can be set only for TAPs */ ret = -EINVAL; if ((tun->flags & TUN_TYPE_MASK) != TUN_TAP_DEV) break; ret = sk_detach_filter(tun->socket.sk); break; default: ret = -EINVAL; break; } unlock: rtnl_unlock(); if (tun) tun_put(tun); return ret; } static long tun_chr_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { return __tun_chr_ioctl(file, cmd, arg, sizeof (struct ifreq)); } #ifdef CONFIG_COMPAT static long tun_chr_compat_ioctl(struct file *file, unsigned int cmd, unsigned long arg) { switch (cmd) { case TUNSETIFF: case TUNGETIFF: case TUNSETTXFILTER: case TUNGETSNDBUF: case TUNSETSNDBUF: case SIOCGIFHWADDR: case SIOCSIFHWADDR: arg = (unsigned long)compat_ptr(arg); break; default: arg = (compat_ulong_t)arg; break; } /* * compat_ifreq is shorter than ifreq, so we must not access beyond * the end of that structure. All fields that are used in this * driver are compatible though, we don't need to convert the * contents. */ return __tun_chr_ioctl(file, cmd, arg, sizeof(struct compat_ifreq)); } #endif /* CONFIG_COMPAT */ static int tun_chr_fasync(int fd, struct file *file, int on) { struct tun_struct *tun = tun_get(file); int ret; if (!tun) return -EBADFD; tun_debug(KERN_INFO, tun, "tun_chr_fasync %d\n", on); if ((ret = fasync_helper(fd, file, on, &tun->fasync)) < 0) goto out; if (on) { ret = __f_setown(file, task_pid(current), PIDTYPE_PID, 0); if (ret) goto out; tun->flags |= TUN_FASYNC; } else tun->flags &= ~TUN_FASYNC; ret = 0; out: tun_put(tun); return ret; } static int tun_chr_open(struct inode *inode, struct file * file) { struct tun_file *tfile; DBG1(KERN_INFO, "tunX: tun_chr_open\n"); tfile = kmalloc(sizeof(*tfile), GFP_KERNEL); if (!tfile) return -ENOMEM; atomic_set(&tfile->count, 0); tfile->tun = NULL; tfile->net = get_net(current->nsproxy->net_ns); file->private_data = tfile; return 0; } static int tun_chr_close(struct inode *inode, struct file *file) { struct tun_file *tfile = file->private_data; struct tun_struct *tun; tun = __tun_get(tfile); if (tun) { struct net_device *dev = tun->dev; tun_debug(KERN_INFO, tun, "tun_chr_close\n"); __tun_detach(tun); /* If desirable, unregister the netdevice. */ if (!(tun->flags & TUN_PERSIST)) { rtnl_lock(); if (dev->reg_state == NETREG_REGISTERED) unregister_netdevice(dev); rtnl_unlock(); } } tun = tfile->tun; if (tun) sock_put(tun->socket.sk); put_net(tfile->net); kfree(tfile); return 0; } static const struct file_operations tun_fops = { .owner = THIS_MODULE, .llseek = no_llseek, .read = do_sync_read, .aio_read = tun_chr_aio_read, .write = do_sync_write, .aio_write = tun_chr_aio_write, .poll = tun_chr_poll, .unlocked_ioctl = tun_chr_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = tun_chr_compat_ioctl, #endif .open = tun_chr_open, .release = tun_chr_close, .fasync = tun_chr_fasync }; static struct miscdevice tun_miscdev = { .minor = TUN_MINOR, .name = "tun", .nodename = "net/tun", .fops = &tun_fops, }; /* ethtool interface */ static int tun_get_settings(struct net_device *dev, struct ethtool_cmd *cmd) { cmd->supported = 0; cmd->advertising = 0; ethtool_cmd_speed_set(cmd, SPEED_10); cmd->duplex = DUPLEX_FULL; cmd->port = PORT_TP; cmd->phy_address = 0; cmd->transceiver = XCVR_INTERNAL; cmd->autoneg = AUTONEG_DISABLE; cmd->maxtxpkt = 0; cmd->maxrxpkt = 0; return 0; } static void tun_get_drvinfo(struct net_device *dev, struct ethtool_drvinfo *info) { struct tun_struct *tun = netdev_priv(dev); strlcpy(info->driver, DRV_NAME, sizeof(info->driver)); strlcpy(info->version, DRV_VERSION, sizeof(info->version)); switch (tun->flags & TUN_TYPE_MASK) { case TUN_TUN_DEV: strlcpy(info->bus_info, "tun", sizeof(info->bus_info)); break; case TUN_TAP_DEV: strlcpy(info->bus_info, "tap", sizeof(info->bus_info)); break; } } static u32 tun_get_msglevel(struct net_device *dev) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); return tun->debug; #else return -EOPNOTSUPP; #endif } static void tun_set_msglevel(struct net_device *dev, u32 value) { #ifdef TUN_DEBUG struct tun_struct *tun = netdev_priv(dev); tun->debug = value; #endif } static const struct ethtool_ops tun_ethtool_ops = { .get_settings = tun_get_settings, .get_drvinfo = tun_get_drvinfo, .get_msglevel = tun_get_msglevel, .set_msglevel = tun_set_msglevel, .get_link = ethtool_op_get_link, }; static int __init tun_init(void) { int ret = 0; pr_info("%s, %s\n", DRV_DESCRIPTION, DRV_VERSION); pr_info("%s\n", DRV_COPYRIGHT); ret = rtnl_link_register(&tun_link_ops); if (ret) { pr_err("Can't register link_ops\n"); goto err_linkops; } ret = misc_register(&tun_miscdev); if (ret) { pr_err("Can't register misc device %d\n", TUN_MINOR); goto err_misc; } return 0; err_misc: rtnl_link_unregister(&tun_link_ops); err_linkops: return ret; } static void tun_cleanup(void) { misc_deregister(&tun_miscdev); rtnl_link_unregister(&tun_link_ops); } /* Get an underlying socket object from tun file. Returns error unless file is * attached to a device. The returned object works like a packet socket, it * can be used for sock_sendmsg/sock_recvmsg. The caller is responsible for * holding a reference to the file for as long as the socket is in use. */ struct socket *tun_get_socket(struct file *file) { struct tun_struct *tun; if (file->f_op != &tun_fops) return ERR_PTR(-EINVAL); tun = tun_get(file); if (!tun) return ERR_PTR(-EBADFD); tun_put(tun); return &tun->socket; } EXPORT_SYMBOL_GPL(tun_get_socket); module_init(tun_init); module_exit(tun_cleanup); MODULE_DESCRIPTION(DRV_DESCRIPTION); MODULE_AUTHOR(DRV_COPYRIGHT); MODULE_LICENSE("GPL"); MODULE_ALIAS_MISCDEV(TUN_MINOR); MODULE_ALIAS("devname:net/tun");
./CrossVul/dataset_final_sorted/CWE-200/c/good_3840_0
crossvul-cpp_data_good_4074_0
/*-------------------------------------------------------------------------*/ /** @file iniparser.c @author N. Devillard @brief Parser for ini files. */ /*--------------------------------------------------------------------------*/ /*---------------------------- Includes ------------------------------------*/ #include <ctype.h> #include "iniparser.h" /*---------------------------- Defines -------------------------------------*/ #define ASCIILINESZ (1024) #define INI_INVALID_KEY ((char*)-1) /*--------------------------------------------------------------------------- Private to this module ---------------------------------------------------------------------------*/ /** * This enum stores the status for each parsed line (internal use only). */ typedef enum _line_status_ { LINE_UNPROCESSED, LINE_ERROR, LINE_EMPTY, LINE_COMMENT, LINE_SECTION, LINE_VALUE } line_status ; /*-------------------------------------------------------------------------*/ /** @brief Convert a string to lowercase. @param in String to convert. @param out Output buffer. @param len Size of the out buffer. @return ptr to the out buffer or NULL if an error occured. This function convert a string into lowercase. At most len - 1 elements of the input string will be converted. */ /*--------------------------------------------------------------------------*/ static const char * strlwc(const char * in, char *out, unsigned len) { unsigned i ; if (in==NULL || out == NULL || len==0) return NULL ; i=0 ; while (in[i] != '\0' && i < len-1) { out[i] = (char)tolower((int)in[i]); i++ ; } out[i] = '\0'; return out ; } /*-------------------------------------------------------------------------*/ /** @brief Copy string in a newly mallocced area @param str String to copy. @return str Copied version of the given string allocated with malloc Original strdup is not portable, need to implement our own */ /*--------------------------------------------------------------------------*/ static char * _strdup(const char *s) { char * copy = (char*) malloc(strlen(s)); strcpy(copy, s); return copy ; } /*-------------------------------------------------------------------------*/ /** @brief Remove blanks at the beginning and the end of a string. @param str String to parse and alter. @return unsigned New size of the string. */ /*--------------------------------------------------------------------------*/ unsigned strstrip(char * s) { char *last = NULL ; char *dest = s; if (s==NULL) return 0; last = s + strlen(s); while (isspace((int)*s) && *s) s++; while (last > s) { if (!isspace((int)*(last-1))) break ; last -- ; } *last = (char)0; memmove(dest,s,last - s + 1); return last - s; } /*-------------------------------------------------------------------------*/ /** @brief Get number of sections in a dictionary @param d Dictionary to examine @return int Number of sections found in dictionary This function returns the number of sections found in a dictionary. The test to recognize sections is done on the string stored in the dictionary: a section name is given as "section" whereas a key is stored as "section:key", thus the test looks for entries that do not contain a colon. This clearly fails in the case a section name contains a colon, but this should simply be avoided. This function returns -1 in case of error. */ /*--------------------------------------------------------------------------*/ int iniparser_getnsec(const dictionary * d) { int i ; int nsec ; if (d==NULL) return -1 ; nsec=0 ; for (i=0 ; i<d->size ; i++) { if (d->key[i]==NULL) continue ; if (strchr(d->key[i], ':')==NULL) { nsec ++ ; } } return nsec ; } /*-------------------------------------------------------------------------*/ /** @brief Get name for section n in a dictionary. @param d Dictionary to examine @param n Section number (from 0 to nsec-1). @return Pointer to char string This function locates the n-th section in a dictionary and returns its name as a pointer to a string statically allocated inside the dictionary. Do not free or modify the returned string! This function returns NULL in case of error. */ /*--------------------------------------------------------------------------*/ const char * iniparser_getsecname(const dictionary * d, int n) { int i ; int foundsec ; if (d==NULL || n<0) return NULL ; foundsec=0 ; for (i=0 ; i<d->size ; i++) { if (d->key[i]==NULL) continue ; if (strchr(d->key[i], ':')==NULL) { foundsec++ ; if (foundsec>n) break ; } } if (foundsec<=n) { return NULL ; } return d->key[i] ; } /*-------------------------------------------------------------------------*/ /** @brief Dump a dictionary to an opened file pointer. @param d Dictionary to dump. @param f Opened file pointer to dump to. @return void This function prints out the contents of a dictionary, one element by line, onto the provided file pointer. It is OK to specify @c stderr or @c stdout as output files. This function is meant for debugging purposes mostly. */ /*--------------------------------------------------------------------------*/ void iniparser_dump(const dictionary * d, FILE * f) { int i ; if (d==NULL || f==NULL) return ; for (i=0 ; i<d->size ; i++) { if (d->key[i]==NULL) continue ; if (d->val[i]!=NULL) { fprintf(f, "[%s]=[%s]\n", d->key[i], d->val[i]); } else { fprintf(f, "[%s]=UNDEF\n", d->key[i]); } } return ; } /*-------------------------------------------------------------------------*/ /** @brief Save a dictionary to a loadable ini file @param d Dictionary to dump @param f Opened file pointer to dump to @return void This function dumps a given dictionary into a loadable ini file. It is Ok to specify @c stderr or @c stdout as output files. */ /*--------------------------------------------------------------------------*/ void iniparser_dump_ini(const dictionary * d, FILE * f) { int i ; int nsec ; const char * secname ; if (d==NULL || f==NULL) return ; nsec = iniparser_getnsec(d); if (nsec<1) { /* No section in file: dump all keys as they are */ for (i=0 ; i<d->size ; i++) { if (d->key[i]==NULL) continue ; fprintf(f, "%s = %s\n", d->key[i], d->val[i]); } return ; } for (i=0 ; i<nsec ; i++) { secname = iniparser_getsecname(d, i) ; iniparser_dumpsection_ini(d, secname, f); } fprintf(f, "\n"); return ; } /*-------------------------------------------------------------------------*/ /** @brief Save a dictionary section to a loadable ini file @param d Dictionary to dump @param s Section name of dictionary to dump @param f Opened file pointer to dump to @return void This function dumps a given section of a given dictionary into a loadable ini file. It is Ok to specify @c stderr or @c stdout as output files. */ /*--------------------------------------------------------------------------*/ void iniparser_dumpsection_ini(const dictionary * d, const char * s, FILE * f) { int j ; char keym[ASCIILINESZ+1]; int seclen ; if (d==NULL || f==NULL) return ; if (! iniparser_find_entry(d, s)) return ; seclen = (int)strlen(s); fprintf(f, "\n[%s]\n", s); sprintf(keym, "%s:", s); for (j=0 ; j<d->size ; j++) { if (d->key[j]==NULL) continue ; if (!strncmp(d->key[j], keym, seclen+1)) { fprintf(f, "%-30s = %s\n", d->key[j]+seclen+1, d->val[j] ? d->val[j] : ""); } } fprintf(f, "\n"); return ; } /*-------------------------------------------------------------------------*/ /** @brief Get the number of keys in a section of a dictionary. @param d Dictionary to examine @param s Section name of dictionary to examine @return Number of keys in section */ /*--------------------------------------------------------------------------*/ int iniparser_getsecnkeys(const dictionary * d, const char * s) { int seclen, nkeys ; char keym[ASCIILINESZ+1]; int j ; nkeys = 0; if (d==NULL) return nkeys; if (! iniparser_find_entry(d, s)) return nkeys; seclen = (int)strlen(s); sprintf(keym, "%s:", s); for (j=0 ; j<d->size ; j++) { if (d->key[j]==NULL) continue ; if (!strncmp(d->key[j], keym, seclen+1)) nkeys++; } return nkeys; } /*-------------------------------------------------------------------------*/ /** @brief Get the number of keys in a section of a dictionary. @param d Dictionary to examine @param s Section name of dictionary to examine @param keys Already allocated array to store the keys in @return The pointer passed as `keys` argument or NULL in case of error This function queries a dictionary and finds all keys in a given section. The keys argument should be an array of pointers which size has been determined by calling `iniparser_getsecnkeys` function prior to this one. Each pointer in the returned char pointer-to-pointer is pointing to a string allocated in the dictionary; do not free or modify them. */ /*--------------------------------------------------------------------------*/ const char ** iniparser_getseckeys(const dictionary * d, const char * s, const char ** keys) { int i, j, seclen ; char keym[ASCIILINESZ+1]; if (d==NULL || keys==NULL) return NULL; if (! iniparser_find_entry(d, s)) return NULL; seclen = (int)strlen(s); sprintf(keym, "%s:", s); i = 0; for (j=0 ; j<d->size ; j++) { if (d->key[j]==NULL) continue ; if (!strncmp(d->key[j], keym, seclen+1)) { keys[i] = d->key[j]; i++; } } return keys; } /*-------------------------------------------------------------------------*/ /** @brief Get the string associated to a key @param d Dictionary to search @param key Key string to look for @param def Default value to return if key not found. @return pointer to statically allocated character string This function queries a dictionary for a key. A key as read from an ini file is given as "section:key". If the key cannot be found, the pointer passed as 'def' is returned. The returned char pointer is pointing to a string allocated in the dictionary, do not free or modify it. */ /*--------------------------------------------------------------------------*/ const char * iniparser_getstring(const dictionary * d, const char * key, const char * def) { const char * lc_key ; const char * sval ; char tmp_str[ASCIILINESZ+1]; if (d==NULL || key==NULL) return def ; lc_key = strlwc(key, tmp_str, sizeof(tmp_str)); sval = dictionary_get(d, lc_key, def); return sval ; } /*-------------------------------------------------------------------------*/ /** @brief Get the string associated to a key, convert to an int @param d Dictionary to search @param key Key string to look for @param notfound Value to return in case of error @return integer This function queries a dictionary for a key. A key as read from an ini file is given as "section:key". If the key cannot be found, the notfound value is returned. Supported values for integers include the usual C notation so decimal, octal (starting with 0) and hexadecimal (starting with 0x) are supported. Examples: "42" -> 42 "042" -> 34 (octal -> decimal) "0x42" -> 66 (hexa -> decimal) Warning: the conversion may overflow in various ways. Conversion is totally outsourced to strtol(), see the associated man page for overflow handling. Credits: Thanks to A. Becker for suggesting strtol() */ /*--------------------------------------------------------------------------*/ int iniparser_getint(const dictionary * d, const char * key, int notfound) { const char * str ; str = iniparser_getstring(d, key, INI_INVALID_KEY); if (str==INI_INVALID_KEY) return notfound ; return (int)strtol(str, NULL, 0); } /*-------------------------------------------------------------------------*/ /** @brief Get the string associated to a key, convert to a double @param d Dictionary to search @param key Key string to look for @param notfound Value to return in case of error @return double This function queries a dictionary for a key. A key as read from an ini file is given as "section:key". If the key cannot be found, the notfound value is returned. */ /*--------------------------------------------------------------------------*/ double iniparser_getdouble(const dictionary * d, const char * key, double notfound) { const char * str ; str = iniparser_getstring(d, key, INI_INVALID_KEY); if (str==INI_INVALID_KEY) return notfound ; return atof(str); } /*-------------------------------------------------------------------------*/ /** @brief Get the string associated to a key, convert to a boolean @param d Dictionary to search @param key Key string to look for @param notfound Value to return in case of error @return integer This function queries a dictionary for a key. A key as read from an ini file is given as "section:key". If the key cannot be found, the notfound value is returned. A true boolean is found if one of the following is matched: - A string starting with 'y' - A string starting with 'Y' - A string starting with 't' - A string starting with 'T' - A string starting with '1' A false boolean is found if one of the following is matched: - A string starting with 'n' - A string starting with 'N' - A string starting with 'f' - A string starting with 'F' - A string starting with '0' The notfound value returned if no boolean is identified, does not necessarily have to be 0 or 1. */ /*--------------------------------------------------------------------------*/ int iniparser_getboolean(const dictionary * d, const char * key, int notfound) { int ret ; const char * c ; c = iniparser_getstring(d, key, INI_INVALID_KEY); if (c==INI_INVALID_KEY) return notfound ; if (c[0]=='y' || c[0]=='Y' || c[0]=='1' || c[0]=='t' || c[0]=='T') { ret = 1 ; } else if (c[0]=='n' || c[0]=='N' || c[0]=='0' || c[0]=='f' || c[0]=='F') { ret = 0 ; } else { ret = notfound ; } return ret; } /*-------------------------------------------------------------------------*/ /** @brief Finds out if a given entry exists in a dictionary @param ini Dictionary to search @param entry Name of the entry to look for @return integer 1 if entry exists, 0 otherwise Finds out if a given entry exists in the dictionary. Since sections are stored as keys with NULL associated values, this is the only way of querying for the presence of sections in a dictionary. */ /*--------------------------------------------------------------------------*/ int iniparser_find_entry(const dictionary * ini, const char * entry) { int found=0 ; if (iniparser_getstring(ini, entry, INI_INVALID_KEY)!=INI_INVALID_KEY) { found = 1 ; } return found ; } /*-------------------------------------------------------------------------*/ /** @brief Set an entry in a dictionary. @param ini Dictionary to modify. @param entry Entry to modify (entry name) @param val New value to associate to the entry. @return int 0 if Ok, -1 otherwise. If the given entry can be found in the dictionary, it is modified to contain the provided value. If it cannot be found, the entry is created. It is Ok to set val to NULL. */ /*--------------------------------------------------------------------------*/ int iniparser_set(dictionary * ini, const char * entry, const char * val) { char tmp_str[ASCIILINESZ+1]; return dictionary_set(ini, strlwc(entry, tmp_str, sizeof(tmp_str)), val) ; } /*-------------------------------------------------------------------------*/ /** @brief Delete an entry in a dictionary @param ini Dictionary to modify @param entry Entry to delete (entry name) @return void If the given entry can be found, it is deleted from the dictionary. */ /*--------------------------------------------------------------------------*/ void iniparser_unset(dictionary * ini, const char * entry) { char tmp_str[ASCIILINESZ+1]; dictionary_unset(ini, strlwc(entry, tmp_str, sizeof(tmp_str))); } /*-------------------------------------------------------------------------*/ /** @brief Load a single line from an INI file @param input_line Input line, may be concatenated multi-line input @param section Output space to store section @param key Output space to store key @param value Output space to store value @return line_status value */ /*--------------------------------------------------------------------------*/ static line_status iniparser_line( const char * input_line, char * section, char * key, char * value) { line_status sta ; char * line = NULL; size_t len ; line = _strdup(input_line); len = strstrip(line); sta = LINE_UNPROCESSED ; if (len<1) { /* Empty line */ sta = LINE_EMPTY ; } else if (line[0]=='#' || line[0]==';') { /* Comment line */ sta = LINE_COMMENT ; } else if (line[0]=='[' && line[len-1]==']') { /* Section name */ sscanf(line, "[%[^]]", section); strstrip(section); strlwc(section, section, len); sta = LINE_SECTION ; } else if (sscanf (line, "%[^=] = \"%[^\"]\"", key, value) == 2 || sscanf (line, "%[^=] = '%[^\']'", key, value) == 2 || sscanf (line, "%[^=] = %[^;#]", key, value) == 2) { /* Usual key=value, with or without comments */ strstrip(key); strlwc(key, key, len); strstrip(value); /* * sscanf cannot handle '' or "" as empty values * this is done here */ if (!strcmp(value, "\"\"") || (!strcmp(value, "''"))) { value[0]=0 ; } sta = LINE_VALUE ; } else if (sscanf(line, "%[^=] = %[;#]", key, value)==2 || sscanf(line, "%[^=] %[=]", key, value) == 2) { /* * Special cases: * key= * key=; * key=# */ strstrip(key); strlwc(key, key, len); value[0]=0 ; sta = LINE_VALUE ; } else { /* Generate syntax error */ sta = LINE_ERROR ; } free(line); return sta ; } /*-------------------------------------------------------------------------*/ /** @brief Parse an ini file and return an allocated dictionary object @param ininame Name of the ini file to read. @return Pointer to newly allocated dictionary This is the parser for ini files. This function is called, providing the name of the file to be read. It returns a dictionary object that should not be accessed directly, but through accessor functions instead. The returned dictionary must be freed using iniparser_freedict(). */ /*--------------------------------------------------------------------------*/ dictionary * iniparser_load(const char * ininame, load_options options) { FILE * in ; char line [ASCIILINESZ+1] ; char section [ASCIILINESZ+1] ; char key [ASCIILINESZ+1] ; char tmp [(ASCIILINESZ * 2) + 1] ; char val [ASCIILINESZ+1] ; int last=0 ; int len ; int lineno=0 ; int errs=0; dictionary * dict ; if ((in=fopen(ininame, "r"))==NULL) { fprintf(stderr, "iniparser: cannot open %s\n", ininame); return NULL ; } dict = dictionary_new(0) ; if (!dict) { fclose(in); return NULL ; } memset(line, 0, ASCIILINESZ); memset(section, 0, ASCIILINESZ); memset(key, 0, ASCIILINESZ); memset(val, 0, ASCIILINESZ); last=0 ; while (fgets(line+last, ASCIILINESZ-last, in)!=NULL) { lineno++ ; len = (int)strlen(line)-1; if (len==0) continue; /* Safety check against buffer overflows */ if (line[len]!='\n' && !feof(in)) { fprintf(stderr, "iniparser: input line too long in %s (%d)\n", ininame, lineno); dictionary_del(dict); fclose(in); return NULL ; } /* Get rid of \n and spaces at end of line */ while ((len>=0) && ((line[len]=='\n') || (isspace(line[len])))) { line[len]=0 ; len-- ; } if (len < 0) { /* Line was entirely \n and/or spaces */ len = 0; } /* Detect multi-line */ if (line[len]=='\\') { /* Multi-line value */ last=len ; continue ; } else { last=0 ; } switch (iniparser_line(line, section, key, val)) { case LINE_EMPTY: case LINE_COMMENT: break ; case LINE_SECTION: errs = dictionary_set(dict, section, NULL); break ; case LINE_VALUE: sprintf(tmp, "%s:%s", section, key); errs = dictionary_set(dict, tmp, val) ; break ; case LINE_ERROR: if(options & HIDE_ERRORED_LINE_CONTENT) { fprintf(stderr, "iniparser: syntax error in %s (%d)\n", ininame, lineno); } else { fprintf(stderr, "iniparser: syntax error in %s (%d):\n", ininame, lineno); fprintf(stderr, "-> %s\n", line); } errs++ ; break; default: break ; } memset(line, 0, ASCIILINESZ); last=0; if (errs<0) { fprintf(stderr, "iniparser: memory allocation failure\n"); break ; } } if (errs) { dictionary_del(dict); dict = NULL ; } fclose(in); return dict ; } /*-------------------------------------------------------------------------*/ /** @brief Free all memory associated to an ini dictionary @param d Dictionary to free @return void Free all memory associated to an ini dictionary. It is mandatory to call this function before the dictionary object gets out of the current context. */ /*--------------------------------------------------------------------------*/ void iniparser_freedict(dictionary * d) { dictionary_del(d); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_4074_0
crossvul-cpp_data_good_867_1
/* * Copyright (C) 2014-2019 Yubico AB - See COPYING */ #include "util.h" #include <u2f-server.h> #include <u2f-host.h> #include <stdlib.h> #include <fcntl.h> #include <sys/stat.h> #include <stdarg.h> #include <syslog.h> #include <pwd.h> #include <errno.h> #include <unistd.h> #include <string.h> int get_devices_from_authfile(const char *authfile, const char *username, unsigned max_devs, int verbose, FILE *debug_file, device_t *devices, unsigned *n_devs) { char *buf = NULL; char *s_user, *s_token; int retval = 0; int fd = -1; struct stat st; struct passwd *pw = NULL, pw_s; char buffer[BUFSIZE]; int gpu_ret; FILE *opwfile = NULL; unsigned i, j; /* Ensure we never return uninitialized count. */ *n_devs = 0; fd = open(authfile, O_RDONLY | O_CLOEXEC | O_NOCTTY); if (fd < 0) { if (verbose) D(debug_file, "Cannot open file: %s (%s)", authfile, strerror(errno)); goto err; } if (fstat(fd, &st) < 0) { if (verbose) D(debug_file, "Cannot stat file: %s (%s)", authfile, strerror(errno)); goto err; } if (!S_ISREG(st.st_mode)) { if (verbose) D(debug_file, "%s is not a regular file", authfile); goto err; } if (st.st_size == 0) { if (verbose) D(debug_file, "File %s is empty", authfile); goto err; } gpu_ret = getpwuid_r(st.st_uid, &pw_s, buffer, sizeof(buffer), &pw); if (gpu_ret != 0 || pw == NULL) { D(debug_file, "Unable to retrieve credentials for uid %u, (%s)", st.st_uid, strerror(errno)); goto err; } if (strcmp(pw->pw_name, username) != 0 && strcmp(pw->pw_name, "root") != 0) { if (strcmp(username, "root") != 0) { D(debug_file, "The owner of the authentication file is neither %s nor root", username); } else { D(debug_file, "The owner of the authentication file is not root"); } goto err; } opwfile = fdopen(fd, "r"); if (opwfile == NULL) { if (verbose) D(debug_file, "fdopen: %s", strerror(errno)); goto err; } else { fd = -1; /* fd belongs to opwfile */ } buf = malloc(sizeof(char) * (DEVSIZE * max_devs)); if (!buf) { if (verbose) D(debug_file, "Unable to allocate memory"); goto err; } retval = -2; while (fgets(buf, (int)(DEVSIZE * (max_devs - 1)), opwfile)) { char *saveptr = NULL; if (buf[strlen(buf) - 1] == '\n') buf[strlen(buf) - 1] = '\0'; if (verbose) D(debug_file, "Authorization line: %s", buf); s_user = strtok_r(buf, ":", &saveptr); if (s_user && strcmp(username, s_user) == 0) { if (verbose) D(debug_file, "Matched user: %s", s_user); retval = -1; // We found at least one line for the user // only keep last line for this user for (i = 0; i < *n_devs; i++) { free(devices[i].keyHandle); free(devices[i].publicKey); devices[i].keyHandle = NULL; devices[i].publicKey = NULL; } *n_devs = 0; i = 0; while ((s_token = strtok_r(NULL, ",", &saveptr))) { devices[i].keyHandle = NULL; devices[i].publicKey = NULL; if ((*n_devs)++ > MAX_DEVS - 1) { *n_devs = MAX_DEVS; if (verbose) D(debug_file, "Found more than %d devices, ignoring the remaining ones", MAX_DEVS); break; } if (verbose) D(debug_file, "KeyHandle for device number %d: %s", i + 1, s_token); devices[i].keyHandle = strdup(s_token); if (!devices[i].keyHandle) { if (verbose) D(debug_file, "Unable to allocate memory for keyHandle number %d", i); goto err; } s_token = strtok_r(NULL, ":", &saveptr); if (!s_token) { if (verbose) D(debug_file, "Unable to retrieve publicKey number %d", i + 1); goto err; } if (verbose) D(debug_file, "publicKey for device number %d: %s", i + 1, s_token); if (strlen(s_token) % 2 != 0) { if (verbose) D(debug_file, "Length of key number %d not even", i + 1); goto err; } devices[i].key_len = strlen(s_token) / 2; if (verbose) D(debug_file, "Length of key number %d is %zu", i + 1, devices[i].key_len); devices[i].publicKey = malloc((sizeof(unsigned char) * devices[i].key_len)); if (!devices[i].publicKey) { if (verbose) D(debug_file, "Unable to allocate memory for publicKey number %d", i); goto err; } for (j = 0; j < devices[i].key_len; j++) { unsigned int x; if (sscanf(&s_token[2 * j], "%2x", &x) != 1) { if (verbose) D(debug_file, "Invalid hex number in key"); goto err; } devices[i].publicKey[j] = (unsigned char)x; } i++; } } } if (verbose) D(debug_file, "Found %d device(s) for user %s", *n_devs, username); retval = 1; goto out; err: for (i = 0; i < *n_devs; i++) { free(devices[i].keyHandle); free(devices[i].publicKey); devices[i].keyHandle = NULL; devices[i].publicKey = NULL; } *n_devs = 0; out: if (buf) { free(buf); buf = NULL; } if (opwfile) fclose(opwfile); if (fd != -1) close(fd); return retval; } void free_devices(device_t *devices, const unsigned n_devs) { unsigned i; if (!devices) return; for (i = 0; i < n_devs; i++) { free(devices[i].keyHandle); devices[i].keyHandle = NULL; free(devices[i].publicKey); devices[i].publicKey = NULL; } free(devices); devices = NULL; } int do_authentication(const cfg_t *cfg, const device_t *devices, const unsigned n_devs, pam_handle_t *pamh) { u2fs_ctx_t *ctx; u2fs_auth_res_t *auth_result; u2fs_rc s_rc; u2fh_rc h_rc; u2fh_devs *devs = NULL; char *response = NULL; char *buf; int retval = -2; int cued = 0; unsigned i = 0; unsigned max_index = 0; unsigned max_index_prev = 0; h_rc = u2fh_global_init(cfg->debug ? U2FH_DEBUG : 0); if (h_rc != U2FH_OK) { D(cfg->debug_file, "Unable to initialize libu2f-host: %s", u2fh_strerror(h_rc)); return retval; } h_rc = u2fh_devs_init(&devs); if (h_rc != U2FH_OK) { D(cfg->debug_file, "Unable to initialize libu2f-host device handles: %s", u2fh_strerror(h_rc)); return retval; } if ((h_rc = u2fh_devs_discover(devs, &max_index)) != U2FH_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to discover device(s), %s", u2fh_strerror(h_rc)); return retval; } max_index_prev = max_index; if (cfg->debug) D(cfg->debug_file, "Device max index is %u", max_index); s_rc = u2fs_global_init(cfg->debug ? U2FS_DEBUG : 0); if (s_rc != U2FS_OK) { D(cfg->debug_file, "Unable to initialize libu2f-server: %s", u2fs_strerror(s_rc)); return retval; } s_rc = u2fs_init(&ctx); if (s_rc != U2FS_OK) { D(cfg->debug_file, "Unable to initialize libu2f-server context: %s", u2fs_strerror(s_rc)); return retval; } if ((s_rc = u2fs_set_origin(ctx, cfg->origin)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set origin: %s", u2fs_strerror(s_rc)); return retval; } if ((s_rc = u2fs_set_appid(ctx, cfg->appid)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set appid: %s", u2fs_strerror(s_rc)); return retval; } if (cfg->nodetect && cfg->debug) D(cfg->debug_file, "nodetect option specified, suitable key detection will be skipped"); i = 0; while (i < n_devs) { retval = -2; if (cfg->debug) D(cfg->debug_file, "Attempting authentication with device number %d", i + 1); if ((s_rc = u2fs_set_keyHandle(ctx, devices[i].keyHandle)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set keyHandle: %s", u2fs_strerror(s_rc)); return retval; } if ((s_rc = u2fs_set_publicKey(ctx, devices[i].publicKey)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set publicKey %s", u2fs_strerror(s_rc)); return retval; } if ((s_rc = u2fs_authentication_challenge(ctx, &buf)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to produce authentication challenge: %s", u2fs_strerror(s_rc)); free(buf); buf = NULL; return retval; } if (cfg->debug) D(cfg->debug_file, "Challenge: %s", buf); if (cfg->nodetect || (h_rc = u2fh_authenticate(devs, buf, cfg->origin, &response, 0)) == U2FH_OK ) { if (cfg->manual == 0 && cfg->cue && !cued) { cued = 1; converse(pamh, PAM_TEXT_INFO, DEFAULT_CUE); } retval = -1; if ((h_rc = u2fh_authenticate(devs, buf, cfg->origin, &response, U2FH_REQUEST_USER_PRESENCE)) == U2FH_OK) { if (cfg->debug) D(cfg->debug_file, "Response: %s", response); s_rc = u2fs_authentication_verify(ctx, response, &auth_result); u2fs_free_auth_res(auth_result); free(response); response = NULL; if (s_rc == U2FS_OK) { retval = 1; free(buf); buf = NULL; break; } } else { if (cfg->debug) D(cfg->debug_file, "Unable to communicate to the device, %s", u2fh_strerror(h_rc)); } } else { if (cfg->debug) D(cfg->debug_file, "Device for this keyhandle is not present."); } free(buf); buf = NULL; i++; if (u2fh_devs_discover(devs, &max_index) != U2FH_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to discover devices"); return retval; } if (max_index > max_index_prev) { if (cfg->debug) D(cfg->debug_file, "Devices max_index has changed: %u (was %u). Starting over", max_index, max_index_prev); max_index_prev = max_index; i = 0; } } u2fh_devs_done(devs); u2fh_global_done(); u2fs_done(ctx); u2fs_global_done(); return retval; } #define MAX_PROMPT_LEN (1024) int do_manual_authentication(const cfg_t *cfg, const device_t *devices, const unsigned n_devs, pam_handle_t *pamh) { u2fs_ctx_t *ctx_arr[n_devs]; u2fs_auth_res_t *auth_result; u2fs_rc s_rc; char *response = NULL; char prompt[MAX_PROMPT_LEN]; char *buf; int retval = -2; unsigned i = 0; if (u2fs_global_init(0) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to initialize libu2f-server"); return retval; } for (i = 0; i < n_devs; ++i) { if (u2fs_init(ctx_arr + i) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to initialize libu2f-server"); return retval; } if ((s_rc = u2fs_set_origin(ctx_arr[i], cfg->origin)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set origin: %s", u2fs_strerror(s_rc)); return retval; } if ((s_rc = u2fs_set_appid(ctx_arr[i], cfg->appid)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set appid: %s", u2fs_strerror(s_rc)); return retval; } if (cfg->debug) D(cfg->debug_file, "Attempting authentication with device number %d", i + 1); if ((s_rc = u2fs_set_keyHandle(ctx_arr[i], devices[i].keyHandle)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set keyHandle: %s", u2fs_strerror(s_rc)); return retval; } if ((s_rc = u2fs_set_publicKey(ctx_arr[i], devices[i].publicKey)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to set publicKey %s", u2fs_strerror(s_rc)); return retval; } if ((s_rc = u2fs_authentication_challenge(ctx_arr[i], &buf)) != U2FS_OK) { if (cfg->debug) D(cfg->debug_file, "Unable to produce authentication challenge: %s", u2fs_strerror(s_rc)); return retval; } if (cfg->debug) D(cfg->debug_file, "Challenge: %s", buf); if (i == 0) { snprintf(prompt, sizeof(prompt), "Now please copy-paste the below challenge(s) to " "'u2f-host -aauthenticate -o %s'", cfg->origin); converse(pamh, PAM_TEXT_INFO, prompt); } converse(pamh, PAM_TEXT_INFO, buf); free(buf); buf = NULL; } converse(pamh, PAM_TEXT_INFO, "Now, please enter the response(s) below, one per line."); retval = -1; for (i = 0; i < n_devs; ++i) { snprintf(prompt, sizeof(prompt), "[%d]: ", i); response = converse(pamh, PAM_PROMPT_ECHO_ON, prompt); converse(pamh, PAM_TEXT_INFO, response); s_rc = u2fs_authentication_verify(ctx_arr[i], response, &auth_result); u2fs_free_auth_res(auth_result); if (s_rc == U2FS_OK) { retval = 1; } free(response); if (retval == 1) { break; } } for (i = 0; i < n_devs; ++i) u2fs_done(ctx_arr[i]); u2fs_global_done(); return retval; } static int _converse(pam_handle_t *pamh, int nargs, const struct pam_message **message, struct pam_response **response) { struct pam_conv *conv; int retval; retval = pam_get_item(pamh, PAM_CONV, (void *)&conv); if (retval != PAM_SUCCESS) { return retval; } return conv->conv(nargs, message, response, conv->appdata_ptr); } char *converse(pam_handle_t *pamh, int echocode, const char *prompt) { const struct pam_message msg = {.msg_style = echocode, .msg = (char *)prompt}; const struct pam_message *msgs = &msg; struct pam_response *resp = NULL; int retval = _converse(pamh, 1, &msgs, &resp); char *ret = NULL; if (retval != PAM_SUCCESS || resp == NULL || resp->resp == NULL || *resp->resp == '\000') { if (retval == PAM_SUCCESS && resp && resp->resp) { ret = resp->resp; } } else { ret = resp->resp; } // Deallocate temporary storage. if (resp) { if (!ret) { free(resp->resp); } free(resp); } return ret; } #if defined(PAM_DEBUG) void _debug(FILE *debug_file, const char *file, int line, const char *func, const char *fmt, ...) { va_list ap; #ifdef __linux__ unsigned int size; char buffer[BUFSIZE]; char *out; size = (unsigned int)snprintf(NULL, 0, DEBUG_STR, file, line, func); va_start(ap, fmt); size += (unsigned int)vsnprintf(NULL, 0, fmt, ap); va_end(ap); va_start(ap, fmt); if (size < (BUFSIZE - 1)) { out = buffer; } else { out = malloc(size); } if (out) { size = (unsigned int)sprintf(out, DEBUG_STR, file, line, func); vsprintf(&out[size], fmt, ap); va_end(ap); } else { out = buffer; sprintf(out, "debug(pam_u2f): malloc failed when trying to log\n"); } if (debug_file == (FILE *)-1) { syslog(LOG_AUTHPRIV | LOG_DEBUG, "%s", out); } else { fprintf(debug_file, "%s\n", out); } if (out != buffer) { free(out); } #else /* Windows, MAC */ va_start(ap, fmt); fprintf(debug_file, DEBUG_STR, file, line, func ); vfprintf(debug_file, fmt, ap); fprintf(debug_file, "\n"); va_end(ap); #endif /* __linux__ */ } #endif /* PAM_DEBUG */
./CrossVul/dataset_final_sorted/CWE-200/c/good_867_1
crossvul-cpp_data_bad_2770_0
/* * Memory Migration functionality - linux/mm/migrate.c * * Copyright (C) 2006 Silicon Graphics, Inc., Christoph Lameter * * Page migration was first developed in the context of the memory hotplug * project. The main authors of the migration code are: * * IWAMOTO Toshihiro <iwamoto@valinux.co.jp> * Hirokazu Takahashi <taka@valinux.co.jp> * Dave Hansen <haveblue@us.ibm.com> * Christoph Lameter */ #include <linux/migrate.h> #include <linux/export.h> #include <linux/swap.h> #include <linux/swapops.h> #include <linux/pagemap.h> #include <linux/buffer_head.h> #include <linux/mm_inline.h> #include <linux/nsproxy.h> #include <linux/pagevec.h> #include <linux/ksm.h> #include <linux/rmap.h> #include <linux/topology.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/writeback.h> #include <linux/mempolicy.h> #include <linux/vmalloc.h> #include <linux/security.h> #include <linux/backing-dev.h> #include <linux/compaction.h> #include <linux/syscalls.h> #include <linux/hugetlb.h> #include <linux/hugetlb_cgroup.h> #include <linux/gfp.h> #include <linux/balloon_compaction.h> #include <linux/mmu_notifier.h> #include <linux/page_idle.h> #include <linux/page_owner.h> #include <linux/sched/mm.h> #include <asm/tlbflush.h> #define CREATE_TRACE_POINTS #include <trace/events/migrate.h> #include "internal.h" /* * migrate_prep() needs to be called before we start compiling a list of pages * to be migrated using isolate_lru_page(). If scheduling work on other CPUs is * undesirable, use migrate_prep_local() */ int migrate_prep(void) { /* * Clear the LRU lists so pages can be isolated. * Note that pages may be moved off the LRU after we have * drained them. Those pages will fail to migrate like other * pages that may be busy. */ lru_add_drain_all(); return 0; } /* Do the necessary work of migrate_prep but not if it involves other CPUs */ int migrate_prep_local(void) { lru_add_drain(); return 0; } int isolate_movable_page(struct page *page, isolate_mode_t mode) { struct address_space *mapping; /* * Avoid burning cycles with pages that are yet under __free_pages(), * or just got freed under us. * * In case we 'win' a race for a movable page being freed under us and * raise its refcount preventing __free_pages() from doing its job * the put_page() at the end of this block will take care of * release this page, thus avoiding a nasty leakage. */ if (unlikely(!get_page_unless_zero(page))) goto out; /* * Check PageMovable before holding a PG_lock because page's owner * assumes anybody doesn't touch PG_lock of newly allocated page * so unconditionally grapping the lock ruins page's owner side. */ if (unlikely(!__PageMovable(page))) goto out_putpage; /* * As movable pages are not isolated from LRU lists, concurrent * compaction threads can race against page migration functions * as well as race against the releasing a page. * * In order to avoid having an already isolated movable page * being (wrongly) re-isolated while it is under migration, * or to avoid attempting to isolate pages being released, * lets be sure we have the page lock * before proceeding with the movable page isolation steps. */ if (unlikely(!trylock_page(page))) goto out_putpage; if (!PageMovable(page) || PageIsolated(page)) goto out_no_isolated; mapping = page_mapping(page); VM_BUG_ON_PAGE(!mapping, page); if (!mapping->a_ops->isolate_page(page, mode)) goto out_no_isolated; /* Driver shouldn't use PG_isolated bit of page->flags */ WARN_ON_ONCE(PageIsolated(page)); __SetPageIsolated(page); unlock_page(page); return 0; out_no_isolated: unlock_page(page); out_putpage: put_page(page); out: return -EBUSY; } /* It should be called on page which is PG_movable */ void putback_movable_page(struct page *page) { struct address_space *mapping; VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageMovable(page), page); VM_BUG_ON_PAGE(!PageIsolated(page), page); mapping = page_mapping(page); mapping->a_ops->putback_page(page); __ClearPageIsolated(page); } /* * Put previously isolated pages back onto the appropriate lists * from where they were once taken off for compaction/migration. * * This function shall be used whenever the isolated pageset has been * built from lru, balloon, hugetlbfs page. See isolate_migratepages_range() * and isolate_huge_page(). */ void putback_movable_pages(struct list_head *l) { struct page *page; struct page *page2; list_for_each_entry_safe(page, page2, l, lru) { if (unlikely(PageHuge(page))) { putback_active_hugepage(page); continue; } list_del(&page->lru); /* * We isolated non-lru movable page so here we can use * __PageMovable because LRU page's mapping cannot have * PAGE_MAPPING_MOVABLE. */ if (unlikely(__PageMovable(page))) { VM_BUG_ON_PAGE(!PageIsolated(page), page); lock_page(page); if (PageMovable(page)) putback_movable_page(page); else __ClearPageIsolated(page); unlock_page(page); put_page(page); } else { dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } } } /* * Restore a potential migration pte to a working pte entry */ static bool remove_migration_pte(struct page *page, struct vm_area_struct *vma, unsigned long addr, void *old) { struct page_vma_mapped_walk pvmw = { .page = old, .vma = vma, .address = addr, .flags = PVMW_SYNC | PVMW_MIGRATION, }; struct page *new; pte_t pte; swp_entry_t entry; VM_BUG_ON_PAGE(PageTail(page), page); while (page_vma_mapped_walk(&pvmw)) { if (PageKsm(page)) new = page; else new = page - pvmw.page->index + linear_page_index(vma, pvmw.address); get_page(new); pte = pte_mkold(mk_pte(new, READ_ONCE(vma->vm_page_prot))); if (pte_swp_soft_dirty(*pvmw.pte)) pte = pte_mksoft_dirty(pte); /* * Recheck VMA as permissions can change since migration started */ entry = pte_to_swp_entry(*pvmw.pte); if (is_write_migration_entry(entry)) pte = maybe_mkwrite(pte, vma); flush_dcache_page(new); #ifdef CONFIG_HUGETLB_PAGE if (PageHuge(new)) { pte = pte_mkhuge(pte); pte = arch_make_huge_pte(pte, vma, new, 0); set_huge_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte); if (PageAnon(new)) hugepage_add_anon_rmap(new, vma, pvmw.address); else page_dup_rmap(new, true); } else #endif { set_pte_at(vma->vm_mm, pvmw.address, pvmw.pte, pte); if (PageAnon(new)) page_add_anon_rmap(new, vma, pvmw.address, false); else page_add_file_rmap(new, false); } if (vma->vm_flags & VM_LOCKED && !PageTransCompound(new)) mlock_vma_page(new); /* No need to invalidate - it was non-present before */ update_mmu_cache(vma, pvmw.address, pvmw.pte); } return true; } /* * Get rid of all migration entries and replace them by * references to the indicated page. */ void remove_migration_ptes(struct page *old, struct page *new, bool locked) { struct rmap_walk_control rwc = { .rmap_one = remove_migration_pte, .arg = old, }; if (locked) rmap_walk_locked(new, &rwc); else rmap_walk(new, &rwc); } /* * Something used the pte of a page under migration. We need to * get to the page and wait until migration is finished. * When we return from this function the fault will be retried. */ void __migration_entry_wait(struct mm_struct *mm, pte_t *ptep, spinlock_t *ptl) { pte_t pte; swp_entry_t entry; struct page *page; spin_lock(ptl); pte = *ptep; if (!is_swap_pte(pte)) goto out; entry = pte_to_swp_entry(pte); if (!is_migration_entry(entry)) goto out; page = migration_entry_to_page(entry); /* * Once radix-tree replacement of page migration started, page_count * *must* be zero. And, we don't want to call wait_on_page_locked() * against a page without get_page(). * So, we use get_page_unless_zero(), here. Even failed, page fault * will occur again. */ if (!get_page_unless_zero(page)) goto out; pte_unmap_unlock(ptep, ptl); wait_on_page_locked(page); put_page(page); return; out: pte_unmap_unlock(ptep, ptl); } void migration_entry_wait(struct mm_struct *mm, pmd_t *pmd, unsigned long address) { spinlock_t *ptl = pte_lockptr(mm, pmd); pte_t *ptep = pte_offset_map(pmd, address); __migration_entry_wait(mm, ptep, ptl); } void migration_entry_wait_huge(struct vm_area_struct *vma, struct mm_struct *mm, pte_t *pte) { spinlock_t *ptl = huge_pte_lockptr(hstate_vma(vma), mm, pte); __migration_entry_wait(mm, pte, ptl); } #ifdef CONFIG_BLOCK /* Returns true if all buffers are successfully locked */ static bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { struct buffer_head *bh = head; /* Simple case, sync compaction */ if (mode != MIGRATE_ASYNC) { do { get_bh(bh); lock_buffer(bh); bh = bh->b_this_page; } while (bh != head); return true; } /* async case, we cannot block on lock_buffer so use trylock_buffer */ do { get_bh(bh); if (!trylock_buffer(bh)) { /* * We failed to lock the buffer and cannot stall in * async migration. Release the taken locks */ struct buffer_head *failed_bh = bh; put_bh(failed_bh); bh = head; while (bh != failed_bh) { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } return false; } bh = bh->b_this_page; } while (bh != head); return true; } #else static inline bool buffer_migrate_lock_buffers(struct buffer_head *head, enum migrate_mode mode) { return true; } #endif /* CONFIG_BLOCK */ /* * Replace the page in the mapping. * * The number of remaining references must be: * 1 for anonymous pages without a mapping * 2 for pages with a mapping * 3 for pages with a mapping and PagePrivate/PagePrivate2 set. */ int migrate_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page, struct buffer_head *head, enum migrate_mode mode, int extra_count) { struct zone *oldzone, *newzone; int dirty; int expected_count = 1 + extra_count; void **pslot; if (!mapping) { /* Anonymous page without mapping */ if (page_count(page) != expected_count) return -EAGAIN; /* No turning back from here */ newpage->index = page->index; newpage->mapping = page->mapping; if (PageSwapBacked(page)) __SetPageSwapBacked(newpage); return MIGRATEPAGE_SUCCESS; } oldzone = page_zone(page); newzone = page_zone(newpage); spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count += 1 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_ref_freeze(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * In the async migration case of moving a page with buffers, lock the * buffers using trylock before the mapping is moved. If the mapping * was moved, we later failed to lock the buffers and could not move * the mapping back due to an elevated page count, we would have to * block waiting on other references to be dropped. */ if (mode == MIGRATE_ASYNC && head && !buffer_migrate_lock_buffers(head, mode)) { page_ref_unfreeze(page, expected_count); spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } /* * Now we know that no one else is looking at the page: * no turning back from here. */ newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); /* add cache reference */ if (PageSwapBacked(page)) { __SetPageSwapBacked(newpage); if (PageSwapCache(page)) { SetPageSwapCache(newpage); set_page_private(newpage, page_private(page)); } } else { VM_BUG_ON_PAGE(PageSwapCache(page), page); } /* Move dirty while page refs frozen and newpage not yet exposed */ dirty = PageDirty(page); if (dirty) { ClearPageDirty(page); SetPageDirty(newpage); } radix_tree_replace_slot(&mapping->page_tree, pslot, newpage); /* * Drop cache reference from old page by unfreezing * to one less reference. * We know this isn't the last reference. */ page_ref_unfreeze(page, expected_count - 1); spin_unlock(&mapping->tree_lock); /* Leave irq disabled to prevent preemption while updating stats */ /* * If moved to a different zone then also account * the page for that zone. Other VM counters will be * taken care of when we establish references to the * new page and drop references to the old page. * * Note that anonymous pages are accounted for * via NR_FILE_PAGES and NR_ANON_MAPPED if they * are mapped to swap space. */ if (newzone != oldzone) { __dec_node_state(oldzone->zone_pgdat, NR_FILE_PAGES); __inc_node_state(newzone->zone_pgdat, NR_FILE_PAGES); if (PageSwapBacked(page) && !PageSwapCache(page)) { __dec_node_state(oldzone->zone_pgdat, NR_SHMEM); __inc_node_state(newzone->zone_pgdat, NR_SHMEM); } if (dirty && mapping_cap_account_dirty(mapping)) { __dec_node_state(oldzone->zone_pgdat, NR_FILE_DIRTY); __dec_zone_state(oldzone, NR_ZONE_WRITE_PENDING); __inc_node_state(newzone->zone_pgdat, NR_FILE_DIRTY); __inc_zone_state(newzone, NR_ZONE_WRITE_PENDING); } } local_irq_enable(); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page_move_mapping); /* * The expected number of remaining references is the same as that * of migrate_page_move_mapping(). */ int migrate_huge_page_move_mapping(struct address_space *mapping, struct page *newpage, struct page *page) { int expected_count; void **pslot; spin_lock_irq(&mapping->tree_lock); pslot = radix_tree_lookup_slot(&mapping->page_tree, page_index(page)); expected_count = 2 + page_has_private(page); if (page_count(page) != expected_count || radix_tree_deref_slot_protected(pslot, &mapping->tree_lock) != page) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } if (!page_ref_freeze(page, expected_count)) { spin_unlock_irq(&mapping->tree_lock); return -EAGAIN; } newpage->index = page->index; newpage->mapping = page->mapping; get_page(newpage); radix_tree_replace_slot(&mapping->page_tree, pslot, newpage); page_ref_unfreeze(page, expected_count - 1); spin_unlock_irq(&mapping->tree_lock); return MIGRATEPAGE_SUCCESS; } /* * Gigantic pages are so large that we do not guarantee that page++ pointer * arithmetic will work across the entire page. We need something more * specialized. */ static void __copy_gigantic_page(struct page *dst, struct page *src, int nr_pages) { int i; struct page *dst_base = dst; struct page *src_base = src; for (i = 0; i < nr_pages; ) { cond_resched(); copy_highpage(dst, src); i++; dst = mem_map_next(dst, dst_base, i); src = mem_map_next(src, src_base, i); } } static void copy_huge_page(struct page *dst, struct page *src) { int i; int nr_pages; if (PageHuge(src)) { /* hugetlbfs page */ struct hstate *h = page_hstate(src); nr_pages = pages_per_huge_page(h); if (unlikely(nr_pages > MAX_ORDER_NR_PAGES)) { __copy_gigantic_page(dst, src, nr_pages); return; } } else { /* thp page */ BUG_ON(!PageTransHuge(src)); nr_pages = hpage_nr_pages(src); } for (i = 0; i < nr_pages; i++) { cond_resched(); copy_highpage(dst + i, src + i); } } /* * Copy the page to its new location */ void migrate_page_copy(struct page *newpage, struct page *page) { int cpupid; if (PageHuge(page) || PageTransHuge(page)) copy_huge_page(newpage, page); else copy_highpage(newpage, page); if (PageError(page)) SetPageError(newpage); if (PageReferenced(page)) SetPageReferenced(newpage); if (PageUptodate(page)) SetPageUptodate(newpage); if (TestClearPageActive(page)) { VM_BUG_ON_PAGE(PageUnevictable(page), page); SetPageActive(newpage); } else if (TestClearPageUnevictable(page)) SetPageUnevictable(newpage); if (PageChecked(page)) SetPageChecked(newpage); if (PageMappedToDisk(page)) SetPageMappedToDisk(newpage); /* Move dirty on pages not done by migrate_page_move_mapping() */ if (PageDirty(page)) SetPageDirty(newpage); if (page_is_young(page)) set_page_young(newpage); if (page_is_idle(page)) set_page_idle(newpage); /* * Copy NUMA information to the new page, to prevent over-eager * future migrations of this same page. */ cpupid = page_cpupid_xchg_last(page, -1); page_cpupid_xchg_last(newpage, cpupid); ksm_migrate_page(newpage, page); /* * Please do not reorder this without considering how mm/ksm.c's * get_ksm_page() depends upon ksm_migrate_page() and PageSwapCache(). */ if (PageSwapCache(page)) ClearPageSwapCache(page); ClearPagePrivate(page); set_page_private(page, 0); /* * If any waiters have accumulated on the new page then * wake them up. */ if (PageWriteback(newpage)) end_page_writeback(newpage); copy_page_owner(page, newpage); mem_cgroup_migrate(page, newpage); } EXPORT_SYMBOL(migrate_page_copy); /************************************************************ * Migration functions ***********************************************************/ /* * Common logic to directly migrate a single LRU page suitable for * pages that do not use PagePrivate/PagePrivate2. * * Pages are locked upon entry and exit. */ int migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { int rc; BUG_ON(PageWriteback(page)); /* Writeback must be complete */ rc = migrate_page_move_mapping(mapping, newpage, page, NULL, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; migrate_page_copy(newpage, page); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(migrate_page); #ifdef CONFIG_BLOCK /* * Migration function for pages with buffers. This function can only be used * if the underlying filesystem guarantees that no other references to "page" * exist. */ int buffer_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { struct buffer_head *bh, *head; int rc; if (!page_has_buffers(page)) return migrate_page(mapping, newpage, page, mode); head = page_buffers(page); rc = migrate_page_move_mapping(mapping, newpage, page, head, mode, 0); if (rc != MIGRATEPAGE_SUCCESS) return rc; /* * In the async case, migrate_page_move_mapping locked the buffers * with an IRQ-safe spinlock held. In the sync case, the buffers * need to be locked now */ if (mode != MIGRATE_ASYNC) BUG_ON(!buffer_migrate_lock_buffers(head, mode)); ClearPagePrivate(page); set_page_private(newpage, page_private(page)); set_page_private(page, 0); put_page(page); get_page(newpage); bh = head; do { set_bh_page(bh, newpage, bh_offset(bh)); bh = bh->b_this_page; } while (bh != head); SetPagePrivate(newpage); migrate_page_copy(newpage, page); bh = head; do { unlock_buffer(bh); put_bh(bh); bh = bh->b_this_page; } while (bh != head); return MIGRATEPAGE_SUCCESS; } EXPORT_SYMBOL(buffer_migrate_page); #endif /* * Writeback a page to clean the dirty state */ static int writeout(struct address_space *mapping, struct page *page) { struct writeback_control wbc = { .sync_mode = WB_SYNC_NONE, .nr_to_write = 1, .range_start = 0, .range_end = LLONG_MAX, .for_reclaim = 1 }; int rc; if (!mapping->a_ops->writepage) /* No write method for the address space */ return -EINVAL; if (!clear_page_dirty_for_io(page)) /* Someone else already triggered a write */ return -EAGAIN; /* * A dirty page may imply that the underlying filesystem has * the page on some queue. So the page must be clean for * migration. Writeout may mean we loose the lock and the * page state is no longer what we checked for earlier. * At this point we know that the migration attempt cannot * be successful. */ remove_migration_ptes(page, page, false); rc = mapping->a_ops->writepage(page, &wbc); if (rc != AOP_WRITEPAGE_ACTIVATE) /* unlocked. Relock */ lock_page(page); return (rc < 0) ? -EIO : -EAGAIN; } /* * Default handling if a filesystem does not provide a migration function. */ static int fallback_migrate_page(struct address_space *mapping, struct page *newpage, struct page *page, enum migrate_mode mode) { if (PageDirty(page)) { /* Only writeback pages in full synchronous migration */ if (mode != MIGRATE_SYNC) return -EBUSY; return writeout(mapping, page); } /* * Buffers may be managed in a filesystem specific way. * We must have no buffers or drop them. */ if (page_has_private(page) && !try_to_release_page(page, GFP_KERNEL)) return -EAGAIN; return migrate_page(mapping, newpage, page, mode); } /* * Move a page to a newly allocated page * The page is locked and all ptes have been successfully removed. * * The new page will have replaced the old page if this function * is successful. * * Return value: * < 0 - error code * MIGRATEPAGE_SUCCESS - success */ static int move_to_new_page(struct page *newpage, struct page *page, enum migrate_mode mode) { struct address_space *mapping; int rc = -EAGAIN; bool is_lru = !__PageMovable(page); VM_BUG_ON_PAGE(!PageLocked(page), page); VM_BUG_ON_PAGE(!PageLocked(newpage), newpage); mapping = page_mapping(page); if (likely(is_lru)) { if (!mapping) rc = migrate_page(mapping, newpage, page, mode); else if (mapping->a_ops->migratepage) /* * Most pages have a mapping and most filesystems * provide a migratepage callback. Anonymous pages * are part of swap space which also has its own * migratepage callback. This is the most common path * for page migration. */ rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); else rc = fallback_migrate_page(mapping, newpage, page, mode); } else { /* * In case of non-lru page, it could be released after * isolation step. In that case, we shouldn't try migration. */ VM_BUG_ON_PAGE(!PageIsolated(page), page); if (!PageMovable(page)) { rc = MIGRATEPAGE_SUCCESS; __ClearPageIsolated(page); goto out; } rc = mapping->a_ops->migratepage(mapping, newpage, page, mode); WARN_ON_ONCE(rc == MIGRATEPAGE_SUCCESS && !PageIsolated(page)); } /* * When successful, old pagecache page->mapping must be cleared before * page is freed; but stats require that PageAnon be left as PageAnon. */ if (rc == MIGRATEPAGE_SUCCESS) { if (__PageMovable(page)) { VM_BUG_ON_PAGE(!PageIsolated(page), page); /* * We clear PG_movable under page_lock so any compactor * cannot try to migrate this page. */ __ClearPageIsolated(page); } /* * Anonymous and movable page->mapping will be cleard by * free_pages_prepare so don't reset it here for keeping * the type to work PageAnon, for example. */ if (!PageMappingFlags(page)) page->mapping = NULL; } out: return rc; } static int __unmap_and_move(struct page *page, struct page *newpage, int force, enum migrate_mode mode) { int rc = -EAGAIN; int page_was_mapped = 0; struct anon_vma *anon_vma = NULL; bool is_lru = !__PageMovable(page); if (!trylock_page(page)) { if (!force || mode == MIGRATE_ASYNC) goto out; /* * It's not safe for direct compaction to call lock_page. * For example, during page readahead pages are added locked * to the LRU. Later, when the IO completes the pages are * marked uptodate and unlocked. However, the queueing * could be merging multiple pages for one bio (e.g. * mpage_readpages). If an allocation happens for the * second or third page, the process can end up locking * the same page twice and deadlocking. Rather than * trying to be clever about what pages can be locked, * avoid the use of lock_page for direct compaction * altogether. */ if (current->flags & PF_MEMALLOC) goto out; lock_page(page); } if (PageWriteback(page)) { /* * Only in the case of a full synchronous migration is it * necessary to wait for PageWriteback. In the async case, * the retry loop is too short and in the sync-light case, * the overhead of stalling is too much */ if (mode != MIGRATE_SYNC) { rc = -EBUSY; goto out_unlock; } if (!force) goto out_unlock; wait_on_page_writeback(page); } /* * By try_to_unmap(), page->mapcount goes down to 0 here. In this case, * we cannot notice that anon_vma is freed while we migrates a page. * This get_anon_vma() delays freeing anon_vma pointer until the end * of migration. File cache pages are no problem because of page_lock() * File Caches may use write_page() or lock_page() in migration, then, * just care Anon page here. * * Only page_get_anon_vma() understands the subtleties of * getting a hold on an anon_vma from outside one of its mms. * But if we cannot get anon_vma, then we won't need it anyway, * because that implies that the anon page is no longer mapped * (and cannot be remapped so long as we hold the page lock). */ if (PageAnon(page) && !PageKsm(page)) anon_vma = page_get_anon_vma(page); /* * Block others from accessing the new page when we get around to * establishing additional references. We are usually the only one * holding a reference to newpage at this point. We used to have a BUG * here if trylock_page(newpage) fails, but would like to allow for * cases where there might be a race with the previous use of newpage. * This is much like races on refcount of oldpage: just don't BUG(). */ if (unlikely(!trylock_page(newpage))) goto out_unlock; if (unlikely(!is_lru)) { rc = move_to_new_page(newpage, page, mode); goto out_unlock_both; } /* * Corner case handling: * 1. When a new swap-cache page is read into, it is added to the LRU * and treated as swapcache but it has no rmap yet. * Calling try_to_unmap() against a page->mapping==NULL page will * trigger a BUG. So handle it here. * 2. An orphaned page (see truncate_complete_page) might have * fs-private metadata. The page can be picked up due to memory * offlining. Everywhere else except page reclaim, the page is * invisible to the vm, so the page can not be migrated. So try to * free the metadata, so the page can be freed. */ if (!page->mapping) { VM_BUG_ON_PAGE(PageAnon(page), page); if (page_has_private(page)) { try_to_free_buffers(page); goto out_unlock_both; } } else if (page_mapped(page)) { /* Establish migration ptes */ VM_BUG_ON_PAGE(PageAnon(page) && !PageKsm(page) && !anon_vma, page); try_to_unmap(page, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(page)) rc = move_to_new_page(newpage, page, mode); if (page_was_mapped) remove_migration_ptes(page, rc == MIGRATEPAGE_SUCCESS ? newpage : page, false); out_unlock_both: unlock_page(newpage); out_unlock: /* Drop an anon_vma reference if we took one */ if (anon_vma) put_anon_vma(anon_vma); unlock_page(page); out: /* * If migration is successful, decrease refcount of the newpage * which will not free the page because new page owner increased * refcounter. As well, if it is LRU page, add the page to LRU * list in here. */ if (rc == MIGRATEPAGE_SUCCESS) { if (unlikely(__PageMovable(newpage))) put_page(newpage); else putback_lru_page(newpage); } return rc; } /* * gcc 4.7 and 4.8 on arm get an ICEs when inlining unmap_and_move(). Work * around it. */ #if (GCC_VERSION >= 40700 && GCC_VERSION < 40900) && defined(CONFIG_ARM) #define ICE_noinline noinline #else #define ICE_noinline #endif /* * Obtain the lock on page, remove all ptes and migrate the page * to the newly allocated page in newpage. */ static ICE_noinline int unmap_and_move(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *page, int force, enum migrate_mode mode, enum migrate_reason reason) { int rc = MIGRATEPAGE_SUCCESS; int *result = NULL; struct page *newpage; newpage = get_new_page(page, private, &result); if (!newpage) return -ENOMEM; if (page_count(page) == 1) { /* page was freed from under us. So we are done. */ ClearPageActive(page); ClearPageUnevictable(page); if (unlikely(__PageMovable(page))) { lock_page(page); if (!PageMovable(page)) __ClearPageIsolated(page); unlock_page(page); } if (put_new_page) put_new_page(newpage, private); else put_page(newpage); goto out; } if (unlikely(PageTransHuge(page))) { lock_page(page); rc = split_huge_page(page); unlock_page(page); if (rc) goto out; } rc = __unmap_and_move(page, newpage, force, mode); if (rc == MIGRATEPAGE_SUCCESS) set_page_owner_migrate_reason(newpage, reason); out: if (rc != -EAGAIN) { /* * A page that has been migrated has all references * removed and will be freed. A page that has not been * migrated will have kepts its references and be * restored. */ list_del(&page->lru); /* * Compaction can migrate also non-LRU pages which are * not accounted to NR_ISOLATED_*. They can be recognized * as __PageMovable */ if (likely(!__PageMovable(page))) dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } /* * If migration is successful, releases reference grabbed during * isolation. Otherwise, restore the page to right list unless * we want to retry. */ if (rc == MIGRATEPAGE_SUCCESS) { put_page(page); if (reason == MR_MEMORY_FAILURE) { /* * Set PG_HWPoison on just freed page * intentionally. Although it's rather weird, * it's how HWPoison flag works at the moment. */ if (!test_set_page_hwpoison(page)) num_poisoned_pages_inc(); } } else { if (rc != -EAGAIN) { if (likely(!__PageMovable(page))) { putback_lru_page(page); goto put_new; } lock_page(page); if (PageMovable(page)) putback_movable_page(page); else __ClearPageIsolated(page); unlock_page(page); put_page(page); } put_new: if (put_new_page) put_new_page(newpage, private); else put_page(newpage); } if (result) { if (rc) *result = rc; else *result = page_to_nid(newpage); } return rc; } /* * Counterpart of unmap_and_move_page() for hugepage migration. * * This function doesn't wait the completion of hugepage I/O * because there is no race between I/O and migration for hugepage. * Note that currently hugepage I/O occurs only in direct I/O * where no lock is held and PG_writeback is irrelevant, * and writeback status of all subpages are counted in the reference * count of the head page (i.e. if all subpages of a 2MB hugepage are * under direct I/O, the reference of the head page is 512 and a bit more.) * This means that when we try to migrate hugepage whose subpages are * doing direct I/O, some references remain after try_to_unmap() and * hugepage migration fails without data corruption. * * There is also no race when direct I/O is issued on the page under migration, * because then pte is replaced with migration swap entry and direct I/O code * will wait in the page fault for migration to complete. */ static int unmap_and_move_huge_page(new_page_t get_new_page, free_page_t put_new_page, unsigned long private, struct page *hpage, int force, enum migrate_mode mode, int reason) { int rc = -EAGAIN; int *result = NULL; int page_was_mapped = 0; struct page *new_hpage; struct anon_vma *anon_vma = NULL; /* * Movability of hugepages depends on architectures and hugepage size. * This check is necessary because some callers of hugepage migration * like soft offline and memory hotremove don't walk through page * tables or check whether the hugepage is pmd-based or not before * kicking migration. */ if (!hugepage_migration_supported(page_hstate(hpage))) { putback_active_hugepage(hpage); return -ENOSYS; } new_hpage = get_new_page(hpage, private, &result); if (!new_hpage) return -ENOMEM; if (!trylock_page(hpage)) { if (!force || mode != MIGRATE_SYNC) goto out; lock_page(hpage); } if (PageAnon(hpage)) anon_vma = page_get_anon_vma(hpage); if (unlikely(!trylock_page(new_hpage))) goto put_anon; if (page_mapped(hpage)) { try_to_unmap(hpage, TTU_MIGRATION|TTU_IGNORE_MLOCK|TTU_IGNORE_ACCESS); page_was_mapped = 1; } if (!page_mapped(hpage)) rc = move_to_new_page(new_hpage, hpage, mode); if (page_was_mapped) remove_migration_ptes(hpage, rc == MIGRATEPAGE_SUCCESS ? new_hpage : hpage, false); unlock_page(new_hpage); put_anon: if (anon_vma) put_anon_vma(anon_vma); if (rc == MIGRATEPAGE_SUCCESS) { hugetlb_cgroup_migrate(hpage, new_hpage); put_new_page = NULL; set_page_owner_migrate_reason(new_hpage, reason); } unlock_page(hpage); out: if (rc != -EAGAIN) putback_active_hugepage(hpage); if (reason == MR_MEMORY_FAILURE && !test_set_page_hwpoison(hpage)) num_poisoned_pages_inc(); /* * If migration was not successful and there's a freeing callback, use * it. Otherwise, put_page() will drop the reference grabbed during * isolation. */ if (put_new_page) put_new_page(new_hpage, private); else putback_active_hugepage(new_hpage); if (result) { if (rc) *result = rc; else *result = page_to_nid(new_hpage); } return rc; } /* * migrate_pages - migrate the pages specified in a list, to the free pages * supplied as the target for the page migration * * @from: The list of pages to be migrated. * @get_new_page: The function used to allocate free pages to be used * as the target of the page migration. * @put_new_page: The function used to free target pages if migration * fails, or NULL if no special handling is necessary. * @private: Private data to be passed on to get_new_page() * @mode: The migration mode that specifies the constraints for * page migration, if any. * @reason: The reason for page migration. * * The function returns after 10 attempts or if no pages are movable any more * because the list has become empty or no retryable pages exist any more. * The caller should call putback_movable_pages() to return pages to the LRU * or free list only if ret != 0. * * Returns the number of pages that were not migrated, or an error code. */ int migrate_pages(struct list_head *from, new_page_t get_new_page, free_page_t put_new_page, unsigned long private, enum migrate_mode mode, int reason) { int retry = 1; int nr_failed = 0; int nr_succeeded = 0; int pass = 0; struct page *page; struct page *page2; int swapwrite = current->flags & PF_SWAPWRITE; int rc; if (!swapwrite) current->flags |= PF_SWAPWRITE; for(pass = 0; pass < 10 && retry; pass++) { retry = 0; list_for_each_entry_safe(page, page2, from, lru) { cond_resched(); if (PageHuge(page)) rc = unmap_and_move_huge_page(get_new_page, put_new_page, private, page, pass > 2, mode, reason); else rc = unmap_and_move(get_new_page, put_new_page, private, page, pass > 2, mode, reason); switch(rc) { case -ENOMEM: nr_failed++; goto out; case -EAGAIN: retry++; break; case MIGRATEPAGE_SUCCESS: nr_succeeded++; break; default: /* * Permanent failure (-EBUSY, -ENOSYS, etc.): * unlike -EAGAIN case, the failed page is * removed from migration page list and not * retried in the next outer loop. */ nr_failed++; break; } } } nr_failed += retry; rc = nr_failed; out: if (nr_succeeded) count_vm_events(PGMIGRATE_SUCCESS, nr_succeeded); if (nr_failed) count_vm_events(PGMIGRATE_FAIL, nr_failed); trace_mm_migrate_pages(nr_succeeded, nr_failed, mode, reason); if (!swapwrite) current->flags &= ~PF_SWAPWRITE; return rc; } #ifdef CONFIG_NUMA /* * Move a list of individual pages */ struct page_to_node { unsigned long addr; struct page *page; int node; int status; }; static struct page *new_page_node(struct page *p, unsigned long private, int **result) { struct page_to_node *pm = (struct page_to_node *)private; while (pm->node != MAX_NUMNODES && pm->page != p) pm++; if (pm->node == MAX_NUMNODES) return NULL; *result = &pm->status; if (PageHuge(p)) return alloc_huge_page_node(page_hstate(compound_head(p)), pm->node); else return __alloc_pages_node(pm->node, GFP_HIGHUSER_MOVABLE | __GFP_THISNODE, 0); } /* * Move a set of pages as indicated in the pm array. The addr * field must be set to the virtual address of the page to be moved * and the node number must contain a valid target node. * The pm array ends with node = MAX_NUMNODES. */ static int do_move_page_to_node_array(struct mm_struct *mm, struct page_to_node *pm, int migrate_all) { int err; struct page_to_node *pp; LIST_HEAD(pagelist); down_read(&mm->mmap_sem); /* * Build a list of pages to migrate */ for (pp = pm; pp->node != MAX_NUMNODES; pp++) { struct vm_area_struct *vma; struct page *page; err = -EFAULT; vma = find_vma(mm, pp->addr); if (!vma || pp->addr < vma->vm_start || !vma_migratable(vma)) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, pp->addr, FOLL_GET | FOLL_SPLIT | FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = -ENOENT; if (!page) goto set_status; pp->page = page; err = page_to_nid(page); if (err == pp->node) /* * Node already in the right place */ goto put_and_set; err = -EACCES; if (page_mapcount(page) > 1 && !migrate_all) goto put_and_set; if (PageHuge(page)) { if (PageHead(page)) isolate_huge_page(page, &pagelist); goto put_and_set; } err = isolate_lru_page(page); if (!err) { list_add_tail(&page->lru, &pagelist); inc_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); } put_and_set: /* * Either remove the duplicate refcount from * isolate_lru_page() or drop the page ref if it was * not isolated. */ put_page(page); set_status: pp->status = err; } err = 0; if (!list_empty(&pagelist)) { err = migrate_pages(&pagelist, new_page_node, NULL, (unsigned long)pm, MIGRATE_SYNC, MR_SYSCALL); if (err) putback_movable_pages(&pagelist); } up_read(&mm->mmap_sem); return err; } /* * Migrate an array of page address onto an array of nodes and fill * the corresponding array of status. */ static int do_pages_move(struct mm_struct *mm, nodemask_t task_nodes, unsigned long nr_pages, const void __user * __user *pages, const int __user *nodes, int __user *status, int flags) { struct page_to_node *pm; unsigned long chunk_nr_pages; unsigned long chunk_start; int err; err = -ENOMEM; pm = (struct page_to_node *)__get_free_page(GFP_KERNEL); if (!pm) goto out; migrate_prep(); /* * Store a chunk of page_to_node array in a page, * but keep the last one as a marker */ chunk_nr_pages = (PAGE_SIZE / sizeof(struct page_to_node)) - 1; for (chunk_start = 0; chunk_start < nr_pages; chunk_start += chunk_nr_pages) { int j; if (chunk_start + chunk_nr_pages > nr_pages) chunk_nr_pages = nr_pages - chunk_start; /* fill the chunk pm with addrs and nodes from user-space */ for (j = 0; j < chunk_nr_pages; j++) { const void __user *p; int node; err = -EFAULT; if (get_user(p, pages + j + chunk_start)) goto out_pm; pm[j].addr = (unsigned long) p; if (get_user(node, nodes + j + chunk_start)) goto out_pm; err = -ENODEV; if (node < 0 || node >= MAX_NUMNODES) goto out_pm; if (!node_state(node, N_MEMORY)) goto out_pm; err = -EACCES; if (!node_isset(node, task_nodes)) goto out_pm; pm[j].node = node; } /* End marker for this chunk */ pm[chunk_nr_pages].node = MAX_NUMNODES; /* Migrate this chunk */ err = do_move_page_to_node_array(mm, pm, flags & MPOL_MF_MOVE_ALL); if (err < 0) goto out_pm; /* Return status information */ for (j = 0; j < chunk_nr_pages; j++) if (put_user(pm[j].status, status + j + chunk_start)) { err = -EFAULT; goto out_pm; } } err = 0; out_pm: free_page((unsigned long)pm); out: return err; } /* * Determine the nodes of an array of pages and store it in an array of status. */ static void do_pages_stat_array(struct mm_struct *mm, unsigned long nr_pages, const void __user **pages, int *status) { unsigned long i; down_read(&mm->mmap_sem); for (i = 0; i < nr_pages; i++) { unsigned long addr = (unsigned long)(*pages); struct vm_area_struct *vma; struct page *page; int err = -EFAULT; vma = find_vma(mm, addr); if (!vma || addr < vma->vm_start) goto set_status; /* FOLL_DUMP to ignore special (like zero) pages */ page = follow_page(vma, addr, FOLL_DUMP); err = PTR_ERR(page); if (IS_ERR(page)) goto set_status; err = page ? page_to_nid(page) : -ENOENT; set_status: *status = err; pages++; status++; } up_read(&mm->mmap_sem); } /* * Determine the nodes of a user array of pages and store it in * a user array of status. */ static int do_pages_stat(struct mm_struct *mm, unsigned long nr_pages, const void __user * __user *pages, int __user *status) { #define DO_PAGES_STAT_CHUNK_NR 16 const void __user *chunk_pages[DO_PAGES_STAT_CHUNK_NR]; int chunk_status[DO_PAGES_STAT_CHUNK_NR]; while (nr_pages) { unsigned long chunk_nr; chunk_nr = nr_pages; if (chunk_nr > DO_PAGES_STAT_CHUNK_NR) chunk_nr = DO_PAGES_STAT_CHUNK_NR; if (copy_from_user(chunk_pages, pages, chunk_nr * sizeof(*chunk_pages))) break; do_pages_stat_array(mm, chunk_nr, chunk_pages, chunk_status); if (copy_to_user(status, chunk_status, chunk_nr * sizeof(*status))) break; pages += chunk_nr; status += chunk_nr; nr_pages -= chunk_nr; } return nr_pages ? -EFAULT : 0; } /* * Move a list of pages in the address space of the currently executing * process. */ SYSCALL_DEFINE6(move_pages, pid_t, pid, unsigned long, nr_pages, const void __user * __user *, pages, const int __user *, nodes, int __user *, status, int, flags) { const struct cred *cred = current_cred(), *tcred; struct task_struct *task; struct mm_struct *mm; int err; nodemask_t task_nodes; /* Check flags */ if (flags & ~(MPOL_MF_MOVE|MPOL_MF_MOVE_ALL)) return -EINVAL; if ((flags & MPOL_MF_MOVE_ALL) && !capable(CAP_SYS_NICE)) return -EPERM; /* Find the mm_struct */ rcu_read_lock(); task = pid ? find_task_by_vpid(pid) : current; if (!task) { rcu_read_unlock(); return -ESRCH; } get_task_struct(task); /* * Check if this process has the right to modify the specified * process. The right exists if the process has administrative * capabilities, superuser privileges or the same * userid as the target process. */ tcred = __task_cred(task); if (!uid_eq(cred->euid, tcred->suid) && !uid_eq(cred->euid, tcred->uid) && !uid_eq(cred->uid, tcred->suid) && !uid_eq(cred->uid, tcred->uid) && !capable(CAP_SYS_NICE)) { rcu_read_unlock(); err = -EPERM; goto out; } rcu_read_unlock(); err = security_task_movememory(task); if (err) goto out; task_nodes = cpuset_mems_allowed(task); mm = get_task_mm(task); put_task_struct(task); if (!mm) return -EINVAL; if (nodes) err = do_pages_move(mm, task_nodes, nr_pages, pages, nodes, status, flags); else err = do_pages_stat(mm, nr_pages, pages, status); mmput(mm); return err; out: put_task_struct(task); return err; } #ifdef CONFIG_NUMA_BALANCING /* * Returns true if this is a safe migration target node for misplaced NUMA * pages. Currently it only checks the watermarks which crude */ static bool migrate_balanced_pgdat(struct pglist_data *pgdat, unsigned long nr_migrate_pages) { int z; for (z = pgdat->nr_zones - 1; z >= 0; z--) { struct zone *zone = pgdat->node_zones + z; if (!populated_zone(zone)) continue; /* Avoid waking kswapd by allocating pages_to_migrate pages. */ if (!zone_watermark_ok(zone, 0, high_wmark_pages(zone) + nr_migrate_pages, 0, 0)) continue; return true; } return false; } static struct page *alloc_misplaced_dst_page(struct page *page, unsigned long data, int **result) { int nid = (int) data; struct page *newpage; newpage = __alloc_pages_node(nid, (GFP_HIGHUSER_MOVABLE | __GFP_THISNODE | __GFP_NOMEMALLOC | __GFP_NORETRY | __GFP_NOWARN) & ~__GFP_RECLAIM, 0); return newpage; } /* * page migration rate limiting control. * Do not migrate more than @pages_to_migrate in a @migrate_interval_millisecs * window of time. Default here says do not migrate more than 1280M per second. */ static unsigned int migrate_interval_millisecs __read_mostly = 100; static unsigned int ratelimit_pages __read_mostly = 128 << (20 - PAGE_SHIFT); /* Returns true if the node is migrate rate-limited after the update */ static bool numamigrate_update_ratelimit(pg_data_t *pgdat, unsigned long nr_pages) { /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (time_after(jiffies, pgdat->numabalancing_migrate_next_window)) { spin_lock(&pgdat->numabalancing_migrate_lock); pgdat->numabalancing_migrate_nr_pages = 0; pgdat->numabalancing_migrate_next_window = jiffies + msecs_to_jiffies(migrate_interval_millisecs); spin_unlock(&pgdat->numabalancing_migrate_lock); } if (pgdat->numabalancing_migrate_nr_pages > ratelimit_pages) { trace_mm_numa_migrate_ratelimit(current, pgdat->node_id, nr_pages); return true; } /* * This is an unlocked non-atomic update so errors are possible. * The consequences are failing to migrate when we potentiall should * have which is not severe enough to warrant locking. If it is ever * a problem, it can be converted to a per-cpu counter. */ pgdat->numabalancing_migrate_nr_pages += nr_pages; return false; } static int numamigrate_isolate_page(pg_data_t *pgdat, struct page *page) { int page_lru; VM_BUG_ON_PAGE(compound_order(page) && !PageTransHuge(page), page); /* Avoid migrating to a node that is nearly full */ if (!migrate_balanced_pgdat(pgdat, 1UL << compound_order(page))) return 0; if (isolate_lru_page(page)) return 0; /* * migrate_misplaced_transhuge_page() skips page migration's usual * check on page_count(), so we must do it here, now that the page * has been isolated: a GUP pin, or any other pin, prevents migration. * The expected page count is 3: 1 for page's mapcount and 1 for the * caller's pin and 1 for the reference taken by isolate_lru_page(). */ if (PageTransHuge(page) && page_count(page) != 3) { putback_lru_page(page); return 0; } page_lru = page_is_file_cache(page); mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru, hpage_nr_pages(page)); /* * Isolating the page has taken another reference, so the * caller's reference can be safely dropped without the page * disappearing underneath us during migration. */ put_page(page); return 1; } bool pmd_trans_migrating(pmd_t pmd) { struct page *page = pmd_page(pmd); return PageLocked(page); } /* * Attempt to migrate a misplaced page to the specified destination * node. Caller is expected to have an elevated reference count on * the page that will be dropped by this function before returning. */ int migrate_misplaced_page(struct page *page, struct vm_area_struct *vma, int node) { pg_data_t *pgdat = NODE_DATA(node); int isolated; int nr_remaining; LIST_HEAD(migratepages); /* * Don't migrate file pages that are mapped in multiple processes * with execute permissions as they are probably shared libraries. */ if (page_mapcount(page) != 1 && page_is_file_cache(page) && (vma->vm_flags & VM_EXEC)) goto out; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, 1)) goto out; isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) goto out; list_add(&page->lru, &migratepages); nr_remaining = migrate_pages(&migratepages, alloc_misplaced_dst_page, NULL, node, MIGRATE_ASYNC, MR_NUMA_MISPLACED); if (nr_remaining) { if (!list_empty(&migratepages)) { list_del(&page->lru); dec_node_page_state(page, NR_ISOLATED_ANON + page_is_file_cache(page)); putback_lru_page(page); } isolated = 0; } else count_vm_numa_event(NUMA_PAGE_MIGRATE); BUG_ON(!list_empty(&migratepages)); return isolated; out: put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #if defined(CONFIG_NUMA_BALANCING) && defined(CONFIG_TRANSPARENT_HUGEPAGE) /* * Migrates a THP to a given target node. page must be locked and is unlocked * before returning. */ int migrate_misplaced_transhuge_page(struct mm_struct *mm, struct vm_area_struct *vma, pmd_t *pmd, pmd_t entry, unsigned long address, struct page *page, int node) { spinlock_t *ptl; pg_data_t *pgdat = NODE_DATA(node); int isolated = 0; struct page *new_page = NULL; int page_lru = page_is_file_cache(page); unsigned long mmun_start = address & HPAGE_PMD_MASK; unsigned long mmun_end = mmun_start + HPAGE_PMD_SIZE; /* * Rate-limit the amount of data that is being migrated to a node. * Optimal placement is no good if the memory bus is saturated and * all the time is being spent migrating! */ if (numamigrate_update_ratelimit(pgdat, HPAGE_PMD_NR)) goto out_dropref; new_page = alloc_pages_node(node, (GFP_TRANSHUGE_LIGHT | __GFP_THISNODE), HPAGE_PMD_ORDER); if (!new_page) goto out_fail; prep_transhuge_page(new_page); isolated = numamigrate_isolate_page(pgdat, page); if (!isolated) { put_page(new_page); goto out_fail; } /* Prepare a page as a migration target */ __SetPageLocked(new_page); if (PageSwapBacked(page)) __SetPageSwapBacked(new_page); /* anon mapping, we can simply copy page->mapping to the new page: */ new_page->mapping = page->mapping; new_page->index = page->index; migrate_page_copy(new_page, page); WARN_ON(PageLRU(new_page)); /* Recheck the target PMD */ mmu_notifier_invalidate_range_start(mm, mmun_start, mmun_end); ptl = pmd_lock(mm, pmd); if (unlikely(!pmd_same(*pmd, entry) || !page_ref_freeze(page, 2))) { spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Reverse changes made by migrate_page_copy() */ if (TestClearPageActive(new_page)) SetPageActive(page); if (TestClearPageUnevictable(new_page)) SetPageUnevictable(page); unlock_page(new_page); put_page(new_page); /* Free it */ /* Retake the callers reference and putback on LRU */ get_page(page); putback_lru_page(page); mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); goto out_unlock; } entry = mk_huge_pmd(new_page, vma->vm_page_prot); entry = maybe_pmd_mkwrite(pmd_mkdirty(entry), vma); /* * Clear the old entry under pagetable lock and establish the new PTE. * Any parallel GUP will either observe the old page blocking on the * page lock, block on the page table lock or observe the new page. * The SetPageUptodate on the new page and page_add_new_anon_rmap * guarantee the copy is visible before the pagetable update. */ flush_cache_range(vma, mmun_start, mmun_end); page_add_anon_rmap(new_page, vma, mmun_start, true); pmdp_huge_clear_flush_notify(vma, mmun_start, pmd); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); page_ref_unfreeze(page, 2); mlock_migrate_page(new_page, page); page_remove_rmap(page, true); set_page_owner_migrate_reason(new_page, MR_NUMA_MISPLACED); spin_unlock(ptl); mmu_notifier_invalidate_range_end(mm, mmun_start, mmun_end); /* Take an "isolate" reference and put new page on the LRU. */ get_page(new_page); putback_lru_page(new_page); unlock_page(new_page); unlock_page(page); put_page(page); /* Drop the rmap reference */ put_page(page); /* Drop the LRU isolation reference */ count_vm_events(PGMIGRATE_SUCCESS, HPAGE_PMD_NR); count_vm_numa_events(NUMA_PAGE_MIGRATE, HPAGE_PMD_NR); mod_node_page_state(page_pgdat(page), NR_ISOLATED_ANON + page_lru, -HPAGE_PMD_NR); return isolated; out_fail: count_vm_events(PGMIGRATE_FAIL, HPAGE_PMD_NR); out_dropref: ptl = pmd_lock(mm, pmd); if (pmd_same(*pmd, entry)) { entry = pmd_modify(entry, vma->vm_page_prot); set_pmd_at(mm, mmun_start, pmd, entry); update_mmu_cache_pmd(vma, address, &entry); } spin_unlock(ptl); out_unlock: unlock_page(page); put_page(page); return 0; } #endif /* CONFIG_NUMA_BALANCING */ #endif /* CONFIG_NUMA */
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2770_0
crossvul-cpp_data_good_3828_0
/* * IPVS An implementation of the IP virtual server support for the * LINUX operating system. IPVS is now implemented as a module * over the NetFilter framework. IPVS can be used to build a * high-performance and highly available server based on a * cluster of servers. * * Authors: Wensong Zhang <wensong@linuxvirtualserver.org> * Peter Kese <peter.kese@ijs.si> * Julian Anastasov <ja@ssi.bg> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Changes: * */ #define KMSG_COMPONENT "IPVS" #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt #include <linux/module.h> #include <linux/init.h> #include <linux/types.h> #include <linux/capability.h> #include <linux/fs.h> #include <linux/sysctl.h> #include <linux/proc_fs.h> #include <linux/workqueue.h> #include <linux/swap.h> #include <linux/seq_file.h> #include <linux/slab.h> #include <linux/netfilter.h> #include <linux/netfilter_ipv4.h> #include <linux/mutex.h> #include <net/net_namespace.h> #include <linux/nsproxy.h> #include <net/ip.h> #ifdef CONFIG_IP_VS_IPV6 #include <net/ipv6.h> #include <net/ip6_route.h> #endif #include <net/route.h> #include <net/sock.h> #include <net/genetlink.h> #include <asm/uaccess.h> #include <net/ip_vs.h> /* semaphore for IPVS sockopts. And, [gs]etsockopt may sleep. */ static DEFINE_MUTEX(__ip_vs_mutex); /* lock for service table */ static DEFINE_RWLOCK(__ip_vs_svc_lock); /* sysctl variables */ #ifdef CONFIG_IP_VS_DEBUG static int sysctl_ip_vs_debug_level = 0; int ip_vs_get_debug_level(void) { return sysctl_ip_vs_debug_level; } #endif /* Protos */ static void __ip_vs_del_service(struct ip_vs_service *svc); #ifdef CONFIG_IP_VS_IPV6 /* Taken from rt6_fill_node() in net/ipv6/route.c, is there a better way? */ static bool __ip_vs_addr_is_local_v6(struct net *net, const struct in6_addr *addr) { struct flowi6 fl6 = { .daddr = *addr, }; struct dst_entry *dst = ip6_route_output(net, NULL, &fl6); bool is_local; is_local = !dst->error && dst->dev && (dst->dev->flags & IFF_LOOPBACK); dst_release(dst); return is_local; } #endif #ifdef CONFIG_SYSCTL /* * update_defense_level is called from keventd and from sysctl, * so it needs to protect itself from softirqs */ static void update_defense_level(struct netns_ipvs *ipvs) { struct sysinfo i; static int old_secure_tcp = 0; int availmem; int nomem; int to_change = -1; /* we only count free and buffered memory (in pages) */ si_meminfo(&i); availmem = i.freeram + i.bufferram; /* however in linux 2.5 the i.bufferram is total page cache size, we need adjust it */ /* si_swapinfo(&i); */ /* availmem = availmem - (i.totalswap - i.freeswap); */ nomem = (availmem < ipvs->sysctl_amemthresh); local_bh_disable(); /* drop_entry */ spin_lock(&ipvs->dropentry_lock); switch (ipvs->sysctl_drop_entry) { case 0: atomic_set(&ipvs->dropentry, 0); break; case 1: if (nomem) { atomic_set(&ipvs->dropentry, 1); ipvs->sysctl_drop_entry = 2; } else { atomic_set(&ipvs->dropentry, 0); } break; case 2: if (nomem) { atomic_set(&ipvs->dropentry, 1); } else { atomic_set(&ipvs->dropentry, 0); ipvs->sysctl_drop_entry = 1; }; break; case 3: atomic_set(&ipvs->dropentry, 1); break; } spin_unlock(&ipvs->dropentry_lock); /* drop_packet */ spin_lock(&ipvs->droppacket_lock); switch (ipvs->sysctl_drop_packet) { case 0: ipvs->drop_rate = 0; break; case 1: if (nomem) { ipvs->drop_rate = ipvs->drop_counter = ipvs->sysctl_amemthresh / (ipvs->sysctl_amemthresh-availmem); ipvs->sysctl_drop_packet = 2; } else { ipvs->drop_rate = 0; } break; case 2: if (nomem) { ipvs->drop_rate = ipvs->drop_counter = ipvs->sysctl_amemthresh / (ipvs->sysctl_amemthresh-availmem); } else { ipvs->drop_rate = 0; ipvs->sysctl_drop_packet = 1; } break; case 3: ipvs->drop_rate = ipvs->sysctl_am_droprate; break; } spin_unlock(&ipvs->droppacket_lock); /* secure_tcp */ spin_lock(&ipvs->securetcp_lock); switch (ipvs->sysctl_secure_tcp) { case 0: if (old_secure_tcp >= 2) to_change = 0; break; case 1: if (nomem) { if (old_secure_tcp < 2) to_change = 1; ipvs->sysctl_secure_tcp = 2; } else { if (old_secure_tcp >= 2) to_change = 0; } break; case 2: if (nomem) { if (old_secure_tcp < 2) to_change = 1; } else { if (old_secure_tcp >= 2) to_change = 0; ipvs->sysctl_secure_tcp = 1; } break; case 3: if (old_secure_tcp < 2) to_change = 1; break; } old_secure_tcp = ipvs->sysctl_secure_tcp; if (to_change >= 0) ip_vs_protocol_timeout_change(ipvs, ipvs->sysctl_secure_tcp > 1); spin_unlock(&ipvs->securetcp_lock); local_bh_enable(); } /* * Timer for checking the defense */ #define DEFENSE_TIMER_PERIOD 1*HZ static void defense_work_handler(struct work_struct *work) { struct netns_ipvs *ipvs = container_of(work, struct netns_ipvs, defense_work.work); update_defense_level(ipvs); if (atomic_read(&ipvs->dropentry)) ip_vs_random_dropentry(ipvs->net); schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD); } #endif int ip_vs_use_count_inc(void) { return try_module_get(THIS_MODULE); } void ip_vs_use_count_dec(void) { module_put(THIS_MODULE); } /* * Hash table: for virtual service lookups */ #define IP_VS_SVC_TAB_BITS 8 #define IP_VS_SVC_TAB_SIZE (1 << IP_VS_SVC_TAB_BITS) #define IP_VS_SVC_TAB_MASK (IP_VS_SVC_TAB_SIZE - 1) /* the service table hashed by <protocol, addr, port> */ static struct list_head ip_vs_svc_table[IP_VS_SVC_TAB_SIZE]; /* the service table hashed by fwmark */ static struct list_head ip_vs_svc_fwm_table[IP_VS_SVC_TAB_SIZE]; /* * Returns hash value for virtual service */ static inline unsigned int ip_vs_svc_hashkey(struct net *net, int af, unsigned int proto, const union nf_inet_addr *addr, __be16 port) { register unsigned int porth = ntohs(port); __be32 addr_fold = addr->ip; #ifdef CONFIG_IP_VS_IPV6 if (af == AF_INET6) addr_fold = addr->ip6[0]^addr->ip6[1]^ addr->ip6[2]^addr->ip6[3]; #endif addr_fold ^= ((size_t)net>>8); return (proto^ntohl(addr_fold)^(porth>>IP_VS_SVC_TAB_BITS)^porth) & IP_VS_SVC_TAB_MASK; } /* * Returns hash value of fwmark for virtual service lookup */ static inline unsigned int ip_vs_svc_fwm_hashkey(struct net *net, __u32 fwmark) { return (((size_t)net>>8) ^ fwmark) & IP_VS_SVC_TAB_MASK; } /* * Hashes a service in the ip_vs_svc_table by <netns,proto,addr,port> * or in the ip_vs_svc_fwm_table by fwmark. * Should be called with locked tables. */ static int ip_vs_svc_hash(struct ip_vs_service *svc) { unsigned int hash; if (svc->flags & IP_VS_SVC_F_HASHED) { pr_err("%s(): request for already hashed, called from %pF\n", __func__, __builtin_return_address(0)); return 0; } if (svc->fwmark == 0) { /* * Hash it by <netns,protocol,addr,port> in ip_vs_svc_table */ hash = ip_vs_svc_hashkey(svc->net, svc->af, svc->protocol, &svc->addr, svc->port); list_add(&svc->s_list, &ip_vs_svc_table[hash]); } else { /* * Hash it by fwmark in svc_fwm_table */ hash = ip_vs_svc_fwm_hashkey(svc->net, svc->fwmark); list_add(&svc->f_list, &ip_vs_svc_fwm_table[hash]); } svc->flags |= IP_VS_SVC_F_HASHED; /* increase its refcnt because it is referenced by the svc table */ atomic_inc(&svc->refcnt); return 1; } /* * Unhashes a service from svc_table / svc_fwm_table. * Should be called with locked tables. */ static int ip_vs_svc_unhash(struct ip_vs_service *svc) { if (!(svc->flags & IP_VS_SVC_F_HASHED)) { pr_err("%s(): request for unhash flagged, called from %pF\n", __func__, __builtin_return_address(0)); return 0; } if (svc->fwmark == 0) { /* Remove it from the svc_table table */ list_del(&svc->s_list); } else { /* Remove it from the svc_fwm_table table */ list_del(&svc->f_list); } svc->flags &= ~IP_VS_SVC_F_HASHED; atomic_dec(&svc->refcnt); return 1; } /* * Get service by {netns, proto,addr,port} in the service table. */ static inline struct ip_vs_service * __ip_vs_service_find(struct net *net, int af, __u16 protocol, const union nf_inet_addr *vaddr, __be16 vport) { unsigned int hash; struct ip_vs_service *svc; /* Check for "full" addressed entries */ hash = ip_vs_svc_hashkey(net, af, protocol, vaddr, vport); list_for_each_entry(svc, &ip_vs_svc_table[hash], s_list){ if ((svc->af == af) && ip_vs_addr_equal(af, &svc->addr, vaddr) && (svc->port == vport) && (svc->protocol == protocol) && net_eq(svc->net, net)) { /* HIT */ return svc; } } return NULL; } /* * Get service by {fwmark} in the service table. */ static inline struct ip_vs_service * __ip_vs_svc_fwm_find(struct net *net, int af, __u32 fwmark) { unsigned int hash; struct ip_vs_service *svc; /* Check for fwmark addressed entries */ hash = ip_vs_svc_fwm_hashkey(net, fwmark); list_for_each_entry(svc, &ip_vs_svc_fwm_table[hash], f_list) { if (svc->fwmark == fwmark && svc->af == af && net_eq(svc->net, net)) { /* HIT */ return svc; } } return NULL; } struct ip_vs_service * ip_vs_service_get(struct net *net, int af, __u32 fwmark, __u16 protocol, const union nf_inet_addr *vaddr, __be16 vport) { struct ip_vs_service *svc; struct netns_ipvs *ipvs = net_ipvs(net); read_lock(&__ip_vs_svc_lock); /* * Check the table hashed by fwmark first */ if (fwmark) { svc = __ip_vs_svc_fwm_find(net, af, fwmark); if (svc) goto out; } /* * Check the table hashed by <protocol,addr,port> * for "full" addressed entries */ svc = __ip_vs_service_find(net, af, protocol, vaddr, vport); if (svc == NULL && protocol == IPPROTO_TCP && atomic_read(&ipvs->ftpsvc_counter) && (vport == FTPDATA || ntohs(vport) >= PROT_SOCK)) { /* * Check if ftp service entry exists, the packet * might belong to FTP data connections. */ svc = __ip_vs_service_find(net, af, protocol, vaddr, FTPPORT); } if (svc == NULL && atomic_read(&ipvs->nullsvc_counter)) { /* * Check if the catch-all port (port zero) exists */ svc = __ip_vs_service_find(net, af, protocol, vaddr, 0); } out: if (svc) atomic_inc(&svc->usecnt); read_unlock(&__ip_vs_svc_lock); IP_VS_DBG_BUF(9, "lookup service: fwm %u %s %s:%u %s\n", fwmark, ip_vs_proto_name(protocol), IP_VS_DBG_ADDR(af, vaddr), ntohs(vport), svc ? "hit" : "not hit"); return svc; } static inline void __ip_vs_bind_svc(struct ip_vs_dest *dest, struct ip_vs_service *svc) { atomic_inc(&svc->refcnt); dest->svc = svc; } static void __ip_vs_unbind_svc(struct ip_vs_dest *dest) { struct ip_vs_service *svc = dest->svc; dest->svc = NULL; if (atomic_dec_and_test(&svc->refcnt)) { IP_VS_DBG_BUF(3, "Removing service %u/%s:%u usecnt=%d\n", svc->fwmark, IP_VS_DBG_ADDR(svc->af, &svc->addr), ntohs(svc->port), atomic_read(&svc->usecnt)); free_percpu(svc->stats.cpustats); kfree(svc); } } /* * Returns hash value for real service */ static inline unsigned int ip_vs_rs_hashkey(int af, const union nf_inet_addr *addr, __be16 port) { register unsigned int porth = ntohs(port); __be32 addr_fold = addr->ip; #ifdef CONFIG_IP_VS_IPV6 if (af == AF_INET6) addr_fold = addr->ip6[0]^addr->ip6[1]^ addr->ip6[2]^addr->ip6[3]; #endif return (ntohl(addr_fold)^(porth>>IP_VS_RTAB_BITS)^porth) & IP_VS_RTAB_MASK; } /* * Hashes ip_vs_dest in rs_table by <proto,addr,port>. * should be called with locked tables. */ static int ip_vs_rs_hash(struct netns_ipvs *ipvs, struct ip_vs_dest *dest) { unsigned int hash; if (!list_empty(&dest->d_list)) { return 0; } /* * Hash by proto,addr,port, * which are the parameters of the real service. */ hash = ip_vs_rs_hashkey(dest->af, &dest->addr, dest->port); list_add(&dest->d_list, &ipvs->rs_table[hash]); return 1; } /* * UNhashes ip_vs_dest from rs_table. * should be called with locked tables. */ static int ip_vs_rs_unhash(struct ip_vs_dest *dest) { /* * Remove it from the rs_table table. */ if (!list_empty(&dest->d_list)) { list_del(&dest->d_list); INIT_LIST_HEAD(&dest->d_list); } return 1; } /* * Lookup real service by <proto,addr,port> in the real service table. */ struct ip_vs_dest * ip_vs_lookup_real_service(struct net *net, int af, __u16 protocol, const union nf_inet_addr *daddr, __be16 dport) { struct netns_ipvs *ipvs = net_ipvs(net); unsigned int hash; struct ip_vs_dest *dest; /* * Check for "full" addressed entries * Return the first found entry */ hash = ip_vs_rs_hashkey(af, daddr, dport); read_lock(&ipvs->rs_lock); list_for_each_entry(dest, &ipvs->rs_table[hash], d_list) { if ((dest->af == af) && ip_vs_addr_equal(af, &dest->addr, daddr) && (dest->port == dport) && ((dest->protocol == protocol) || dest->vfwmark)) { /* HIT */ read_unlock(&ipvs->rs_lock); return dest; } } read_unlock(&ipvs->rs_lock); return NULL; } /* * Lookup destination by {addr,port} in the given service */ static struct ip_vs_dest * ip_vs_lookup_dest(struct ip_vs_service *svc, const union nf_inet_addr *daddr, __be16 dport) { struct ip_vs_dest *dest; /* * Find the destination for the given service */ list_for_each_entry(dest, &svc->destinations, n_list) { if ((dest->af == svc->af) && ip_vs_addr_equal(svc->af, &dest->addr, daddr) && (dest->port == dport)) { /* HIT */ return dest; } } return NULL; } /* * Find destination by {daddr,dport,vaddr,protocol} * Cretaed to be used in ip_vs_process_message() in * the backup synchronization daemon. It finds the * destination to be bound to the received connection * on the backup. * * ip_vs_lookup_real_service() looked promissing, but * seems not working as expected. */ struct ip_vs_dest *ip_vs_find_dest(struct net *net, int af, const union nf_inet_addr *daddr, __be16 dport, const union nf_inet_addr *vaddr, __be16 vport, __u16 protocol, __u32 fwmark, __u32 flags) { struct ip_vs_dest *dest; struct ip_vs_service *svc; __be16 port = dport; svc = ip_vs_service_get(net, af, fwmark, protocol, vaddr, vport); if (!svc) return NULL; if (fwmark && (flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ) port = 0; dest = ip_vs_lookup_dest(svc, daddr, port); if (!dest) dest = ip_vs_lookup_dest(svc, daddr, port ^ dport); if (dest) atomic_inc(&dest->refcnt); ip_vs_service_put(svc); return dest; } /* * Lookup dest by {svc,addr,port} in the destination trash. * The destination trash is used to hold the destinations that are removed * from the service table but are still referenced by some conn entries. * The reason to add the destination trash is when the dest is temporary * down (either by administrator or by monitor program), the dest can be * picked back from the trash, the remaining connections to the dest can * continue, and the counting information of the dest is also useful for * scheduling. */ static struct ip_vs_dest * ip_vs_trash_get_dest(struct ip_vs_service *svc, const union nf_inet_addr *daddr, __be16 dport) { struct ip_vs_dest *dest, *nxt; struct netns_ipvs *ipvs = net_ipvs(svc->net); /* * Find the destination in trash */ list_for_each_entry_safe(dest, nxt, &ipvs->dest_trash, n_list) { IP_VS_DBG_BUF(3, "Destination %u/%s:%u still in trash, " "dest->refcnt=%d\n", dest->vfwmark, IP_VS_DBG_ADDR(svc->af, &dest->addr), ntohs(dest->port), atomic_read(&dest->refcnt)); if (dest->af == svc->af && ip_vs_addr_equal(svc->af, &dest->addr, daddr) && dest->port == dport && dest->vfwmark == svc->fwmark && dest->protocol == svc->protocol && (svc->fwmark || (ip_vs_addr_equal(svc->af, &dest->vaddr, &svc->addr) && dest->vport == svc->port))) { /* HIT */ return dest; } /* * Try to purge the destination from trash if not referenced */ if (atomic_read(&dest->refcnt) == 1) { IP_VS_DBG_BUF(3, "Removing destination %u/%s:%u " "from trash\n", dest->vfwmark, IP_VS_DBG_ADDR(svc->af, &dest->addr), ntohs(dest->port)); list_del(&dest->n_list); ip_vs_dst_reset(dest); __ip_vs_unbind_svc(dest); free_percpu(dest->stats.cpustats); kfree(dest); } } return NULL; } /* * Clean up all the destinations in the trash * Called by the ip_vs_control_cleanup() * * When the ip_vs_control_clearup is activated by ipvs module exit, * the service tables must have been flushed and all the connections * are expired, and the refcnt of each destination in the trash must * be 1, so we simply release them here. */ static void ip_vs_trash_cleanup(struct net *net) { struct ip_vs_dest *dest, *nxt; struct netns_ipvs *ipvs = net_ipvs(net); list_for_each_entry_safe(dest, nxt, &ipvs->dest_trash, n_list) { list_del(&dest->n_list); ip_vs_dst_reset(dest); __ip_vs_unbind_svc(dest); free_percpu(dest->stats.cpustats); kfree(dest); } } static void ip_vs_copy_stats(struct ip_vs_stats_user *dst, struct ip_vs_stats *src) { #define IP_VS_SHOW_STATS_COUNTER(c) dst->c = src->ustats.c - src->ustats0.c spin_lock_bh(&src->lock); IP_VS_SHOW_STATS_COUNTER(conns); IP_VS_SHOW_STATS_COUNTER(inpkts); IP_VS_SHOW_STATS_COUNTER(outpkts); IP_VS_SHOW_STATS_COUNTER(inbytes); IP_VS_SHOW_STATS_COUNTER(outbytes); ip_vs_read_estimator(dst, src); spin_unlock_bh(&src->lock); } static void ip_vs_zero_stats(struct ip_vs_stats *stats) { spin_lock_bh(&stats->lock); /* get current counters as zero point, rates are zeroed */ #define IP_VS_ZERO_STATS_COUNTER(c) stats->ustats0.c = stats->ustats.c IP_VS_ZERO_STATS_COUNTER(conns); IP_VS_ZERO_STATS_COUNTER(inpkts); IP_VS_ZERO_STATS_COUNTER(outpkts); IP_VS_ZERO_STATS_COUNTER(inbytes); IP_VS_ZERO_STATS_COUNTER(outbytes); ip_vs_zero_estimator(stats); spin_unlock_bh(&stats->lock); } /* * Update a destination in the given service */ static void __ip_vs_update_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, struct ip_vs_dest_user_kern *udest, int add) { struct netns_ipvs *ipvs = net_ipvs(svc->net); int conn_flags; /* set the weight and the flags */ atomic_set(&dest->weight, udest->weight); conn_flags = udest->conn_flags & IP_VS_CONN_F_DEST_MASK; conn_flags |= IP_VS_CONN_F_INACTIVE; /* set the IP_VS_CONN_F_NOOUTPUT flag if not masquerading/NAT */ if ((conn_flags & IP_VS_CONN_F_FWD_MASK) != IP_VS_CONN_F_MASQ) { conn_flags |= IP_VS_CONN_F_NOOUTPUT; } else { /* * Put the real service in rs_table if not present. * For now only for NAT! */ write_lock_bh(&ipvs->rs_lock); ip_vs_rs_hash(ipvs, dest); write_unlock_bh(&ipvs->rs_lock); } atomic_set(&dest->conn_flags, conn_flags); /* bind the service */ if (!dest->svc) { __ip_vs_bind_svc(dest, svc); } else { if (dest->svc != svc) { __ip_vs_unbind_svc(dest); ip_vs_zero_stats(&dest->stats); __ip_vs_bind_svc(dest, svc); } } /* set the dest status flags */ dest->flags |= IP_VS_DEST_F_AVAILABLE; if (udest->u_threshold == 0 || udest->u_threshold > dest->u_threshold) dest->flags &= ~IP_VS_DEST_F_OVERLOAD; dest->u_threshold = udest->u_threshold; dest->l_threshold = udest->l_threshold; spin_lock_bh(&dest->dst_lock); ip_vs_dst_reset(dest); spin_unlock_bh(&dest->dst_lock); if (add) ip_vs_start_estimator(svc->net, &dest->stats); write_lock_bh(&__ip_vs_svc_lock); /* Wait until all other svc users go away */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 0); if (add) { list_add(&dest->n_list, &svc->destinations); svc->num_dests++; } /* call the update_service, because server weight may be changed */ if (svc->scheduler->update_service) svc->scheduler->update_service(svc); write_unlock_bh(&__ip_vs_svc_lock); } /* * Create a destination for the given service */ static int ip_vs_new_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest, struct ip_vs_dest **dest_p) { struct ip_vs_dest *dest; unsigned int atype; EnterFunction(2); #ifdef CONFIG_IP_VS_IPV6 if (svc->af == AF_INET6) { atype = ipv6_addr_type(&udest->addr.in6); if ((!(atype & IPV6_ADDR_UNICAST) || atype & IPV6_ADDR_LINKLOCAL) && !__ip_vs_addr_is_local_v6(svc->net, &udest->addr.in6)) return -EINVAL; } else #endif { atype = inet_addr_type(svc->net, udest->addr.ip); if (atype != RTN_LOCAL && atype != RTN_UNICAST) return -EINVAL; } dest = kzalloc(sizeof(struct ip_vs_dest), GFP_KERNEL); if (dest == NULL) return -ENOMEM; dest->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats); if (!dest->stats.cpustats) goto err_alloc; dest->af = svc->af; dest->protocol = svc->protocol; dest->vaddr = svc->addr; dest->vport = svc->port; dest->vfwmark = svc->fwmark; ip_vs_addr_copy(svc->af, &dest->addr, &udest->addr); dest->port = udest->port; atomic_set(&dest->activeconns, 0); atomic_set(&dest->inactconns, 0); atomic_set(&dest->persistconns, 0); atomic_set(&dest->refcnt, 1); INIT_LIST_HEAD(&dest->d_list); spin_lock_init(&dest->dst_lock); spin_lock_init(&dest->stats.lock); __ip_vs_update_dest(svc, dest, udest, 1); *dest_p = dest; LeaveFunction(2); return 0; err_alloc: kfree(dest); return -ENOMEM; } /* * Add a destination into an existing service */ static int ip_vs_add_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; union nf_inet_addr daddr; __be16 dport = udest->port; int ret; EnterFunction(2); if (udest->weight < 0) { pr_err("%s(): server weight less than zero\n", __func__); return -ERANGE; } if (udest->l_threshold > udest->u_threshold) { pr_err("%s(): lower threshold is higher than upper threshold\n", __func__); return -ERANGE; } ip_vs_addr_copy(svc->af, &daddr, &udest->addr); /* * Check if the dest already exists in the list */ dest = ip_vs_lookup_dest(svc, &daddr, dport); if (dest != NULL) { IP_VS_DBG(1, "%s(): dest already exists\n", __func__); return -EEXIST; } /* * Check if the dest already exists in the trash and * is from the same service */ dest = ip_vs_trash_get_dest(svc, &daddr, dport); if (dest != NULL) { IP_VS_DBG_BUF(3, "Get destination %s:%u from trash, " "dest->refcnt=%d, service %u/%s:%u\n", IP_VS_DBG_ADDR(svc->af, &daddr), ntohs(dport), atomic_read(&dest->refcnt), dest->vfwmark, IP_VS_DBG_ADDR(svc->af, &dest->vaddr), ntohs(dest->vport)); /* * Get the destination from the trash */ list_del(&dest->n_list); __ip_vs_update_dest(svc, dest, udest, 1); ret = 0; } else { /* * Allocate and initialize the dest structure */ ret = ip_vs_new_dest(svc, udest, &dest); } LeaveFunction(2); return ret; } /* * Edit a destination in the given service */ static int ip_vs_edit_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; union nf_inet_addr daddr; __be16 dport = udest->port; EnterFunction(2); if (udest->weight < 0) { pr_err("%s(): server weight less than zero\n", __func__); return -ERANGE; } if (udest->l_threshold > udest->u_threshold) { pr_err("%s(): lower threshold is higher than upper threshold\n", __func__); return -ERANGE; } ip_vs_addr_copy(svc->af, &daddr, &udest->addr); /* * Lookup the destination list */ dest = ip_vs_lookup_dest(svc, &daddr, dport); if (dest == NULL) { IP_VS_DBG(1, "%s(): dest doesn't exist\n", __func__); return -ENOENT; } __ip_vs_update_dest(svc, dest, udest, 0); LeaveFunction(2); return 0; } /* * Delete a destination (must be already unlinked from the service) */ static void __ip_vs_del_dest(struct net *net, struct ip_vs_dest *dest) { struct netns_ipvs *ipvs = net_ipvs(net); ip_vs_stop_estimator(net, &dest->stats); /* * Remove it from the d-linked list with the real services. */ write_lock_bh(&ipvs->rs_lock); ip_vs_rs_unhash(dest); write_unlock_bh(&ipvs->rs_lock); /* * Decrease the refcnt of the dest, and free the dest * if nobody refers to it (refcnt=0). Otherwise, throw * the destination into the trash. */ if (atomic_dec_and_test(&dest->refcnt)) { IP_VS_DBG_BUF(3, "Removing destination %u/%s:%u\n", dest->vfwmark, IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port)); ip_vs_dst_reset(dest); /* simply decrease svc->refcnt here, let the caller check and release the service if nobody refers to it. Only user context can release destination and service, and only one user context can update virtual service at a time, so the operation here is OK */ atomic_dec(&dest->svc->refcnt); free_percpu(dest->stats.cpustats); kfree(dest); } else { IP_VS_DBG_BUF(3, "Moving dest %s:%u into trash, " "dest->refcnt=%d\n", IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port), atomic_read(&dest->refcnt)); list_add(&dest->n_list, &ipvs->dest_trash); atomic_inc(&dest->refcnt); } } /* * Unlink a destination from the given service */ static void __ip_vs_unlink_dest(struct ip_vs_service *svc, struct ip_vs_dest *dest, int svcupd) { dest->flags &= ~IP_VS_DEST_F_AVAILABLE; /* * Remove it from the d-linked destination list. */ list_del(&dest->n_list); svc->num_dests--; /* * Call the update_service function of its scheduler */ if (svcupd && svc->scheduler->update_service) svc->scheduler->update_service(svc); } /* * Delete a destination server in the given service */ static int ip_vs_del_dest(struct ip_vs_service *svc, struct ip_vs_dest_user_kern *udest) { struct ip_vs_dest *dest; __be16 dport = udest->port; EnterFunction(2); dest = ip_vs_lookup_dest(svc, &udest->addr, dport); if (dest == NULL) { IP_VS_DBG(1, "%s(): destination not found!\n", __func__); return -ENOENT; } write_lock_bh(&__ip_vs_svc_lock); /* * Wait until all other svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 0); /* * Unlink dest from the service */ __ip_vs_unlink_dest(svc, dest, 1); write_unlock_bh(&__ip_vs_svc_lock); /* * Delete the destination */ __ip_vs_del_dest(svc->net, dest); LeaveFunction(2); return 0; } /* * Add a service into the service hash table */ static int ip_vs_add_service(struct net *net, struct ip_vs_service_user_kern *u, struct ip_vs_service **svc_p) { int ret = 0; struct ip_vs_scheduler *sched = NULL; struct ip_vs_pe *pe = NULL; struct ip_vs_service *svc = NULL; struct netns_ipvs *ipvs = net_ipvs(net); /* increase the module use count */ ip_vs_use_count_inc(); /* Lookup the scheduler by 'u->sched_name' */ sched = ip_vs_scheduler_get(u->sched_name); if (sched == NULL) { pr_info("Scheduler module ip_vs_%s not found\n", u->sched_name); ret = -ENOENT; goto out_err; } if (u->pe_name && *u->pe_name) { pe = ip_vs_pe_getbyname(u->pe_name); if (pe == NULL) { pr_info("persistence engine module ip_vs_pe_%s " "not found\n", u->pe_name); ret = -ENOENT; goto out_err; } } #ifdef CONFIG_IP_VS_IPV6 if (u->af == AF_INET6 && (u->netmask < 1 || u->netmask > 128)) { ret = -EINVAL; goto out_err; } #endif svc = kzalloc(sizeof(struct ip_vs_service), GFP_KERNEL); if (svc == NULL) { IP_VS_DBG(1, "%s(): no memory\n", __func__); ret = -ENOMEM; goto out_err; } svc->stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats); if (!svc->stats.cpustats) goto out_err; /* I'm the first user of the service */ atomic_set(&svc->usecnt, 0); atomic_set(&svc->refcnt, 0); svc->af = u->af; svc->protocol = u->protocol; ip_vs_addr_copy(svc->af, &svc->addr, &u->addr); svc->port = u->port; svc->fwmark = u->fwmark; svc->flags = u->flags; svc->timeout = u->timeout * HZ; svc->netmask = u->netmask; svc->net = net; INIT_LIST_HEAD(&svc->destinations); rwlock_init(&svc->sched_lock); spin_lock_init(&svc->stats.lock); /* Bind the scheduler */ ret = ip_vs_bind_scheduler(svc, sched); if (ret) goto out_err; sched = NULL; /* Bind the ct retriever */ ip_vs_bind_pe(svc, pe); pe = NULL; /* Update the virtual service counters */ if (svc->port == FTPPORT) atomic_inc(&ipvs->ftpsvc_counter); else if (svc->port == 0) atomic_inc(&ipvs->nullsvc_counter); ip_vs_start_estimator(net, &svc->stats); /* Count only IPv4 services for old get/setsockopt interface */ if (svc->af == AF_INET) ipvs->num_services++; /* Hash the service into the service table */ write_lock_bh(&__ip_vs_svc_lock); ip_vs_svc_hash(svc); write_unlock_bh(&__ip_vs_svc_lock); *svc_p = svc; /* Now there is a service - full throttle */ ipvs->enable = 1; return 0; out_err: if (svc != NULL) { ip_vs_unbind_scheduler(svc); if (svc->inc) { local_bh_disable(); ip_vs_app_inc_put(svc->inc); local_bh_enable(); } if (svc->stats.cpustats) free_percpu(svc->stats.cpustats); kfree(svc); } ip_vs_scheduler_put(sched); ip_vs_pe_put(pe); /* decrease the module use count */ ip_vs_use_count_dec(); return ret; } /* * Edit a service and bind it with a new scheduler */ static int ip_vs_edit_service(struct ip_vs_service *svc, struct ip_vs_service_user_kern *u) { struct ip_vs_scheduler *sched, *old_sched; struct ip_vs_pe *pe = NULL, *old_pe = NULL; int ret = 0; /* * Lookup the scheduler, by 'u->sched_name' */ sched = ip_vs_scheduler_get(u->sched_name); if (sched == NULL) { pr_info("Scheduler module ip_vs_%s not found\n", u->sched_name); return -ENOENT; } old_sched = sched; if (u->pe_name && *u->pe_name) { pe = ip_vs_pe_getbyname(u->pe_name); if (pe == NULL) { pr_info("persistence engine module ip_vs_pe_%s " "not found\n", u->pe_name); ret = -ENOENT; goto out; } old_pe = pe; } #ifdef CONFIG_IP_VS_IPV6 if (u->af == AF_INET6 && (u->netmask < 1 || u->netmask > 128)) { ret = -EINVAL; goto out; } #endif write_lock_bh(&__ip_vs_svc_lock); /* * Wait until all other svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 0); /* * Set the flags and timeout value */ svc->flags = u->flags | IP_VS_SVC_F_HASHED; svc->timeout = u->timeout * HZ; svc->netmask = u->netmask; old_sched = svc->scheduler; if (sched != old_sched) { /* * Unbind the old scheduler */ if ((ret = ip_vs_unbind_scheduler(svc))) { old_sched = sched; goto out_unlock; } /* * Bind the new scheduler */ if ((ret = ip_vs_bind_scheduler(svc, sched))) { /* * If ip_vs_bind_scheduler fails, restore the old * scheduler. * The main reason of failure is out of memory. * * The question is if the old scheduler can be * restored all the time. TODO: if it cannot be * restored some time, we must delete the service, * otherwise the system may crash. */ ip_vs_bind_scheduler(svc, old_sched); old_sched = sched; goto out_unlock; } } old_pe = svc->pe; if (pe != old_pe) { ip_vs_unbind_pe(svc); ip_vs_bind_pe(svc, pe); } out_unlock: write_unlock_bh(&__ip_vs_svc_lock); out: ip_vs_scheduler_put(old_sched); ip_vs_pe_put(old_pe); return ret; } /* * Delete a service from the service list * - The service must be unlinked, unlocked and not referenced! * - We are called under _bh lock */ static void __ip_vs_del_service(struct ip_vs_service *svc) { struct ip_vs_dest *dest, *nxt; struct ip_vs_scheduler *old_sched; struct ip_vs_pe *old_pe; struct netns_ipvs *ipvs = net_ipvs(svc->net); pr_info("%s: enter\n", __func__); /* Count only IPv4 services for old get/setsockopt interface */ if (svc->af == AF_INET) ipvs->num_services--; ip_vs_stop_estimator(svc->net, &svc->stats); /* Unbind scheduler */ old_sched = svc->scheduler; ip_vs_unbind_scheduler(svc); ip_vs_scheduler_put(old_sched); /* Unbind persistence engine */ old_pe = svc->pe; ip_vs_unbind_pe(svc); ip_vs_pe_put(old_pe); /* Unbind app inc */ if (svc->inc) { ip_vs_app_inc_put(svc->inc); svc->inc = NULL; } /* * Unlink the whole destination list */ list_for_each_entry_safe(dest, nxt, &svc->destinations, n_list) { __ip_vs_unlink_dest(svc, dest, 0); __ip_vs_del_dest(svc->net, dest); } /* * Update the virtual service counters */ if (svc->port == FTPPORT) atomic_dec(&ipvs->ftpsvc_counter); else if (svc->port == 0) atomic_dec(&ipvs->nullsvc_counter); /* * Free the service if nobody refers to it */ if (atomic_read(&svc->refcnt) == 0) { IP_VS_DBG_BUF(3, "Removing service %u/%s:%u usecnt=%d\n", svc->fwmark, IP_VS_DBG_ADDR(svc->af, &svc->addr), ntohs(svc->port), atomic_read(&svc->usecnt)); free_percpu(svc->stats.cpustats); kfree(svc); } /* decrease the module use count */ ip_vs_use_count_dec(); } /* * Unlink a service from list and try to delete it if its refcnt reached 0 */ static void ip_vs_unlink_service(struct ip_vs_service *svc) { /* * Unhash it from the service table */ write_lock_bh(&__ip_vs_svc_lock); ip_vs_svc_unhash(svc); /* * Wait until all the svc users go away. */ IP_VS_WAIT_WHILE(atomic_read(&svc->usecnt) > 0); __ip_vs_del_service(svc); write_unlock_bh(&__ip_vs_svc_lock); } /* * Delete a service from the service list */ static int ip_vs_del_service(struct ip_vs_service *svc) { if (svc == NULL) return -EEXIST; ip_vs_unlink_service(svc); return 0; } /* * Flush all the virtual services */ static int ip_vs_flush(struct net *net) { int idx; struct ip_vs_service *svc, *nxt; /* * Flush the service table hashed by <netns,protocol,addr,port> */ for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry_safe(svc, nxt, &ip_vs_svc_table[idx], s_list) { if (net_eq(svc->net, net)) ip_vs_unlink_service(svc); } } /* * Flush the service table hashed by fwmark */ for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry_safe(svc, nxt, &ip_vs_svc_fwm_table[idx], f_list) { if (net_eq(svc->net, net)) ip_vs_unlink_service(svc); } } return 0; } /* * Delete service by {netns} in the service table. * Called by __ip_vs_cleanup() */ void ip_vs_service_net_cleanup(struct net *net) { EnterFunction(2); /* Check for "full" addressed entries */ mutex_lock(&__ip_vs_mutex); ip_vs_flush(net); mutex_unlock(&__ip_vs_mutex); LeaveFunction(2); } /* * Release dst hold by dst_cache */ static inline void __ip_vs_dev_reset(struct ip_vs_dest *dest, struct net_device *dev) { spin_lock_bh(&dest->dst_lock); if (dest->dst_cache && dest->dst_cache->dev == dev) { IP_VS_DBG_BUF(3, "Reset dev:%s dest %s:%u ,dest->refcnt=%d\n", dev->name, IP_VS_DBG_ADDR(dest->af, &dest->addr), ntohs(dest->port), atomic_read(&dest->refcnt)); ip_vs_dst_reset(dest); } spin_unlock_bh(&dest->dst_lock); } /* * Netdev event receiver * Currently only NETDEV_UNREGISTER is handled, i.e. if we hold a reference to * a device that is "unregister" it must be released. */ static int ip_vs_dst_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *dev = ptr; struct net *net = dev_net(dev); struct netns_ipvs *ipvs = net_ipvs(net); struct ip_vs_service *svc; struct ip_vs_dest *dest; unsigned int idx; if (event != NETDEV_UNREGISTER || !ipvs) return NOTIFY_DONE; IP_VS_DBG(3, "%s() dev=%s\n", __func__, dev->name); EnterFunction(2); mutex_lock(&__ip_vs_mutex); for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) { if (net_eq(svc->net, net)) { list_for_each_entry(dest, &svc->destinations, n_list) { __ip_vs_dev_reset(dest, dev); } } } list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) { if (net_eq(svc->net, net)) { list_for_each_entry(dest, &svc->destinations, n_list) { __ip_vs_dev_reset(dest, dev); } } } } list_for_each_entry(dest, &ipvs->dest_trash, n_list) { __ip_vs_dev_reset(dest, dev); } mutex_unlock(&__ip_vs_mutex); LeaveFunction(2); return NOTIFY_DONE; } /* * Zero counters in a service or all services */ static int ip_vs_zero_service(struct ip_vs_service *svc) { struct ip_vs_dest *dest; write_lock_bh(&__ip_vs_svc_lock); list_for_each_entry(dest, &svc->destinations, n_list) { ip_vs_zero_stats(&dest->stats); } ip_vs_zero_stats(&svc->stats); write_unlock_bh(&__ip_vs_svc_lock); return 0; } static int ip_vs_zero_all(struct net *net) { int idx; struct ip_vs_service *svc; for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) { if (net_eq(svc->net, net)) ip_vs_zero_service(svc); } } for(idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) { if (net_eq(svc->net, net)) ip_vs_zero_service(svc); } } ip_vs_zero_stats(&net_ipvs(net)->tot_stats); return 0; } #ifdef CONFIG_SYSCTL static int zero; static int three = 3; static int proc_do_defense_mode(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { struct net *net = current->nsproxy->net_ns; int *valp = table->data; int val = *valp; int rc; rc = proc_dointvec(table, write, buffer, lenp, ppos); if (write && (*valp != val)) { if ((*valp < 0) || (*valp > 3)) { /* Restore the correct value */ *valp = val; } else { update_defense_level(net_ipvs(net)); } } return rc; } static int proc_do_sync_threshold(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = table->data; int val[2]; int rc; /* backup the value first */ memcpy(val, valp, sizeof(val)); rc = proc_dointvec(table, write, buffer, lenp, ppos); if (write && (valp[0] < 0 || valp[1] < 0 || (valp[0] >= valp[1] && valp[1]))) { /* Restore the correct value */ memcpy(valp, val, sizeof(val)); } return rc; } static int proc_do_sync_mode(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = table->data; int val = *valp; int rc; rc = proc_dointvec(table, write, buffer, lenp, ppos); if (write && (*valp != val)) { if ((*valp < 0) || (*valp > 1)) { /* Restore the correct value */ *valp = val; } } return rc; } static int proc_do_sync_ports(ctl_table *table, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = table->data; int val = *valp; int rc; rc = proc_dointvec(table, write, buffer, lenp, ppos); if (write && (*valp != val)) { if (*valp < 1 || !is_power_of_2(*valp)) { /* Restore the correct value */ *valp = val; } } return rc; } /* * IPVS sysctl table (under the /proc/sys/net/ipv4/vs/) * Do not change order or insert new entries without * align with netns init in ip_vs_control_net_init() */ static struct ctl_table vs_vars[] = { { .procname = "amemthresh", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "am_droprate", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "drop_entry", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_do_defense_mode, }, { .procname = "drop_packet", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_do_defense_mode, }, #ifdef CONFIG_IP_VS_NFCT { .procname = "conntrack", .maxlen = sizeof(int), .mode = 0644, .proc_handler = &proc_dointvec, }, #endif { .procname = "secure_tcp", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_do_defense_mode, }, { .procname = "snat_reroute", .maxlen = sizeof(int), .mode = 0644, .proc_handler = &proc_dointvec, }, { .procname = "sync_version", .maxlen = sizeof(int), .mode = 0644, .proc_handler = &proc_do_sync_mode, }, { .procname = "sync_ports", .maxlen = sizeof(int), .mode = 0644, .proc_handler = &proc_do_sync_ports, }, { .procname = "sync_qlen_max", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "sync_sock_size", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "cache_bypass", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "expire_nodest_conn", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "expire_quiescent_template", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "sync_threshold", .maxlen = sizeof(((struct netns_ipvs *)0)->sysctl_sync_threshold), .mode = 0644, .proc_handler = proc_do_sync_threshold, }, { .procname = "sync_refresh_period", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "sync_retries", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_minmax, .extra1 = &zero, .extra2 = &three, }, { .procname = "nat_icmp_send", .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_IP_VS_DEBUG { .procname = "debug_level", .data = &sysctl_ip_vs_debug_level, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #endif #if 0 { .procname = "timeout_established", .data = &vs_timeout_table_dos.timeout[IP_VS_S_ESTABLISHED], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_synsent", .data = &vs_timeout_table_dos.timeout[IP_VS_S_SYN_SENT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_synrecv", .data = &vs_timeout_table_dos.timeout[IP_VS_S_SYN_RECV], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_finwait", .data = &vs_timeout_table_dos.timeout[IP_VS_S_FIN_WAIT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_timewait", .data = &vs_timeout_table_dos.timeout[IP_VS_S_TIME_WAIT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_close", .data = &vs_timeout_table_dos.timeout[IP_VS_S_CLOSE], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_closewait", .data = &vs_timeout_table_dos.timeout[IP_VS_S_CLOSE_WAIT], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_lastack", .data = &vs_timeout_table_dos.timeout[IP_VS_S_LAST_ACK], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_listen", .data = &vs_timeout_table_dos.timeout[IP_VS_S_LISTEN], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_synack", .data = &vs_timeout_table_dos.timeout[IP_VS_S_SYNACK], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_udp", .data = &vs_timeout_table_dos.timeout[IP_VS_S_UDP], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "timeout_icmp", .data = &vs_timeout_table_dos.timeout[IP_VS_S_ICMP], .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, #endif { } }; #endif #ifdef CONFIG_PROC_FS struct ip_vs_iter { struct seq_net_private p; /* Do not move this, netns depends upon it*/ struct list_head *table; int bucket; }; /* * Write the contents of the VS rule table to a PROCfs file. * (It is kept just for backward compatibility) */ static inline const char *ip_vs_fwd_name(unsigned int flags) { switch (flags & IP_VS_CONN_F_FWD_MASK) { case IP_VS_CONN_F_LOCALNODE: return "Local"; case IP_VS_CONN_F_TUNNEL: return "Tunnel"; case IP_VS_CONN_F_DROUTE: return "Route"; default: return "Masq"; } } /* Get the Nth entry in the two lists */ static struct ip_vs_service *ip_vs_info_array(struct seq_file *seq, loff_t pos) { struct net *net = seq_file_net(seq); struct ip_vs_iter *iter = seq->private; int idx; struct ip_vs_service *svc; /* look in hash by protocol */ for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) { if (net_eq(svc->net, net) && pos-- == 0) { iter->table = ip_vs_svc_table; iter->bucket = idx; return svc; } } } /* keep looking in fwmark */ for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) { if (net_eq(svc->net, net) && pos-- == 0) { iter->table = ip_vs_svc_fwm_table; iter->bucket = idx; return svc; } } } return NULL; } static void *ip_vs_info_seq_start(struct seq_file *seq, loff_t *pos) __acquires(__ip_vs_svc_lock) { read_lock_bh(&__ip_vs_svc_lock); return *pos ? ip_vs_info_array(seq, *pos - 1) : SEQ_START_TOKEN; } static void *ip_vs_info_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct list_head *e; struct ip_vs_iter *iter; struct ip_vs_service *svc; ++*pos; if (v == SEQ_START_TOKEN) return ip_vs_info_array(seq,0); svc = v; iter = seq->private; if (iter->table == ip_vs_svc_table) { /* next service in table hashed by protocol */ if ((e = svc->s_list.next) != &ip_vs_svc_table[iter->bucket]) return list_entry(e, struct ip_vs_service, s_list); while (++iter->bucket < IP_VS_SVC_TAB_SIZE) { list_for_each_entry(svc,&ip_vs_svc_table[iter->bucket], s_list) { return svc; } } iter->table = ip_vs_svc_fwm_table; iter->bucket = -1; goto scan_fwmark; } /* next service in hashed by fwmark */ if ((e = svc->f_list.next) != &ip_vs_svc_fwm_table[iter->bucket]) return list_entry(e, struct ip_vs_service, f_list); scan_fwmark: while (++iter->bucket < IP_VS_SVC_TAB_SIZE) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[iter->bucket], f_list) return svc; } return NULL; } static void ip_vs_info_seq_stop(struct seq_file *seq, void *v) __releases(__ip_vs_svc_lock) { read_unlock_bh(&__ip_vs_svc_lock); } static int ip_vs_info_seq_show(struct seq_file *seq, void *v) { if (v == SEQ_START_TOKEN) { seq_printf(seq, "IP Virtual Server version %d.%d.%d (size=%d)\n", NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size); seq_puts(seq, "Prot LocalAddress:Port Scheduler Flags\n"); seq_puts(seq, " -> RemoteAddress:Port Forward Weight ActiveConn InActConn\n"); } else { const struct ip_vs_service *svc = v; const struct ip_vs_iter *iter = seq->private; const struct ip_vs_dest *dest; if (iter->table == ip_vs_svc_table) { #ifdef CONFIG_IP_VS_IPV6 if (svc->af == AF_INET6) seq_printf(seq, "%s [%pI6]:%04X %s ", ip_vs_proto_name(svc->protocol), &svc->addr.in6, ntohs(svc->port), svc->scheduler->name); else #endif seq_printf(seq, "%s %08X:%04X %s %s ", ip_vs_proto_name(svc->protocol), ntohl(svc->addr.ip), ntohs(svc->port), svc->scheduler->name, (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":""); } else { seq_printf(seq, "FWM %08X %s %s", svc->fwmark, svc->scheduler->name, (svc->flags & IP_VS_SVC_F_ONEPACKET)?"ops ":""); } if (svc->flags & IP_VS_SVC_F_PERSISTENT) seq_printf(seq, "persistent %d %08X\n", svc->timeout, ntohl(svc->netmask)); else seq_putc(seq, '\n'); list_for_each_entry(dest, &svc->destinations, n_list) { #ifdef CONFIG_IP_VS_IPV6 if (dest->af == AF_INET6) seq_printf(seq, " -> [%pI6]:%04X" " %-7s %-6d %-10d %-10d\n", &dest->addr.in6, ntohs(dest->port), ip_vs_fwd_name(atomic_read(&dest->conn_flags)), atomic_read(&dest->weight), atomic_read(&dest->activeconns), atomic_read(&dest->inactconns)); else #endif seq_printf(seq, " -> %08X:%04X " "%-7s %-6d %-10d %-10d\n", ntohl(dest->addr.ip), ntohs(dest->port), ip_vs_fwd_name(atomic_read(&dest->conn_flags)), atomic_read(&dest->weight), atomic_read(&dest->activeconns), atomic_read(&dest->inactconns)); } } return 0; } static const struct seq_operations ip_vs_info_seq_ops = { .start = ip_vs_info_seq_start, .next = ip_vs_info_seq_next, .stop = ip_vs_info_seq_stop, .show = ip_vs_info_seq_show, }; static int ip_vs_info_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &ip_vs_info_seq_ops, sizeof(struct ip_vs_iter)); } static const struct file_operations ip_vs_info_fops = { .owner = THIS_MODULE, .open = ip_vs_info_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int ip_vs_stats_show(struct seq_file *seq, void *v) { struct net *net = seq_file_single_net(seq); struct ip_vs_stats_user show; /* 01234567 01234567 01234567 0123456701234567 0123456701234567 */ seq_puts(seq, " Total Incoming Outgoing Incoming Outgoing\n"); seq_printf(seq, " Conns Packets Packets Bytes Bytes\n"); ip_vs_copy_stats(&show, &net_ipvs(net)->tot_stats); seq_printf(seq, "%8X %8X %8X %16LX %16LX\n\n", show.conns, show.inpkts, show.outpkts, (unsigned long long) show.inbytes, (unsigned long long) show.outbytes); /* 01234567 01234567 01234567 0123456701234567 0123456701234567 */ seq_puts(seq, " Conns/s Pkts/s Pkts/s Bytes/s Bytes/s\n"); seq_printf(seq, "%8X %8X %8X %16X %16X\n", show.cps, show.inpps, show.outpps, show.inbps, show.outbps); return 0; } static int ip_vs_stats_seq_open(struct inode *inode, struct file *file) { return single_open_net(inode, file, ip_vs_stats_show); } static const struct file_operations ip_vs_stats_fops = { .owner = THIS_MODULE, .open = ip_vs_stats_seq_open, .read = seq_read, .llseek = seq_lseek, .release = single_release_net, }; static int ip_vs_stats_percpu_show(struct seq_file *seq, void *v) { struct net *net = seq_file_single_net(seq); struct ip_vs_stats *tot_stats = &net_ipvs(net)->tot_stats; struct ip_vs_cpu_stats *cpustats = tot_stats->cpustats; struct ip_vs_stats_user rates; int i; /* 01234567 01234567 01234567 0123456701234567 0123456701234567 */ seq_puts(seq, " Total Incoming Outgoing Incoming Outgoing\n"); seq_printf(seq, "CPU Conns Packets Packets Bytes Bytes\n"); for_each_possible_cpu(i) { struct ip_vs_cpu_stats *u = per_cpu_ptr(cpustats, i); unsigned int start; __u64 inbytes, outbytes; do { start = u64_stats_fetch_begin_bh(&u->syncp); inbytes = u->ustats.inbytes; outbytes = u->ustats.outbytes; } while (u64_stats_fetch_retry_bh(&u->syncp, start)); seq_printf(seq, "%3X %8X %8X %8X %16LX %16LX\n", i, u->ustats.conns, u->ustats.inpkts, u->ustats.outpkts, (__u64)inbytes, (__u64)outbytes); } spin_lock_bh(&tot_stats->lock); seq_printf(seq, " ~ %8X %8X %8X %16LX %16LX\n\n", tot_stats->ustats.conns, tot_stats->ustats.inpkts, tot_stats->ustats.outpkts, (unsigned long long) tot_stats->ustats.inbytes, (unsigned long long) tot_stats->ustats.outbytes); ip_vs_read_estimator(&rates, tot_stats); spin_unlock_bh(&tot_stats->lock); /* 01234567 01234567 01234567 0123456701234567 0123456701234567 */ seq_puts(seq, " Conns/s Pkts/s Pkts/s Bytes/s Bytes/s\n"); seq_printf(seq, " %8X %8X %8X %16X %16X\n", rates.cps, rates.inpps, rates.outpps, rates.inbps, rates.outbps); return 0; } static int ip_vs_stats_percpu_seq_open(struct inode *inode, struct file *file) { return single_open_net(inode, file, ip_vs_stats_percpu_show); } static const struct file_operations ip_vs_stats_percpu_fops = { .owner = THIS_MODULE, .open = ip_vs_stats_percpu_seq_open, .read = seq_read, .llseek = seq_lseek, .release = single_release_net, }; #endif /* * Set timeout values for tcp tcpfin udp in the timeout_table. */ static int ip_vs_set_timeout(struct net *net, struct ip_vs_timeout_user *u) { #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP) struct ip_vs_proto_data *pd; #endif IP_VS_DBG(2, "Setting timeout tcp:%d tcpfin:%d udp:%d\n", u->tcp_timeout, u->tcp_fin_timeout, u->udp_timeout); #ifdef CONFIG_IP_VS_PROTO_TCP if (u->tcp_timeout) { pd = ip_vs_proto_data_get(net, IPPROTO_TCP); pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] = u->tcp_timeout * HZ; } if (u->tcp_fin_timeout) { pd = ip_vs_proto_data_get(net, IPPROTO_TCP); pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] = u->tcp_fin_timeout * HZ; } #endif #ifdef CONFIG_IP_VS_PROTO_UDP if (u->udp_timeout) { pd = ip_vs_proto_data_get(net, IPPROTO_UDP); pd->timeout_table[IP_VS_UDP_S_NORMAL] = u->udp_timeout * HZ; } #endif return 0; } #define SET_CMDID(cmd) (cmd - IP_VS_BASE_CTL) #define SERVICE_ARG_LEN (sizeof(struct ip_vs_service_user)) #define SVCDEST_ARG_LEN (sizeof(struct ip_vs_service_user) + \ sizeof(struct ip_vs_dest_user)) #define TIMEOUT_ARG_LEN (sizeof(struct ip_vs_timeout_user)) #define DAEMON_ARG_LEN (sizeof(struct ip_vs_daemon_user)) #define MAX_ARG_LEN SVCDEST_ARG_LEN static const unsigned char set_arglen[SET_CMDID(IP_VS_SO_SET_MAX)+1] = { [SET_CMDID(IP_VS_SO_SET_ADD)] = SERVICE_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_EDIT)] = SERVICE_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_DEL)] = SERVICE_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_FLUSH)] = 0, [SET_CMDID(IP_VS_SO_SET_ADDDEST)] = SVCDEST_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_DELDEST)] = SVCDEST_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_EDITDEST)] = SVCDEST_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_TIMEOUT)] = TIMEOUT_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_STARTDAEMON)] = DAEMON_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_STOPDAEMON)] = DAEMON_ARG_LEN, [SET_CMDID(IP_VS_SO_SET_ZERO)] = SERVICE_ARG_LEN, }; static void ip_vs_copy_usvc_compat(struct ip_vs_service_user_kern *usvc, struct ip_vs_service_user *usvc_compat) { memset(usvc, 0, sizeof(*usvc)); usvc->af = AF_INET; usvc->protocol = usvc_compat->protocol; usvc->addr.ip = usvc_compat->addr; usvc->port = usvc_compat->port; usvc->fwmark = usvc_compat->fwmark; /* Deep copy of sched_name is not needed here */ usvc->sched_name = usvc_compat->sched_name; usvc->flags = usvc_compat->flags; usvc->timeout = usvc_compat->timeout; usvc->netmask = usvc_compat->netmask; } static void ip_vs_copy_udest_compat(struct ip_vs_dest_user_kern *udest, struct ip_vs_dest_user *udest_compat) { memset(udest, 0, sizeof(*udest)); udest->addr.ip = udest_compat->addr; udest->port = udest_compat->port; udest->conn_flags = udest_compat->conn_flags; udest->weight = udest_compat->weight; udest->u_threshold = udest_compat->u_threshold; udest->l_threshold = udest_compat->l_threshold; } static int do_ip_vs_set_ctl(struct sock *sk, int cmd, void __user *user, unsigned int len) { struct net *net = sock_net(sk); int ret; unsigned char arg[MAX_ARG_LEN]; struct ip_vs_service_user *usvc_compat; struct ip_vs_service_user_kern usvc; struct ip_vs_service *svc; struct ip_vs_dest_user *udest_compat; struct ip_vs_dest_user_kern udest; struct netns_ipvs *ipvs = net_ipvs(net); if (!capable(CAP_NET_ADMIN)) return -EPERM; if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_SET_MAX) return -EINVAL; if (len < 0 || len > MAX_ARG_LEN) return -EINVAL; if (len != set_arglen[SET_CMDID(cmd)]) { pr_err("set_ctl: len %u != %u\n", len, set_arglen[SET_CMDID(cmd)]); return -EINVAL; } if (copy_from_user(arg, user, len) != 0) return -EFAULT; /* increase the module use count */ ip_vs_use_count_inc(); /* Handle daemons since they have another lock */ if (cmd == IP_VS_SO_SET_STARTDAEMON || cmd == IP_VS_SO_SET_STOPDAEMON) { struct ip_vs_daemon_user *dm = (struct ip_vs_daemon_user *)arg; if (mutex_lock_interruptible(&ipvs->sync_mutex)) { ret = -ERESTARTSYS; goto out_dec; } if (cmd == IP_VS_SO_SET_STARTDAEMON) ret = start_sync_thread(net, dm->state, dm->mcast_ifn, dm->syncid); else ret = stop_sync_thread(net, dm->state); mutex_unlock(&ipvs->sync_mutex); goto out_dec; } if (mutex_lock_interruptible(&__ip_vs_mutex)) { ret = -ERESTARTSYS; goto out_dec; } if (cmd == IP_VS_SO_SET_FLUSH) { /* Flush the virtual service */ ret = ip_vs_flush(net); goto out_unlock; } else if (cmd == IP_VS_SO_SET_TIMEOUT) { /* Set timeout values for (tcp tcpfin udp) */ ret = ip_vs_set_timeout(net, (struct ip_vs_timeout_user *)arg); goto out_unlock; } usvc_compat = (struct ip_vs_service_user *)arg; udest_compat = (struct ip_vs_dest_user *)(usvc_compat + 1); /* We only use the new structs internally, so copy userspace compat * structs to extended internal versions */ ip_vs_copy_usvc_compat(&usvc, usvc_compat); ip_vs_copy_udest_compat(&udest, udest_compat); if (cmd == IP_VS_SO_SET_ZERO) { /* if no service address is set, zero counters in all */ if (!usvc.fwmark && !usvc.addr.ip && !usvc.port) { ret = ip_vs_zero_all(net); goto out_unlock; } } /* Check for valid protocol: TCP or UDP or SCTP, even for fwmark!=0 */ if (usvc.protocol != IPPROTO_TCP && usvc.protocol != IPPROTO_UDP && usvc.protocol != IPPROTO_SCTP) { pr_err("set_ctl: invalid protocol: %d %pI4:%d %s\n", usvc.protocol, &usvc.addr.ip, ntohs(usvc.port), usvc.sched_name); ret = -EFAULT; goto out_unlock; } /* Lookup the exact service by <protocol, addr, port> or fwmark */ if (usvc.fwmark == 0) svc = __ip_vs_service_find(net, usvc.af, usvc.protocol, &usvc.addr, usvc.port); else svc = __ip_vs_svc_fwm_find(net, usvc.af, usvc.fwmark); if (cmd != IP_VS_SO_SET_ADD && (svc == NULL || svc->protocol != usvc.protocol)) { ret = -ESRCH; goto out_unlock; } switch (cmd) { case IP_VS_SO_SET_ADD: if (svc != NULL) ret = -EEXIST; else ret = ip_vs_add_service(net, &usvc, &svc); break; case IP_VS_SO_SET_EDIT: ret = ip_vs_edit_service(svc, &usvc); break; case IP_VS_SO_SET_DEL: ret = ip_vs_del_service(svc); if (!ret) goto out_unlock; break; case IP_VS_SO_SET_ZERO: ret = ip_vs_zero_service(svc); break; case IP_VS_SO_SET_ADDDEST: ret = ip_vs_add_dest(svc, &udest); break; case IP_VS_SO_SET_EDITDEST: ret = ip_vs_edit_dest(svc, &udest); break; case IP_VS_SO_SET_DELDEST: ret = ip_vs_del_dest(svc, &udest); break; default: ret = -EINVAL; } out_unlock: mutex_unlock(&__ip_vs_mutex); out_dec: /* decrease the module use count */ ip_vs_use_count_dec(); return ret; } static void ip_vs_copy_service(struct ip_vs_service_entry *dst, struct ip_vs_service *src) { dst->protocol = src->protocol; dst->addr = src->addr.ip; dst->port = src->port; dst->fwmark = src->fwmark; strlcpy(dst->sched_name, src->scheduler->name, sizeof(dst->sched_name)); dst->flags = src->flags; dst->timeout = src->timeout / HZ; dst->netmask = src->netmask; dst->num_dests = src->num_dests; ip_vs_copy_stats(&dst->stats, &src->stats); } static inline int __ip_vs_get_service_entries(struct net *net, const struct ip_vs_get_services *get, struct ip_vs_get_services __user *uptr) { int idx, count=0; struct ip_vs_service *svc; struct ip_vs_service_entry entry; int ret = 0; for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_table[idx], s_list) { /* Only expose IPv4 entries to old interface */ if (svc->af != AF_INET || !net_eq(svc->net, net)) continue; if (count >= get->num_services) goto out; memset(&entry, 0, sizeof(entry)); ip_vs_copy_service(&entry, svc); if (copy_to_user(&uptr->entrytable[count], &entry, sizeof(entry))) { ret = -EFAULT; goto out; } count++; } } for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[idx], f_list) { /* Only expose IPv4 entries to old interface */ if (svc->af != AF_INET || !net_eq(svc->net, net)) continue; if (count >= get->num_services) goto out; memset(&entry, 0, sizeof(entry)); ip_vs_copy_service(&entry, svc); if (copy_to_user(&uptr->entrytable[count], &entry, sizeof(entry))) { ret = -EFAULT; goto out; } count++; } } out: return ret; } static inline int __ip_vs_get_dest_entries(struct net *net, const struct ip_vs_get_dests *get, struct ip_vs_get_dests __user *uptr) { struct ip_vs_service *svc; union nf_inet_addr addr = { .ip = get->addr }; int ret = 0; if (get->fwmark) svc = __ip_vs_svc_fwm_find(net, AF_INET, get->fwmark); else svc = __ip_vs_service_find(net, AF_INET, get->protocol, &addr, get->port); if (svc) { int count = 0; struct ip_vs_dest *dest; struct ip_vs_dest_entry entry; list_for_each_entry(dest, &svc->destinations, n_list) { if (count >= get->num_dests) break; entry.addr = dest->addr.ip; entry.port = dest->port; entry.conn_flags = atomic_read(&dest->conn_flags); entry.weight = atomic_read(&dest->weight); entry.u_threshold = dest->u_threshold; entry.l_threshold = dest->l_threshold; entry.activeconns = atomic_read(&dest->activeconns); entry.inactconns = atomic_read(&dest->inactconns); entry.persistconns = atomic_read(&dest->persistconns); ip_vs_copy_stats(&entry.stats, &dest->stats); if (copy_to_user(&uptr->entrytable[count], &entry, sizeof(entry))) { ret = -EFAULT; break; } count++; } } else ret = -ESRCH; return ret; } static inline void __ip_vs_get_timeouts(struct net *net, struct ip_vs_timeout_user *u) { #if defined(CONFIG_IP_VS_PROTO_TCP) || defined(CONFIG_IP_VS_PROTO_UDP) struct ip_vs_proto_data *pd; #endif #ifdef CONFIG_IP_VS_PROTO_TCP pd = ip_vs_proto_data_get(net, IPPROTO_TCP); u->tcp_timeout = pd->timeout_table[IP_VS_TCP_S_ESTABLISHED] / HZ; u->tcp_fin_timeout = pd->timeout_table[IP_VS_TCP_S_FIN_WAIT] / HZ; #endif #ifdef CONFIG_IP_VS_PROTO_UDP pd = ip_vs_proto_data_get(net, IPPROTO_UDP); u->udp_timeout = pd->timeout_table[IP_VS_UDP_S_NORMAL] / HZ; #endif } #define GET_CMDID(cmd) (cmd - IP_VS_BASE_CTL) #define GET_INFO_ARG_LEN (sizeof(struct ip_vs_getinfo)) #define GET_SERVICES_ARG_LEN (sizeof(struct ip_vs_get_services)) #define GET_SERVICE_ARG_LEN (sizeof(struct ip_vs_service_entry)) #define GET_DESTS_ARG_LEN (sizeof(struct ip_vs_get_dests)) #define GET_TIMEOUT_ARG_LEN (sizeof(struct ip_vs_timeout_user)) #define GET_DAEMON_ARG_LEN (sizeof(struct ip_vs_daemon_user) * 2) static const unsigned char get_arglen[GET_CMDID(IP_VS_SO_GET_MAX)+1] = { [GET_CMDID(IP_VS_SO_GET_VERSION)] = 64, [GET_CMDID(IP_VS_SO_GET_INFO)] = GET_INFO_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_SERVICES)] = GET_SERVICES_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_SERVICE)] = GET_SERVICE_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_DESTS)] = GET_DESTS_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_TIMEOUT)] = GET_TIMEOUT_ARG_LEN, [GET_CMDID(IP_VS_SO_GET_DAEMON)] = GET_DAEMON_ARG_LEN, }; static int do_ip_vs_get_ctl(struct sock *sk, int cmd, void __user *user, int *len) { unsigned char arg[128]; int ret = 0; unsigned int copylen; struct net *net = sock_net(sk); struct netns_ipvs *ipvs = net_ipvs(net); BUG_ON(!net); if (!capable(CAP_NET_ADMIN)) return -EPERM; if (cmd < IP_VS_BASE_CTL || cmd > IP_VS_SO_GET_MAX) return -EINVAL; if (*len < get_arglen[GET_CMDID(cmd)]) { pr_err("get_ctl: len %u < %u\n", *len, get_arglen[GET_CMDID(cmd)]); return -EINVAL; } copylen = get_arglen[GET_CMDID(cmd)]; if (copylen > 128) return -EINVAL; if (copy_from_user(arg, user, copylen) != 0) return -EFAULT; /* * Handle daemons first since it has its own locking */ if (cmd == IP_VS_SO_GET_DAEMON) { struct ip_vs_daemon_user d[2]; memset(&d, 0, sizeof(d)); if (mutex_lock_interruptible(&ipvs->sync_mutex)) return -ERESTARTSYS; if (ipvs->sync_state & IP_VS_STATE_MASTER) { d[0].state = IP_VS_STATE_MASTER; strlcpy(d[0].mcast_ifn, ipvs->master_mcast_ifn, sizeof(d[0].mcast_ifn)); d[0].syncid = ipvs->master_syncid; } if (ipvs->sync_state & IP_VS_STATE_BACKUP) { d[1].state = IP_VS_STATE_BACKUP; strlcpy(d[1].mcast_ifn, ipvs->backup_mcast_ifn, sizeof(d[1].mcast_ifn)); d[1].syncid = ipvs->backup_syncid; } if (copy_to_user(user, &d, sizeof(d)) != 0) ret = -EFAULT; mutex_unlock(&ipvs->sync_mutex); return ret; } if (mutex_lock_interruptible(&__ip_vs_mutex)) return -ERESTARTSYS; switch (cmd) { case IP_VS_SO_GET_VERSION: { char buf[64]; sprintf(buf, "IP Virtual Server version %d.%d.%d (size=%d)", NVERSION(IP_VS_VERSION_CODE), ip_vs_conn_tab_size); if (copy_to_user(user, buf, strlen(buf)+1) != 0) { ret = -EFAULT; goto out; } *len = strlen(buf)+1; } break; case IP_VS_SO_GET_INFO: { struct ip_vs_getinfo info; info.version = IP_VS_VERSION_CODE; info.size = ip_vs_conn_tab_size; info.num_services = ipvs->num_services; if (copy_to_user(user, &info, sizeof(info)) != 0) ret = -EFAULT; } break; case IP_VS_SO_GET_SERVICES: { struct ip_vs_get_services *get; int size; get = (struct ip_vs_get_services *)arg; size = sizeof(*get) + sizeof(struct ip_vs_service_entry) * get->num_services; if (*len != size) { pr_err("length: %u != %u\n", *len, size); ret = -EINVAL; goto out; } ret = __ip_vs_get_service_entries(net, get, user); } break; case IP_VS_SO_GET_SERVICE: { struct ip_vs_service_entry *entry; struct ip_vs_service *svc; union nf_inet_addr addr; entry = (struct ip_vs_service_entry *)arg; addr.ip = entry->addr; if (entry->fwmark) svc = __ip_vs_svc_fwm_find(net, AF_INET, entry->fwmark); else svc = __ip_vs_service_find(net, AF_INET, entry->protocol, &addr, entry->port); if (svc) { ip_vs_copy_service(entry, svc); if (copy_to_user(user, entry, sizeof(*entry)) != 0) ret = -EFAULT; } else ret = -ESRCH; } break; case IP_VS_SO_GET_DESTS: { struct ip_vs_get_dests *get; int size; get = (struct ip_vs_get_dests *)arg; size = sizeof(*get) + sizeof(struct ip_vs_dest_entry) * get->num_dests; if (*len != size) { pr_err("length: %u != %u\n", *len, size); ret = -EINVAL; goto out; } ret = __ip_vs_get_dest_entries(net, get, user); } break; case IP_VS_SO_GET_TIMEOUT: { struct ip_vs_timeout_user t; memset(&t, 0, sizeof(t)); __ip_vs_get_timeouts(net, &t); if (copy_to_user(user, &t, sizeof(t)) != 0) ret = -EFAULT; } break; default: ret = -EINVAL; } out: mutex_unlock(&__ip_vs_mutex); return ret; } static struct nf_sockopt_ops ip_vs_sockopts = { .pf = PF_INET, .set_optmin = IP_VS_BASE_CTL, .set_optmax = IP_VS_SO_SET_MAX+1, .set = do_ip_vs_set_ctl, .get_optmin = IP_VS_BASE_CTL, .get_optmax = IP_VS_SO_GET_MAX+1, .get = do_ip_vs_get_ctl, .owner = THIS_MODULE, }; /* * Generic Netlink interface */ /* IPVS genetlink family */ static struct genl_family ip_vs_genl_family = { .id = GENL_ID_GENERATE, .hdrsize = 0, .name = IPVS_GENL_NAME, .version = IPVS_GENL_VERSION, .maxattr = IPVS_CMD_MAX, .netnsok = true, /* Make ipvsadm to work on netns */ }; /* Policy used for first-level command attributes */ static const struct nla_policy ip_vs_cmd_policy[IPVS_CMD_ATTR_MAX + 1] = { [IPVS_CMD_ATTR_SERVICE] = { .type = NLA_NESTED }, [IPVS_CMD_ATTR_DEST] = { .type = NLA_NESTED }, [IPVS_CMD_ATTR_DAEMON] = { .type = NLA_NESTED }, [IPVS_CMD_ATTR_TIMEOUT_TCP] = { .type = NLA_U32 }, [IPVS_CMD_ATTR_TIMEOUT_TCP_FIN] = { .type = NLA_U32 }, [IPVS_CMD_ATTR_TIMEOUT_UDP] = { .type = NLA_U32 }, }; /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DAEMON */ static const struct nla_policy ip_vs_daemon_policy[IPVS_DAEMON_ATTR_MAX + 1] = { [IPVS_DAEMON_ATTR_STATE] = { .type = NLA_U32 }, [IPVS_DAEMON_ATTR_MCAST_IFN] = { .type = NLA_NUL_STRING, .len = IP_VS_IFNAME_MAXLEN }, [IPVS_DAEMON_ATTR_SYNC_ID] = { .type = NLA_U32 }, }; /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_SERVICE */ static const struct nla_policy ip_vs_svc_policy[IPVS_SVC_ATTR_MAX + 1] = { [IPVS_SVC_ATTR_AF] = { .type = NLA_U16 }, [IPVS_SVC_ATTR_PROTOCOL] = { .type = NLA_U16 }, [IPVS_SVC_ATTR_ADDR] = { .type = NLA_BINARY, .len = sizeof(union nf_inet_addr) }, [IPVS_SVC_ATTR_PORT] = { .type = NLA_U16 }, [IPVS_SVC_ATTR_FWMARK] = { .type = NLA_U32 }, [IPVS_SVC_ATTR_SCHED_NAME] = { .type = NLA_NUL_STRING, .len = IP_VS_SCHEDNAME_MAXLEN }, [IPVS_SVC_ATTR_PE_NAME] = { .type = NLA_NUL_STRING, .len = IP_VS_PENAME_MAXLEN }, [IPVS_SVC_ATTR_FLAGS] = { .type = NLA_BINARY, .len = sizeof(struct ip_vs_flags) }, [IPVS_SVC_ATTR_TIMEOUT] = { .type = NLA_U32 }, [IPVS_SVC_ATTR_NETMASK] = { .type = NLA_U32 }, [IPVS_SVC_ATTR_STATS] = { .type = NLA_NESTED }, }; /* Policy used for attributes in nested attribute IPVS_CMD_ATTR_DEST */ static const struct nla_policy ip_vs_dest_policy[IPVS_DEST_ATTR_MAX + 1] = { [IPVS_DEST_ATTR_ADDR] = { .type = NLA_BINARY, .len = sizeof(union nf_inet_addr) }, [IPVS_DEST_ATTR_PORT] = { .type = NLA_U16 }, [IPVS_DEST_ATTR_FWD_METHOD] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_WEIGHT] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_U_THRESH] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_L_THRESH] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_ACTIVE_CONNS] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_INACT_CONNS] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_PERSIST_CONNS] = { .type = NLA_U32 }, [IPVS_DEST_ATTR_STATS] = { .type = NLA_NESTED }, }; static int ip_vs_genl_fill_stats(struct sk_buff *skb, int container_type, struct ip_vs_stats *stats) { struct ip_vs_stats_user ustats; struct nlattr *nl_stats = nla_nest_start(skb, container_type); if (!nl_stats) return -EMSGSIZE; ip_vs_copy_stats(&ustats, stats); if (nla_put_u32(skb, IPVS_STATS_ATTR_CONNS, ustats.conns) || nla_put_u32(skb, IPVS_STATS_ATTR_INPKTS, ustats.inpkts) || nla_put_u32(skb, IPVS_STATS_ATTR_OUTPKTS, ustats.outpkts) || nla_put_u64(skb, IPVS_STATS_ATTR_INBYTES, ustats.inbytes) || nla_put_u64(skb, IPVS_STATS_ATTR_OUTBYTES, ustats.outbytes) || nla_put_u32(skb, IPVS_STATS_ATTR_CPS, ustats.cps) || nla_put_u32(skb, IPVS_STATS_ATTR_INPPS, ustats.inpps) || nla_put_u32(skb, IPVS_STATS_ATTR_OUTPPS, ustats.outpps) || nla_put_u32(skb, IPVS_STATS_ATTR_INBPS, ustats.inbps) || nla_put_u32(skb, IPVS_STATS_ATTR_OUTBPS, ustats.outbps)) goto nla_put_failure; nla_nest_end(skb, nl_stats); return 0; nla_put_failure: nla_nest_cancel(skb, nl_stats); return -EMSGSIZE; } static int ip_vs_genl_fill_service(struct sk_buff *skb, struct ip_vs_service *svc) { struct nlattr *nl_service; struct ip_vs_flags flags = { .flags = svc->flags, .mask = ~0 }; nl_service = nla_nest_start(skb, IPVS_CMD_ATTR_SERVICE); if (!nl_service) return -EMSGSIZE; if (nla_put_u16(skb, IPVS_SVC_ATTR_AF, svc->af)) goto nla_put_failure; if (svc->fwmark) { if (nla_put_u32(skb, IPVS_SVC_ATTR_FWMARK, svc->fwmark)) goto nla_put_failure; } else { if (nla_put_u16(skb, IPVS_SVC_ATTR_PROTOCOL, svc->protocol) || nla_put(skb, IPVS_SVC_ATTR_ADDR, sizeof(svc->addr), &svc->addr) || nla_put_u16(skb, IPVS_SVC_ATTR_PORT, svc->port)) goto nla_put_failure; } if (nla_put_string(skb, IPVS_SVC_ATTR_SCHED_NAME, svc->scheduler->name) || (svc->pe && nla_put_string(skb, IPVS_SVC_ATTR_PE_NAME, svc->pe->name)) || nla_put(skb, IPVS_SVC_ATTR_FLAGS, sizeof(flags), &flags) || nla_put_u32(skb, IPVS_SVC_ATTR_TIMEOUT, svc->timeout / HZ) || nla_put_u32(skb, IPVS_SVC_ATTR_NETMASK, svc->netmask)) goto nla_put_failure; if (ip_vs_genl_fill_stats(skb, IPVS_SVC_ATTR_STATS, &svc->stats)) goto nla_put_failure; nla_nest_end(skb, nl_service); return 0; nla_put_failure: nla_nest_cancel(skb, nl_service); return -EMSGSIZE; } static int ip_vs_genl_dump_service(struct sk_buff *skb, struct ip_vs_service *svc, struct netlink_callback *cb) { void *hdr; hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, &ip_vs_genl_family, NLM_F_MULTI, IPVS_CMD_NEW_SERVICE); if (!hdr) return -EMSGSIZE; if (ip_vs_genl_fill_service(skb, svc) < 0) goto nla_put_failure; return genlmsg_end(skb, hdr); nla_put_failure: genlmsg_cancel(skb, hdr); return -EMSGSIZE; } static int ip_vs_genl_dump_services(struct sk_buff *skb, struct netlink_callback *cb) { int idx = 0, i; int start = cb->args[0]; struct ip_vs_service *svc; struct net *net = skb_sknet(skb); mutex_lock(&__ip_vs_mutex); for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) { list_for_each_entry(svc, &ip_vs_svc_table[i], s_list) { if (++idx <= start || !net_eq(svc->net, net)) continue; if (ip_vs_genl_dump_service(skb, svc, cb) < 0) { idx--; goto nla_put_failure; } } } for (i = 0; i < IP_VS_SVC_TAB_SIZE; i++) { list_for_each_entry(svc, &ip_vs_svc_fwm_table[i], f_list) { if (++idx <= start || !net_eq(svc->net, net)) continue; if (ip_vs_genl_dump_service(skb, svc, cb) < 0) { idx--; goto nla_put_failure; } } } nla_put_failure: mutex_unlock(&__ip_vs_mutex); cb->args[0] = idx; return skb->len; } static int ip_vs_genl_parse_service(struct net *net, struct ip_vs_service_user_kern *usvc, struct nlattr *nla, int full_entry, struct ip_vs_service **ret_svc) { struct nlattr *attrs[IPVS_SVC_ATTR_MAX + 1]; struct nlattr *nla_af, *nla_port, *nla_fwmark, *nla_protocol, *nla_addr; struct ip_vs_service *svc; /* Parse mandatory identifying service fields first */ if (nla == NULL || nla_parse_nested(attrs, IPVS_SVC_ATTR_MAX, nla, ip_vs_svc_policy)) return -EINVAL; nla_af = attrs[IPVS_SVC_ATTR_AF]; nla_protocol = attrs[IPVS_SVC_ATTR_PROTOCOL]; nla_addr = attrs[IPVS_SVC_ATTR_ADDR]; nla_port = attrs[IPVS_SVC_ATTR_PORT]; nla_fwmark = attrs[IPVS_SVC_ATTR_FWMARK]; if (!(nla_af && (nla_fwmark || (nla_port && nla_protocol && nla_addr)))) return -EINVAL; memset(usvc, 0, sizeof(*usvc)); usvc->af = nla_get_u16(nla_af); #ifdef CONFIG_IP_VS_IPV6 if (usvc->af != AF_INET && usvc->af != AF_INET6) #else if (usvc->af != AF_INET) #endif return -EAFNOSUPPORT; if (nla_fwmark) { usvc->protocol = IPPROTO_TCP; usvc->fwmark = nla_get_u32(nla_fwmark); } else { usvc->protocol = nla_get_u16(nla_protocol); nla_memcpy(&usvc->addr, nla_addr, sizeof(usvc->addr)); usvc->port = nla_get_u16(nla_port); usvc->fwmark = 0; } if (usvc->fwmark) svc = __ip_vs_svc_fwm_find(net, usvc->af, usvc->fwmark); else svc = __ip_vs_service_find(net, usvc->af, usvc->protocol, &usvc->addr, usvc->port); *ret_svc = svc; /* If a full entry was requested, check for the additional fields */ if (full_entry) { struct nlattr *nla_sched, *nla_flags, *nla_pe, *nla_timeout, *nla_netmask; struct ip_vs_flags flags; nla_sched = attrs[IPVS_SVC_ATTR_SCHED_NAME]; nla_pe = attrs[IPVS_SVC_ATTR_PE_NAME]; nla_flags = attrs[IPVS_SVC_ATTR_FLAGS]; nla_timeout = attrs[IPVS_SVC_ATTR_TIMEOUT]; nla_netmask = attrs[IPVS_SVC_ATTR_NETMASK]; if (!(nla_sched && nla_flags && nla_timeout && nla_netmask)) return -EINVAL; nla_memcpy(&flags, nla_flags, sizeof(flags)); /* prefill flags from service if it already exists */ if (svc) usvc->flags = svc->flags; /* set new flags from userland */ usvc->flags = (usvc->flags & ~flags.mask) | (flags.flags & flags.mask); usvc->sched_name = nla_data(nla_sched); usvc->pe_name = nla_pe ? nla_data(nla_pe) : NULL; usvc->timeout = nla_get_u32(nla_timeout); usvc->netmask = nla_get_u32(nla_netmask); } return 0; } static struct ip_vs_service *ip_vs_genl_find_service(struct net *net, struct nlattr *nla) { struct ip_vs_service_user_kern usvc; struct ip_vs_service *svc; int ret; ret = ip_vs_genl_parse_service(net, &usvc, nla, 0, &svc); return ret ? ERR_PTR(ret) : svc; } static int ip_vs_genl_fill_dest(struct sk_buff *skb, struct ip_vs_dest *dest) { struct nlattr *nl_dest; nl_dest = nla_nest_start(skb, IPVS_CMD_ATTR_DEST); if (!nl_dest) return -EMSGSIZE; if (nla_put(skb, IPVS_DEST_ATTR_ADDR, sizeof(dest->addr), &dest->addr) || nla_put_u16(skb, IPVS_DEST_ATTR_PORT, dest->port) || nla_put_u32(skb, IPVS_DEST_ATTR_FWD_METHOD, (atomic_read(&dest->conn_flags) & IP_VS_CONN_F_FWD_MASK)) || nla_put_u32(skb, IPVS_DEST_ATTR_WEIGHT, atomic_read(&dest->weight)) || nla_put_u32(skb, IPVS_DEST_ATTR_U_THRESH, dest->u_threshold) || nla_put_u32(skb, IPVS_DEST_ATTR_L_THRESH, dest->l_threshold) || nla_put_u32(skb, IPVS_DEST_ATTR_ACTIVE_CONNS, atomic_read(&dest->activeconns)) || nla_put_u32(skb, IPVS_DEST_ATTR_INACT_CONNS, atomic_read(&dest->inactconns)) || nla_put_u32(skb, IPVS_DEST_ATTR_PERSIST_CONNS, atomic_read(&dest->persistconns))) goto nla_put_failure; if (ip_vs_genl_fill_stats(skb, IPVS_DEST_ATTR_STATS, &dest->stats)) goto nla_put_failure; nla_nest_end(skb, nl_dest); return 0; nla_put_failure: nla_nest_cancel(skb, nl_dest); return -EMSGSIZE; } static int ip_vs_genl_dump_dest(struct sk_buff *skb, struct ip_vs_dest *dest, struct netlink_callback *cb) { void *hdr; hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, &ip_vs_genl_family, NLM_F_MULTI, IPVS_CMD_NEW_DEST); if (!hdr) return -EMSGSIZE; if (ip_vs_genl_fill_dest(skb, dest) < 0) goto nla_put_failure; return genlmsg_end(skb, hdr); nla_put_failure: genlmsg_cancel(skb, hdr); return -EMSGSIZE; } static int ip_vs_genl_dump_dests(struct sk_buff *skb, struct netlink_callback *cb) { int idx = 0; int start = cb->args[0]; struct ip_vs_service *svc; struct ip_vs_dest *dest; struct nlattr *attrs[IPVS_CMD_ATTR_MAX + 1]; struct net *net = skb_sknet(skb); mutex_lock(&__ip_vs_mutex); /* Try to find the service for which to dump destinations */ if (nlmsg_parse(cb->nlh, GENL_HDRLEN, attrs, IPVS_CMD_ATTR_MAX, ip_vs_cmd_policy)) goto out_err; svc = ip_vs_genl_find_service(net, attrs[IPVS_CMD_ATTR_SERVICE]); if (IS_ERR(svc) || svc == NULL) goto out_err; /* Dump the destinations */ list_for_each_entry(dest, &svc->destinations, n_list) { if (++idx <= start) continue; if (ip_vs_genl_dump_dest(skb, dest, cb) < 0) { idx--; goto nla_put_failure; } } nla_put_failure: cb->args[0] = idx; out_err: mutex_unlock(&__ip_vs_mutex); return skb->len; } static int ip_vs_genl_parse_dest(struct ip_vs_dest_user_kern *udest, struct nlattr *nla, int full_entry) { struct nlattr *attrs[IPVS_DEST_ATTR_MAX + 1]; struct nlattr *nla_addr, *nla_port; /* Parse mandatory identifying destination fields first */ if (nla == NULL || nla_parse_nested(attrs, IPVS_DEST_ATTR_MAX, nla, ip_vs_dest_policy)) return -EINVAL; nla_addr = attrs[IPVS_DEST_ATTR_ADDR]; nla_port = attrs[IPVS_DEST_ATTR_PORT]; if (!(nla_addr && nla_port)) return -EINVAL; memset(udest, 0, sizeof(*udest)); nla_memcpy(&udest->addr, nla_addr, sizeof(udest->addr)); udest->port = nla_get_u16(nla_port); /* If a full entry was requested, check for the additional fields */ if (full_entry) { struct nlattr *nla_fwd, *nla_weight, *nla_u_thresh, *nla_l_thresh; nla_fwd = attrs[IPVS_DEST_ATTR_FWD_METHOD]; nla_weight = attrs[IPVS_DEST_ATTR_WEIGHT]; nla_u_thresh = attrs[IPVS_DEST_ATTR_U_THRESH]; nla_l_thresh = attrs[IPVS_DEST_ATTR_L_THRESH]; if (!(nla_fwd && nla_weight && nla_u_thresh && nla_l_thresh)) return -EINVAL; udest->conn_flags = nla_get_u32(nla_fwd) & IP_VS_CONN_F_FWD_MASK; udest->weight = nla_get_u32(nla_weight); udest->u_threshold = nla_get_u32(nla_u_thresh); udest->l_threshold = nla_get_u32(nla_l_thresh); } return 0; } static int ip_vs_genl_fill_daemon(struct sk_buff *skb, __be32 state, const char *mcast_ifn, __be32 syncid) { struct nlattr *nl_daemon; nl_daemon = nla_nest_start(skb, IPVS_CMD_ATTR_DAEMON); if (!nl_daemon) return -EMSGSIZE; if (nla_put_u32(skb, IPVS_DAEMON_ATTR_STATE, state) || nla_put_string(skb, IPVS_DAEMON_ATTR_MCAST_IFN, mcast_ifn) || nla_put_u32(skb, IPVS_DAEMON_ATTR_SYNC_ID, syncid)) goto nla_put_failure; nla_nest_end(skb, nl_daemon); return 0; nla_put_failure: nla_nest_cancel(skb, nl_daemon); return -EMSGSIZE; } static int ip_vs_genl_dump_daemon(struct sk_buff *skb, __be32 state, const char *mcast_ifn, __be32 syncid, struct netlink_callback *cb) { void *hdr; hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, &ip_vs_genl_family, NLM_F_MULTI, IPVS_CMD_NEW_DAEMON); if (!hdr) return -EMSGSIZE; if (ip_vs_genl_fill_daemon(skb, state, mcast_ifn, syncid)) goto nla_put_failure; return genlmsg_end(skb, hdr); nla_put_failure: genlmsg_cancel(skb, hdr); return -EMSGSIZE; } static int ip_vs_genl_dump_daemons(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = skb_sknet(skb); struct netns_ipvs *ipvs = net_ipvs(net); mutex_lock(&ipvs->sync_mutex); if ((ipvs->sync_state & IP_VS_STATE_MASTER) && !cb->args[0]) { if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_MASTER, ipvs->master_mcast_ifn, ipvs->master_syncid, cb) < 0) goto nla_put_failure; cb->args[0] = 1; } if ((ipvs->sync_state & IP_VS_STATE_BACKUP) && !cb->args[1]) { if (ip_vs_genl_dump_daemon(skb, IP_VS_STATE_BACKUP, ipvs->backup_mcast_ifn, ipvs->backup_syncid, cb) < 0) goto nla_put_failure; cb->args[1] = 1; } nla_put_failure: mutex_unlock(&ipvs->sync_mutex); return skb->len; } static int ip_vs_genl_new_daemon(struct net *net, struct nlattr **attrs) { if (!(attrs[IPVS_DAEMON_ATTR_STATE] && attrs[IPVS_DAEMON_ATTR_MCAST_IFN] && attrs[IPVS_DAEMON_ATTR_SYNC_ID])) return -EINVAL; return start_sync_thread(net, nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE]), nla_data(attrs[IPVS_DAEMON_ATTR_MCAST_IFN]), nla_get_u32(attrs[IPVS_DAEMON_ATTR_SYNC_ID])); } static int ip_vs_genl_del_daemon(struct net *net, struct nlattr **attrs) { if (!attrs[IPVS_DAEMON_ATTR_STATE]) return -EINVAL; return stop_sync_thread(net, nla_get_u32(attrs[IPVS_DAEMON_ATTR_STATE])); } static int ip_vs_genl_set_config(struct net *net, struct nlattr **attrs) { struct ip_vs_timeout_user t; __ip_vs_get_timeouts(net, &t); if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]) t.tcp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP]); if (attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]) t.tcp_fin_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_TCP_FIN]); if (attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]) t.udp_timeout = nla_get_u32(attrs[IPVS_CMD_ATTR_TIMEOUT_UDP]); return ip_vs_set_timeout(net, &t); } static int ip_vs_genl_set_daemon(struct sk_buff *skb, struct genl_info *info) { int ret = 0, cmd; struct net *net; struct netns_ipvs *ipvs; net = skb_sknet(skb); ipvs = net_ipvs(net); cmd = info->genlhdr->cmd; if (cmd == IPVS_CMD_NEW_DAEMON || cmd == IPVS_CMD_DEL_DAEMON) { struct nlattr *daemon_attrs[IPVS_DAEMON_ATTR_MAX + 1]; mutex_lock(&ipvs->sync_mutex); if (!info->attrs[IPVS_CMD_ATTR_DAEMON] || nla_parse_nested(daemon_attrs, IPVS_DAEMON_ATTR_MAX, info->attrs[IPVS_CMD_ATTR_DAEMON], ip_vs_daemon_policy)) { ret = -EINVAL; goto out; } if (cmd == IPVS_CMD_NEW_DAEMON) ret = ip_vs_genl_new_daemon(net, daemon_attrs); else ret = ip_vs_genl_del_daemon(net, daemon_attrs); out: mutex_unlock(&ipvs->sync_mutex); } return ret; } static int ip_vs_genl_set_cmd(struct sk_buff *skb, struct genl_info *info) { struct ip_vs_service *svc = NULL; struct ip_vs_service_user_kern usvc; struct ip_vs_dest_user_kern udest; int ret = 0, cmd; int need_full_svc = 0, need_full_dest = 0; struct net *net; net = skb_sknet(skb); cmd = info->genlhdr->cmd; mutex_lock(&__ip_vs_mutex); if (cmd == IPVS_CMD_FLUSH) { ret = ip_vs_flush(net); goto out; } else if (cmd == IPVS_CMD_SET_CONFIG) { ret = ip_vs_genl_set_config(net, info->attrs); goto out; } else if (cmd == IPVS_CMD_ZERO && !info->attrs[IPVS_CMD_ATTR_SERVICE]) { ret = ip_vs_zero_all(net); goto out; } /* All following commands require a service argument, so check if we * received a valid one. We need a full service specification when * adding / editing a service. Only identifying members otherwise. */ if (cmd == IPVS_CMD_NEW_SERVICE || cmd == IPVS_CMD_SET_SERVICE) need_full_svc = 1; ret = ip_vs_genl_parse_service(net, &usvc, info->attrs[IPVS_CMD_ATTR_SERVICE], need_full_svc, &svc); if (ret) goto out; /* Unless we're adding a new service, the service must already exist */ if ((cmd != IPVS_CMD_NEW_SERVICE) && (svc == NULL)) { ret = -ESRCH; goto out; } /* Destination commands require a valid destination argument. For * adding / editing a destination, we need a full destination * specification. */ if (cmd == IPVS_CMD_NEW_DEST || cmd == IPVS_CMD_SET_DEST || cmd == IPVS_CMD_DEL_DEST) { if (cmd != IPVS_CMD_DEL_DEST) need_full_dest = 1; ret = ip_vs_genl_parse_dest(&udest, info->attrs[IPVS_CMD_ATTR_DEST], need_full_dest); if (ret) goto out; } switch (cmd) { case IPVS_CMD_NEW_SERVICE: if (svc == NULL) ret = ip_vs_add_service(net, &usvc, &svc); else ret = -EEXIST; break; case IPVS_CMD_SET_SERVICE: ret = ip_vs_edit_service(svc, &usvc); break; case IPVS_CMD_DEL_SERVICE: ret = ip_vs_del_service(svc); /* do not use svc, it can be freed */ break; case IPVS_CMD_NEW_DEST: ret = ip_vs_add_dest(svc, &udest); break; case IPVS_CMD_SET_DEST: ret = ip_vs_edit_dest(svc, &udest); break; case IPVS_CMD_DEL_DEST: ret = ip_vs_del_dest(svc, &udest); break; case IPVS_CMD_ZERO: ret = ip_vs_zero_service(svc); break; default: ret = -EINVAL; } out: mutex_unlock(&__ip_vs_mutex); return ret; } static int ip_vs_genl_get_cmd(struct sk_buff *skb, struct genl_info *info) { struct sk_buff *msg; void *reply; int ret, cmd, reply_cmd; struct net *net; net = skb_sknet(skb); cmd = info->genlhdr->cmd; if (cmd == IPVS_CMD_GET_SERVICE) reply_cmd = IPVS_CMD_NEW_SERVICE; else if (cmd == IPVS_CMD_GET_INFO) reply_cmd = IPVS_CMD_SET_INFO; else if (cmd == IPVS_CMD_GET_CONFIG) reply_cmd = IPVS_CMD_SET_CONFIG; else { pr_err("unknown Generic Netlink command\n"); return -EINVAL; } msg = nlmsg_new(NLMSG_DEFAULT_SIZE, GFP_KERNEL); if (!msg) return -ENOMEM; mutex_lock(&__ip_vs_mutex); reply = genlmsg_put_reply(msg, info, &ip_vs_genl_family, 0, reply_cmd); if (reply == NULL) goto nla_put_failure; switch (cmd) { case IPVS_CMD_GET_SERVICE: { struct ip_vs_service *svc; svc = ip_vs_genl_find_service(net, info->attrs[IPVS_CMD_ATTR_SERVICE]); if (IS_ERR(svc)) { ret = PTR_ERR(svc); goto out_err; } else if (svc) { ret = ip_vs_genl_fill_service(msg, svc); if (ret) goto nla_put_failure; } else { ret = -ESRCH; goto out_err; } break; } case IPVS_CMD_GET_CONFIG: { struct ip_vs_timeout_user t; __ip_vs_get_timeouts(net, &t); #ifdef CONFIG_IP_VS_PROTO_TCP if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP, t.tcp_timeout) || nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_TCP_FIN, t.tcp_fin_timeout)) goto nla_put_failure; #endif #ifdef CONFIG_IP_VS_PROTO_UDP if (nla_put_u32(msg, IPVS_CMD_ATTR_TIMEOUT_UDP, t.udp_timeout)) goto nla_put_failure; #endif break; } case IPVS_CMD_GET_INFO: if (nla_put_u32(msg, IPVS_INFO_ATTR_VERSION, IP_VS_VERSION_CODE) || nla_put_u32(msg, IPVS_INFO_ATTR_CONN_TAB_SIZE, ip_vs_conn_tab_size)) goto nla_put_failure; break; } genlmsg_end(msg, reply); ret = genlmsg_reply(msg, info); goto out; nla_put_failure: pr_err("not enough space in Netlink message\n"); ret = -EMSGSIZE; out_err: nlmsg_free(msg); out: mutex_unlock(&__ip_vs_mutex); return ret; } static struct genl_ops ip_vs_genl_ops[] __read_mostly = { { .cmd = IPVS_CMD_NEW_SERVICE, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_SET_SERVICE, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_DEL_SERVICE, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_GET_SERVICE, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_get_cmd, .dumpit = ip_vs_genl_dump_services, .policy = ip_vs_cmd_policy, }, { .cmd = IPVS_CMD_NEW_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_SET_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_DEL_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_GET_DEST, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .dumpit = ip_vs_genl_dump_dests, }, { .cmd = IPVS_CMD_NEW_DAEMON, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_daemon, }, { .cmd = IPVS_CMD_DEL_DAEMON, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_daemon, }, { .cmd = IPVS_CMD_GET_DAEMON, .flags = GENL_ADMIN_PERM, .dumpit = ip_vs_genl_dump_daemons, }, { .cmd = IPVS_CMD_SET_CONFIG, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_GET_CONFIG, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_get_cmd, }, { .cmd = IPVS_CMD_GET_INFO, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_get_cmd, }, { .cmd = IPVS_CMD_ZERO, .flags = GENL_ADMIN_PERM, .policy = ip_vs_cmd_policy, .doit = ip_vs_genl_set_cmd, }, { .cmd = IPVS_CMD_FLUSH, .flags = GENL_ADMIN_PERM, .doit = ip_vs_genl_set_cmd, }, }; static int __init ip_vs_genl_register(void) { return genl_register_family_with_ops(&ip_vs_genl_family, ip_vs_genl_ops, ARRAY_SIZE(ip_vs_genl_ops)); } static void ip_vs_genl_unregister(void) { genl_unregister_family(&ip_vs_genl_family); } /* End of Generic Netlink interface definitions */ /* * per netns intit/exit func. */ #ifdef CONFIG_SYSCTL int __net_init ip_vs_control_net_init_sysctl(struct net *net) { int idx; struct netns_ipvs *ipvs = net_ipvs(net); struct ctl_table *tbl; atomic_set(&ipvs->dropentry, 0); spin_lock_init(&ipvs->dropentry_lock); spin_lock_init(&ipvs->droppacket_lock); spin_lock_init(&ipvs->securetcp_lock); if (!net_eq(net, &init_net)) { tbl = kmemdup(vs_vars, sizeof(vs_vars), GFP_KERNEL); if (tbl == NULL) return -ENOMEM; } else tbl = vs_vars; /* Initialize sysctl defaults */ idx = 0; ipvs->sysctl_amemthresh = 1024; tbl[idx++].data = &ipvs->sysctl_amemthresh; ipvs->sysctl_am_droprate = 10; tbl[idx++].data = &ipvs->sysctl_am_droprate; tbl[idx++].data = &ipvs->sysctl_drop_entry; tbl[idx++].data = &ipvs->sysctl_drop_packet; #ifdef CONFIG_IP_VS_NFCT tbl[idx++].data = &ipvs->sysctl_conntrack; #endif tbl[idx++].data = &ipvs->sysctl_secure_tcp; ipvs->sysctl_snat_reroute = 1; tbl[idx++].data = &ipvs->sysctl_snat_reroute; ipvs->sysctl_sync_ver = 1; tbl[idx++].data = &ipvs->sysctl_sync_ver; ipvs->sysctl_sync_ports = 1; tbl[idx++].data = &ipvs->sysctl_sync_ports; ipvs->sysctl_sync_qlen_max = nr_free_buffer_pages() / 32; tbl[idx++].data = &ipvs->sysctl_sync_qlen_max; ipvs->sysctl_sync_sock_size = 0; tbl[idx++].data = &ipvs->sysctl_sync_sock_size; tbl[idx++].data = &ipvs->sysctl_cache_bypass; tbl[idx++].data = &ipvs->sysctl_expire_nodest_conn; tbl[idx++].data = &ipvs->sysctl_expire_quiescent_template; ipvs->sysctl_sync_threshold[0] = DEFAULT_SYNC_THRESHOLD; ipvs->sysctl_sync_threshold[1] = DEFAULT_SYNC_PERIOD; tbl[idx].data = &ipvs->sysctl_sync_threshold; tbl[idx++].maxlen = sizeof(ipvs->sysctl_sync_threshold); ipvs->sysctl_sync_refresh_period = DEFAULT_SYNC_REFRESH_PERIOD; tbl[idx++].data = &ipvs->sysctl_sync_refresh_period; ipvs->sysctl_sync_retries = clamp_t(int, DEFAULT_SYNC_RETRIES, 0, 3); tbl[idx++].data = &ipvs->sysctl_sync_retries; tbl[idx++].data = &ipvs->sysctl_nat_icmp_send; ipvs->sysctl_hdr = register_net_sysctl(net, "net/ipv4/vs", tbl); if (ipvs->sysctl_hdr == NULL) { if (!net_eq(net, &init_net)) kfree(tbl); return -ENOMEM; } ip_vs_start_estimator(net, &ipvs->tot_stats); ipvs->sysctl_tbl = tbl; /* Schedule defense work */ INIT_DELAYED_WORK(&ipvs->defense_work, defense_work_handler); schedule_delayed_work(&ipvs->defense_work, DEFENSE_TIMER_PERIOD); return 0; } void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net) { struct netns_ipvs *ipvs = net_ipvs(net); cancel_delayed_work_sync(&ipvs->defense_work); cancel_work_sync(&ipvs->defense_work.work); unregister_net_sysctl_table(ipvs->sysctl_hdr); } #else int __net_init ip_vs_control_net_init_sysctl(struct net *net) { return 0; } void __net_exit ip_vs_control_net_cleanup_sysctl(struct net *net) { } #endif static struct notifier_block ip_vs_dst_notifier = { .notifier_call = ip_vs_dst_event, }; int __net_init ip_vs_control_net_init(struct net *net) { int idx; struct netns_ipvs *ipvs = net_ipvs(net); rwlock_init(&ipvs->rs_lock); /* Initialize rs_table */ for (idx = 0; idx < IP_VS_RTAB_SIZE; idx++) INIT_LIST_HEAD(&ipvs->rs_table[idx]); INIT_LIST_HEAD(&ipvs->dest_trash); atomic_set(&ipvs->ftpsvc_counter, 0); atomic_set(&ipvs->nullsvc_counter, 0); /* procfs stats */ ipvs->tot_stats.cpustats = alloc_percpu(struct ip_vs_cpu_stats); if (!ipvs->tot_stats.cpustats) return -ENOMEM; spin_lock_init(&ipvs->tot_stats.lock); proc_net_fops_create(net, "ip_vs", 0, &ip_vs_info_fops); proc_net_fops_create(net, "ip_vs_stats", 0, &ip_vs_stats_fops); proc_net_fops_create(net, "ip_vs_stats_percpu", 0, &ip_vs_stats_percpu_fops); if (ip_vs_control_net_init_sysctl(net)) goto err; return 0; err: free_percpu(ipvs->tot_stats.cpustats); return -ENOMEM; } void __net_exit ip_vs_control_net_cleanup(struct net *net) { struct netns_ipvs *ipvs = net_ipvs(net); ip_vs_trash_cleanup(net); ip_vs_stop_estimator(net, &ipvs->tot_stats); ip_vs_control_net_cleanup_sysctl(net); proc_net_remove(net, "ip_vs_stats_percpu"); proc_net_remove(net, "ip_vs_stats"); proc_net_remove(net, "ip_vs"); free_percpu(ipvs->tot_stats.cpustats); } int __init ip_vs_register_nl_ioctl(void) { int ret; ret = nf_register_sockopt(&ip_vs_sockopts); if (ret) { pr_err("cannot register sockopt.\n"); goto err_sock; } ret = ip_vs_genl_register(); if (ret) { pr_err("cannot register Generic Netlink interface.\n"); goto err_genl; } return 0; err_genl: nf_unregister_sockopt(&ip_vs_sockopts); err_sock: return ret; } void ip_vs_unregister_nl_ioctl(void) { ip_vs_genl_unregister(); nf_unregister_sockopt(&ip_vs_sockopts); } int __init ip_vs_control_init(void) { int idx; int ret; EnterFunction(2); /* Initialize svc_table, ip_vs_svc_fwm_table, rs_table */ for (idx = 0; idx < IP_VS_SVC_TAB_SIZE; idx++) { INIT_LIST_HEAD(&ip_vs_svc_table[idx]); INIT_LIST_HEAD(&ip_vs_svc_fwm_table[idx]); } smp_wmb(); /* Do we really need it now ? */ ret = register_netdevice_notifier(&ip_vs_dst_notifier); if (ret < 0) return ret; LeaveFunction(2); return 0; } void ip_vs_control_cleanup(void) { EnterFunction(2); unregister_netdevice_notifier(&ip_vs_dst_notifier); LeaveFunction(2); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_3828_0
crossvul-cpp_data_good_1508_4
/* Copyright (C) 2010 ABRT team Copyright (C) 2010 RedHat Inc This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "libabrt.h" #define ABRT_CONF "abrt.conf" char * g_settings_sWatchCrashdumpArchiveDir = NULL; unsigned int g_settings_nMaxCrashReportsSize = 1000; char * g_settings_dump_location = NULL; bool g_settings_delete_uploaded = 0; bool g_settings_autoreporting = 0; char * g_settings_autoreporting_event = NULL; bool g_settings_shortenedreporting = 0; bool g_settings_privatereports = true; void free_abrt_conf_data() { free(g_settings_sWatchCrashdumpArchiveDir); g_settings_sWatchCrashdumpArchiveDir = NULL; free(g_settings_dump_location); g_settings_dump_location = NULL; } static void ParseCommon(map_string_t *settings, const char *conf_filename) { const char *value; value = get_map_string_item_or_NULL(settings, "WatchCrashdumpArchiveDir"); if (value) { g_settings_sWatchCrashdumpArchiveDir = xstrdup(value); remove_map_string_item(settings, "WatchCrashdumpArchiveDir"); } value = get_map_string_item_or_NULL(settings, "MaxCrashReportsSize"); if (value) { char *end; errno = 0; unsigned long ul = strtoul(value, &end, 10); if (errno || end == value || *end != '\0' || ul > INT_MAX) error_msg("Error parsing %s setting: '%s'", "MaxCrashReportsSize", value); else g_settings_nMaxCrashReportsSize = ul; remove_map_string_item(settings, "MaxCrashReportsSize"); } value = get_map_string_item_or_NULL(settings, "DumpLocation"); if (value) { g_settings_dump_location = xstrdup(value); remove_map_string_item(settings, "DumpLocation"); } else g_settings_dump_location = xstrdup(DEFAULT_DUMP_LOCATION); value = get_map_string_item_or_NULL(settings, "DeleteUploaded"); if (value) { g_settings_delete_uploaded = string_to_bool(value); remove_map_string_item(settings, "DeleteUploaded"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEnabled"); if (value) { g_settings_autoreporting = string_to_bool(value); remove_map_string_item(settings, "AutoreportingEnabled"); } value = get_map_string_item_or_NULL(settings, "AutoreportingEvent"); if (value) { g_settings_autoreporting_event = xstrdup(value); remove_map_string_item(settings, "AutoreportingEvent"); } else g_settings_autoreporting_event = xstrdup("report_uReport"); value = get_map_string_item_or_NULL(settings, "ShortenedReporting"); if (value) { g_settings_shortenedreporting = string_to_bool(value); remove_map_string_item(settings, "ShortenedReporting"); } else g_settings_shortenedreporting = 0; value = get_map_string_item_or_NULL(settings, "PrivateReports"); if (value) { g_settings_privatereports = string_to_bool(value); remove_map_string_item(settings, "PrivateReports"); } GHashTableIter iter; const char *name; /*char *value; - already declared */ init_map_string_iter(&iter, settings); while (next_map_string_iter(&iter, &name, &value)) { error_msg("Unrecognized variable '%s' in '%s'", name, conf_filename); } } int load_abrt_conf() { free_abrt_conf_data(); map_string_t *settings = new_map_string(); if (!load_abrt_conf_file(ABRT_CONF, settings)) perror_msg("Can't load '%s'", ABRT_CONF); ParseCommon(settings, ABRT_CONF); free_map_string(settings); return 0; } int load_abrt_conf_file(const char *file, map_string_t *settings) { static const char *const base_directories[] = { DEFAULT_CONF_DIR, CONF_DIR, NULL }; return load_conf_file_from_dirs(file, base_directories, settings, /*skip key w/o values:*/ false); } int load_abrt_plugin_conf_file(const char *file, map_string_t *settings) { static const char *const base_directories[] = { DEFAULT_PLUGINS_CONF_DIR, PLUGINS_CONF_DIR, NULL }; return load_conf_file_from_dirs(file, base_directories, settings, /*skip key w/o values:*/ false); } int save_abrt_conf_file(const char *file, map_string_t *settings) { char *path = concat_path_file(CONF_DIR, file); int retval = save_conf_file(path, settings); free(path); return retval; } int save_abrt_plugin_conf_file(const char *file, map_string_t *settings) { char *path = concat_path_file(PLUGINS_CONF_DIR, file); int retval = save_conf_file(path, settings); free(path); return retval; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_1508_4
crossvul-cpp_data_bad_3834_0
/* BlueZ - Bluetooth protocol stack for Linux Copyright (C) 2000-2001 Qualcomm Incorporated Written 2000,2001 by Maxim Krasnyansky <maxk@qualcomm.com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS SOFTWARE IS DISCLAIMED. */ /* Bluetooth HCI sockets. */ #include <linux/export.h> #include <asm/unaligned.h> #include <net/bluetooth/bluetooth.h> #include <net/bluetooth/hci_core.h> #include <net/bluetooth/hci_mon.h> static atomic_t monitor_promisc = ATOMIC_INIT(0); /* ----- HCI socket interface ----- */ static inline int hci_test_bit(int nr, void *addr) { return *((__u32 *) addr + (nr >> 5)) & ((__u32) 1 << (nr & 31)); } /* Security filter */ static struct hci_sec_filter hci_sec_filter = { /* Packet types */ 0x10, /* Events */ { 0x1000d9fe, 0x0000b00c }, /* Commands */ { { 0x0 }, /* OGF_LINK_CTL */ { 0xbe000006, 0x00000001, 0x00000000, 0x00 }, /* OGF_LINK_POLICY */ { 0x00005200, 0x00000000, 0x00000000, 0x00 }, /* OGF_HOST_CTL */ { 0xaab00200, 0x2b402aaa, 0x05220154, 0x00 }, /* OGF_INFO_PARAM */ { 0x000002be, 0x00000000, 0x00000000, 0x00 }, /* OGF_STATUS_PARAM */ { 0x000000ea, 0x00000000, 0x00000000, 0x00 } } }; static struct bt_sock_list hci_sk_list = { .lock = __RW_LOCK_UNLOCKED(hci_sk_list.lock) }; /* Send frame to RAW socket */ void hci_send_to_sock(struct hci_dev *hdev, struct sk_buff *skb) { struct sock *sk; struct hlist_node *node; struct sk_buff *skb_copy = NULL; BT_DBG("hdev %p len %d", hdev, skb->len); read_lock(&hci_sk_list.lock); sk_for_each(sk, node, &hci_sk_list.head) { struct hci_filter *flt; struct sk_buff *nskb; if (sk->sk_state != BT_BOUND || hci_pi(sk)->hdev != hdev) continue; /* Don't send frame to the socket it came from */ if (skb->sk == sk) continue; if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) continue; /* Apply filter */ flt = &hci_pi(sk)->filter; if (!test_bit((bt_cb(skb)->pkt_type == HCI_VENDOR_PKT) ? 0 : (bt_cb(skb)->pkt_type & HCI_FLT_TYPE_BITS), &flt->type_mask)) continue; if (bt_cb(skb)->pkt_type == HCI_EVENT_PKT) { int evt = (*(__u8 *)skb->data & HCI_FLT_EVENT_BITS); if (!hci_test_bit(evt, &flt->event_mask)) continue; if (flt->opcode && ((evt == HCI_EV_CMD_COMPLETE && flt->opcode != get_unaligned((__le16 *)(skb->data + 3))) || (evt == HCI_EV_CMD_STATUS && flt->opcode != get_unaligned((__le16 *)(skb->data + 4))))) continue; } if (!skb_copy) { /* Create a private copy with headroom */ skb_copy = __pskb_copy(skb, 1, GFP_ATOMIC); if (!skb_copy) continue; /* Put type byte before the data */ memcpy(skb_push(skb_copy, 1), &bt_cb(skb)->pkt_type, 1); } nskb = skb_clone(skb_copy, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&hci_sk_list.lock); kfree_skb(skb_copy); } /* Send frame to control socket */ void hci_send_to_control(struct sk_buff *skb, struct sock *skip_sk) { struct sock *sk; struct hlist_node *node; BT_DBG("len %d", skb->len); read_lock(&hci_sk_list.lock); sk_for_each(sk, node, &hci_sk_list.head) { struct sk_buff *nskb; /* Skip the original socket */ if (sk == skip_sk) continue; if (sk->sk_state != BT_BOUND) continue; if (hci_pi(sk)->channel != HCI_CHANNEL_CONTROL) continue; nskb = skb_clone(skb, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&hci_sk_list.lock); } /* Send frame to monitor socket */ void hci_send_to_monitor(struct hci_dev *hdev, struct sk_buff *skb) { struct sock *sk; struct hlist_node *node; struct sk_buff *skb_copy = NULL; __le16 opcode; if (!atomic_read(&monitor_promisc)) return; BT_DBG("hdev %p len %d", hdev, skb->len); switch (bt_cb(skb)->pkt_type) { case HCI_COMMAND_PKT: opcode = __constant_cpu_to_le16(HCI_MON_COMMAND_PKT); break; case HCI_EVENT_PKT: opcode = __constant_cpu_to_le16(HCI_MON_EVENT_PKT); break; case HCI_ACLDATA_PKT: if (bt_cb(skb)->incoming) opcode = __constant_cpu_to_le16(HCI_MON_ACL_RX_PKT); else opcode = __constant_cpu_to_le16(HCI_MON_ACL_TX_PKT); break; case HCI_SCODATA_PKT: if (bt_cb(skb)->incoming) opcode = __constant_cpu_to_le16(HCI_MON_SCO_RX_PKT); else opcode = __constant_cpu_to_le16(HCI_MON_SCO_TX_PKT); break; default: return; } read_lock(&hci_sk_list.lock); sk_for_each(sk, node, &hci_sk_list.head) { struct sk_buff *nskb; if (sk->sk_state != BT_BOUND) continue; if (hci_pi(sk)->channel != HCI_CHANNEL_MONITOR) continue; if (!skb_copy) { struct hci_mon_hdr *hdr; /* Create a private copy with headroom */ skb_copy = __pskb_copy(skb, HCI_MON_HDR_SIZE, GFP_ATOMIC); if (!skb_copy) continue; /* Put header before the data */ hdr = (void *) skb_push(skb_copy, HCI_MON_HDR_SIZE); hdr->opcode = opcode; hdr->index = cpu_to_le16(hdev->id); hdr->len = cpu_to_le16(skb->len); } nskb = skb_clone(skb_copy, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&hci_sk_list.lock); kfree_skb(skb_copy); } static void send_monitor_event(struct sk_buff *skb) { struct sock *sk; struct hlist_node *node; BT_DBG("len %d", skb->len); read_lock(&hci_sk_list.lock); sk_for_each(sk, node, &hci_sk_list.head) { struct sk_buff *nskb; if (sk->sk_state != BT_BOUND) continue; if (hci_pi(sk)->channel != HCI_CHANNEL_MONITOR) continue; nskb = skb_clone(skb, GFP_ATOMIC); if (!nskb) continue; if (sock_queue_rcv_skb(sk, nskb)) kfree_skb(nskb); } read_unlock(&hci_sk_list.lock); } static struct sk_buff *create_monitor_event(struct hci_dev *hdev, int event) { struct hci_mon_hdr *hdr; struct hci_mon_new_index *ni; struct sk_buff *skb; __le16 opcode; switch (event) { case HCI_DEV_REG: skb = bt_skb_alloc(HCI_MON_NEW_INDEX_SIZE, GFP_ATOMIC); if (!skb) return NULL; ni = (void *) skb_put(skb, HCI_MON_NEW_INDEX_SIZE); ni->type = hdev->dev_type; ni->bus = hdev->bus; bacpy(&ni->bdaddr, &hdev->bdaddr); memcpy(ni->name, hdev->name, 8); opcode = __constant_cpu_to_le16(HCI_MON_NEW_INDEX); break; case HCI_DEV_UNREG: skb = bt_skb_alloc(0, GFP_ATOMIC); if (!skb) return NULL; opcode = __constant_cpu_to_le16(HCI_MON_DEL_INDEX); break; default: return NULL; } __net_timestamp(skb); hdr = (void *) skb_push(skb, HCI_MON_HDR_SIZE); hdr->opcode = opcode; hdr->index = cpu_to_le16(hdev->id); hdr->len = cpu_to_le16(skb->len - HCI_MON_HDR_SIZE); return skb; } static void send_monitor_replay(struct sock *sk) { struct hci_dev *hdev; read_lock(&hci_dev_list_lock); list_for_each_entry(hdev, &hci_dev_list, list) { struct sk_buff *skb; skb = create_monitor_event(hdev, HCI_DEV_REG); if (!skb) continue; if (sock_queue_rcv_skb(sk, skb)) kfree_skb(skb); } read_unlock(&hci_dev_list_lock); } /* Generate internal stack event */ static void hci_si_event(struct hci_dev *hdev, int type, int dlen, void *data) { struct hci_event_hdr *hdr; struct hci_ev_stack_internal *ev; struct sk_buff *skb; skb = bt_skb_alloc(HCI_EVENT_HDR_SIZE + sizeof(*ev) + dlen, GFP_ATOMIC); if (!skb) return; hdr = (void *) skb_put(skb, HCI_EVENT_HDR_SIZE); hdr->evt = HCI_EV_STACK_INTERNAL; hdr->plen = sizeof(*ev) + dlen; ev = (void *) skb_put(skb, sizeof(*ev) + dlen); ev->type = type; memcpy(ev->data, data, dlen); bt_cb(skb)->incoming = 1; __net_timestamp(skb); bt_cb(skb)->pkt_type = HCI_EVENT_PKT; skb->dev = (void *) hdev; hci_send_to_sock(hdev, skb); kfree_skb(skb); } void hci_sock_dev_event(struct hci_dev *hdev, int event) { struct hci_ev_si_device ev; BT_DBG("hdev %s event %d", hdev->name, event); /* Send event to monitor */ if (atomic_read(&monitor_promisc)) { struct sk_buff *skb; skb = create_monitor_event(hdev, event); if (skb) { send_monitor_event(skb); kfree_skb(skb); } } /* Send event to sockets */ ev.event = event; ev.dev_id = hdev->id; hci_si_event(NULL, HCI_EV_SI_DEVICE, sizeof(ev), &ev); if (event == HCI_DEV_UNREG) { struct sock *sk; struct hlist_node *node; /* Detach sockets from device */ read_lock(&hci_sk_list.lock); sk_for_each(sk, node, &hci_sk_list.head) { bh_lock_sock_nested(sk); if (hci_pi(sk)->hdev == hdev) { hci_pi(sk)->hdev = NULL; sk->sk_err = EPIPE; sk->sk_state = BT_OPEN; sk->sk_state_change(sk); hci_dev_put(hdev); } bh_unlock_sock(sk); } read_unlock(&hci_sk_list.lock); } } static int hci_sock_release(struct socket *sock) { struct sock *sk = sock->sk; struct hci_dev *hdev; BT_DBG("sock %p sk %p", sock, sk); if (!sk) return 0; hdev = hci_pi(sk)->hdev; if (hci_pi(sk)->channel == HCI_CHANNEL_MONITOR) atomic_dec(&monitor_promisc); bt_sock_unlink(&hci_sk_list, sk); if (hdev) { atomic_dec(&hdev->promisc); hci_dev_put(hdev); } sock_orphan(sk); skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_write_queue); sock_put(sk); return 0; } static int hci_sock_blacklist_add(struct hci_dev *hdev, void __user *arg) { bdaddr_t bdaddr; int err; if (copy_from_user(&bdaddr, arg, sizeof(bdaddr))) return -EFAULT; hci_dev_lock(hdev); err = hci_blacklist_add(hdev, &bdaddr, 0); hci_dev_unlock(hdev); return err; } static int hci_sock_blacklist_del(struct hci_dev *hdev, void __user *arg) { bdaddr_t bdaddr; int err; if (copy_from_user(&bdaddr, arg, sizeof(bdaddr))) return -EFAULT; hci_dev_lock(hdev); err = hci_blacklist_del(hdev, &bdaddr, 0); hci_dev_unlock(hdev); return err; } /* Ioctls that require bound socket */ static int hci_sock_bound_ioctl(struct sock *sk, unsigned int cmd, unsigned long arg) { struct hci_dev *hdev = hci_pi(sk)->hdev; if (!hdev) return -EBADFD; switch (cmd) { case HCISETRAW: if (!capable(CAP_NET_ADMIN)) return -EACCES; if (test_bit(HCI_QUIRK_RAW_DEVICE, &hdev->quirks)) return -EPERM; if (arg) set_bit(HCI_RAW, &hdev->flags); else clear_bit(HCI_RAW, &hdev->flags); return 0; case HCIGETCONNINFO: return hci_get_conn_info(hdev, (void __user *) arg); case HCIGETAUTHINFO: return hci_get_auth_info(hdev, (void __user *) arg); case HCIBLOCKADDR: if (!capable(CAP_NET_ADMIN)) return -EACCES; return hci_sock_blacklist_add(hdev, (void __user *) arg); case HCIUNBLOCKADDR: if (!capable(CAP_NET_ADMIN)) return -EACCES; return hci_sock_blacklist_del(hdev, (void __user *) arg); default: if (hdev->ioctl) return hdev->ioctl(hdev, cmd, arg); return -EINVAL; } } static int hci_sock_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg) { struct sock *sk = sock->sk; void __user *argp = (void __user *) arg; int err; BT_DBG("cmd %x arg %lx", cmd, arg); switch (cmd) { case HCIGETDEVLIST: return hci_get_dev_list(argp); case HCIGETDEVINFO: return hci_get_dev_info(argp); case HCIGETCONNLIST: return hci_get_conn_list(argp); case HCIDEVUP: if (!capable(CAP_NET_ADMIN)) return -EACCES; return hci_dev_open(arg); case HCIDEVDOWN: if (!capable(CAP_NET_ADMIN)) return -EACCES; return hci_dev_close(arg); case HCIDEVRESET: if (!capable(CAP_NET_ADMIN)) return -EACCES; return hci_dev_reset(arg); case HCIDEVRESTAT: if (!capable(CAP_NET_ADMIN)) return -EACCES; return hci_dev_reset_stat(arg); case HCISETSCAN: case HCISETAUTH: case HCISETENCRYPT: case HCISETPTYPE: case HCISETLINKPOL: case HCISETLINKMODE: case HCISETACLMTU: case HCISETSCOMTU: if (!capable(CAP_NET_ADMIN)) return -EACCES; return hci_dev_cmd(cmd, argp); case HCIINQUIRY: return hci_inquiry(argp); default: lock_sock(sk); err = hci_sock_bound_ioctl(sk, cmd, arg); release_sock(sk); return err; } } static int hci_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_hci haddr; struct sock *sk = sock->sk; struct hci_dev *hdev = NULL; int len, err = 0; BT_DBG("sock %p sk %p", sock, sk); if (!addr) return -EINVAL; memset(&haddr, 0, sizeof(haddr)); len = min_t(unsigned int, sizeof(haddr), addr_len); memcpy(&haddr, addr, len); if (haddr.hci_family != AF_BLUETOOTH) return -EINVAL; lock_sock(sk); if (sk->sk_state == BT_BOUND) { err = -EALREADY; goto done; } switch (haddr.hci_channel) { case HCI_CHANNEL_RAW: if (hci_pi(sk)->hdev) { err = -EALREADY; goto done; } if (haddr.hci_dev != HCI_DEV_NONE) { hdev = hci_dev_get(haddr.hci_dev); if (!hdev) { err = -ENODEV; goto done; } atomic_inc(&hdev->promisc); } hci_pi(sk)->hdev = hdev; break; case HCI_CHANNEL_CONTROL: if (haddr.hci_dev != HCI_DEV_NONE) { err = -EINVAL; goto done; } if (!capable(CAP_NET_ADMIN)) { err = -EPERM; goto done; } break; case HCI_CHANNEL_MONITOR: if (haddr.hci_dev != HCI_DEV_NONE) { err = -EINVAL; goto done; } if (!capable(CAP_NET_RAW)) { err = -EPERM; goto done; } send_monitor_replay(sk); atomic_inc(&monitor_promisc); break; default: err = -EINVAL; goto done; } hci_pi(sk)->channel = haddr.hci_channel; sk->sk_state = BT_BOUND; done: release_sock(sk); return err; } static int hci_sock_getname(struct socket *sock, struct sockaddr *addr, int *addr_len, int peer) { struct sockaddr_hci *haddr = (struct sockaddr_hci *) addr; struct sock *sk = sock->sk; struct hci_dev *hdev = hci_pi(sk)->hdev; BT_DBG("sock %p sk %p", sock, sk); if (!hdev) return -EBADFD; lock_sock(sk); *addr_len = sizeof(*haddr); haddr->hci_family = AF_BLUETOOTH; haddr->hci_dev = hdev->id; release_sock(sk); return 0; } static void hci_sock_cmsg(struct sock *sk, struct msghdr *msg, struct sk_buff *skb) { __u32 mask = hci_pi(sk)->cmsg_mask; if (mask & HCI_CMSG_DIR) { int incoming = bt_cb(skb)->incoming; put_cmsg(msg, SOL_HCI, HCI_CMSG_DIR, sizeof(incoming), &incoming); } if (mask & HCI_CMSG_TSTAMP) { #ifdef CONFIG_COMPAT struct compat_timeval ctv; #endif struct timeval tv; void *data; int len; skb_get_timestamp(skb, &tv); data = &tv; len = sizeof(tv); #ifdef CONFIG_COMPAT if (!COMPAT_USE_64BIT_TIME && (msg->msg_flags & MSG_CMSG_COMPAT)) { ctv.tv_sec = tv.tv_sec; ctv.tv_usec = tv.tv_usec; data = &ctv; len = sizeof(ctv); } #endif put_cmsg(msg, SOL_HCI, HCI_CMSG_TSTAMP, len, data); } } static int hci_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct sk_buff *skb; int copied, err; BT_DBG("sock %p, sk %p", sock, sk); if (flags & (MSG_OOB)) return -EOPNOTSUPP; if (sk->sk_state == BT_CLOSED) return 0; skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) return err; msg->msg_namelen = 0; copied = skb->len; if (len < copied) { msg->msg_flags |= MSG_TRUNC; copied = len; } skb_reset_transport_header(skb); err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied); switch (hci_pi(sk)->channel) { case HCI_CHANNEL_RAW: hci_sock_cmsg(sk, msg, skb); break; case HCI_CHANNEL_CONTROL: case HCI_CHANNEL_MONITOR: sock_recv_timestamp(msg, sk, skb); break; } skb_free_datagram(sk, skb); return err ? : copied; } static int hci_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct hci_dev *hdev; struct sk_buff *skb; int err; BT_DBG("sock %p sk %p", sock, sk); if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_NOSIGNAL|MSG_ERRQUEUE)) return -EINVAL; if (len < 4 || len > HCI_MAX_FRAME_SIZE) return -EINVAL; lock_sock(sk); switch (hci_pi(sk)->channel) { case HCI_CHANNEL_RAW: break; case HCI_CHANNEL_CONTROL: err = mgmt_control(sk, msg, len); goto done; case HCI_CHANNEL_MONITOR: err = -EOPNOTSUPP; goto done; default: err = -EINVAL; goto done; } hdev = hci_pi(sk)->hdev; if (!hdev) { err = -EBADFD; goto done; } if (!test_bit(HCI_UP, &hdev->flags)) { err = -ENETDOWN; goto done; } skb = bt_skb_send_alloc(sk, len, msg->msg_flags & MSG_DONTWAIT, &err); if (!skb) goto done; if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { err = -EFAULT; goto drop; } bt_cb(skb)->pkt_type = *((unsigned char *) skb->data); skb_pull(skb, 1); skb->dev = (void *) hdev; if (bt_cb(skb)->pkt_type == HCI_COMMAND_PKT) { u16 opcode = get_unaligned_le16(skb->data); u16 ogf = hci_opcode_ogf(opcode); u16 ocf = hci_opcode_ocf(opcode); if (((ogf > HCI_SFLT_MAX_OGF) || !hci_test_bit(ocf & HCI_FLT_OCF_BITS, &hci_sec_filter.ocf_mask[ogf])) && !capable(CAP_NET_RAW)) { err = -EPERM; goto drop; } if (test_bit(HCI_RAW, &hdev->flags) || (ogf == 0x3f)) { skb_queue_tail(&hdev->raw_q, skb); queue_work(hdev->workqueue, &hdev->tx_work); } else { skb_queue_tail(&hdev->cmd_q, skb); queue_work(hdev->workqueue, &hdev->cmd_work); } } else { if (!capable(CAP_NET_RAW)) { err = -EPERM; goto drop; } skb_queue_tail(&hdev->raw_q, skb); queue_work(hdev->workqueue, &hdev->tx_work); } err = len; done: release_sock(sk); return err; drop: kfree_skb(skb); goto done; } static int hci_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int len) { struct hci_ufilter uf = { .opcode = 0 }; struct sock *sk = sock->sk; int err = 0, opt = 0; BT_DBG("sk %p, opt %d", sk, optname); lock_sock(sk); if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) { err = -EINVAL; goto done; } switch (optname) { case HCI_DATA_DIR: if (get_user(opt, (int __user *)optval)) { err = -EFAULT; break; } if (opt) hci_pi(sk)->cmsg_mask |= HCI_CMSG_DIR; else hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_DIR; break; case HCI_TIME_STAMP: if (get_user(opt, (int __user *)optval)) { err = -EFAULT; break; } if (opt) hci_pi(sk)->cmsg_mask |= HCI_CMSG_TSTAMP; else hci_pi(sk)->cmsg_mask &= ~HCI_CMSG_TSTAMP; break; case HCI_FILTER: { struct hci_filter *f = &hci_pi(sk)->filter; uf.type_mask = f->type_mask; uf.opcode = f->opcode; uf.event_mask[0] = *((u32 *) f->event_mask + 0); uf.event_mask[1] = *((u32 *) f->event_mask + 1); } len = min_t(unsigned int, len, sizeof(uf)); if (copy_from_user(&uf, optval, len)) { err = -EFAULT; break; } if (!capable(CAP_NET_RAW)) { uf.type_mask &= hci_sec_filter.type_mask; uf.event_mask[0] &= *((u32 *) hci_sec_filter.event_mask + 0); uf.event_mask[1] &= *((u32 *) hci_sec_filter.event_mask + 1); } { struct hci_filter *f = &hci_pi(sk)->filter; f->type_mask = uf.type_mask; f->opcode = uf.opcode; *((u32 *) f->event_mask + 0) = uf.event_mask[0]; *((u32 *) f->event_mask + 1) = uf.event_mask[1]; } break; default: err = -ENOPROTOOPT; break; } done: release_sock(sk); return err; } static int hci_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct hci_ufilter uf; struct sock *sk = sock->sk; int len, opt, err = 0; BT_DBG("sk %p, opt %d", sk, optname); if (get_user(len, optlen)) return -EFAULT; lock_sock(sk); if (hci_pi(sk)->channel != HCI_CHANNEL_RAW) { err = -EINVAL; goto done; } switch (optname) { case HCI_DATA_DIR: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_DIR) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_TIME_STAMP: if (hci_pi(sk)->cmsg_mask & HCI_CMSG_TSTAMP) opt = 1; else opt = 0; if (put_user(opt, optval)) err = -EFAULT; break; case HCI_FILTER: { struct hci_filter *f = &hci_pi(sk)->filter; uf.type_mask = f->type_mask; uf.opcode = f->opcode; uf.event_mask[0] = *((u32 *) f->event_mask + 0); uf.event_mask[1] = *((u32 *) f->event_mask + 1); } len = min_t(unsigned int, len, sizeof(uf)); if (copy_to_user(optval, &uf, len)) err = -EFAULT; break; default: err = -ENOPROTOOPT; break; } done: release_sock(sk); return err; } static const struct proto_ops hci_sock_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .release = hci_sock_release, .bind = hci_sock_bind, .getname = hci_sock_getname, .sendmsg = hci_sock_sendmsg, .recvmsg = hci_sock_recvmsg, .ioctl = hci_sock_ioctl, .poll = datagram_poll, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = hci_sock_setsockopt, .getsockopt = hci_sock_getsockopt, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .mmap = sock_no_mmap }; static struct proto hci_sk_proto = { .name = "HCI", .owner = THIS_MODULE, .obj_size = sizeof(struct hci_pinfo) }; static int hci_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; BT_DBG("sock %p", sock); if (sock->type != SOCK_RAW) return -ESOCKTNOSUPPORT; sock->ops = &hci_sock_ops; sk = sk_alloc(net, PF_BLUETOOTH, GFP_ATOMIC, &hci_sk_proto); if (!sk) return -ENOMEM; sock_init_data(sock, sk); sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = protocol; sock->state = SS_UNCONNECTED; sk->sk_state = BT_OPEN; bt_sock_link(&hci_sk_list, sk); return 0; } static const struct net_proto_family hci_sock_family_ops = { .family = PF_BLUETOOTH, .owner = THIS_MODULE, .create = hci_sock_create, }; int __init hci_sock_init(void) { int err; err = proto_register(&hci_sk_proto, 0); if (err < 0) return err; err = bt_sock_register(BTPROTO_HCI, &hci_sock_family_ops); if (err < 0) goto error; BT_INFO("HCI socket layer initialized"); return 0; error: BT_ERR("HCI socket registration failed"); proto_unregister(&hci_sk_proto); return err; } void hci_sock_cleanup(void) { if (bt_sock_unregister(BTPROTO_HCI) < 0) BT_ERR("HCI socket unregistration failed"); proto_unregister(&hci_sk_proto); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_3834_0
crossvul-cpp_data_good_203_0
/* Copyright (c) 2013-2018 the Civetweb developers * Copyright (c) 2004-2013 Sergey Lyubka * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ #if defined(__GNUC__) || defined(__MINGW32__) /* Disable unused macros warnings - not all defines are required * for all systems and all compilers. */ #pragma GCC diagnostic ignored "-Wunused-macros" /* A padding warning is just plain useless */ #pragma GCC diagnostic ignored "-Wpadded" #endif #if defined(__clang__) /* GCC does not (yet) support this pragma */ /* We must set some flags for the headers we include. These flags * are reserved ids according to C99, so we need to disable a * warning for that. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wreserved-id-macro" #endif #if defined(_WIN32) #if !defined(_CRT_SECURE_NO_WARNINGS) #define _CRT_SECURE_NO_WARNINGS /* Disable deprecation warning in VS2005 */ #endif #if !defined(_WIN32_WINNT) /* defined for tdm-gcc so we can use getnameinfo */ #define _WIN32_WINNT 0x0501 #endif #else #if !defined(_GNU_SOURCE) #define _GNU_SOURCE /* for setgroups(), pthread_setname_np() */ #endif #if defined(__linux__) && !defined(_XOPEN_SOURCE) #define _XOPEN_SOURCE 600 /* For flockfile() on Linux */ #endif #if !defined(_LARGEFILE_SOURCE) #define _LARGEFILE_SOURCE /* For fseeko(), ftello() */ #endif #if !defined(_FILE_OFFSET_BITS) #define _FILE_OFFSET_BITS 64 /* Use 64-bit file offsets by default */ #endif #if !defined(__STDC_FORMAT_MACROS) #define __STDC_FORMAT_MACROS /* <inttypes.h> wants this for C++ */ #endif #if !defined(__STDC_LIMIT_MACROS) #define __STDC_LIMIT_MACROS /* C++ wants that for INT64_MAX */ #endif #if !defined(_DARWIN_UNLIMITED_SELECT) #define _DARWIN_UNLIMITED_SELECT #endif #if defined(__sun) #define __EXTENSIONS__ /* to expose flockfile and friends in stdio.h */ #define __inline inline /* not recognized on older compiler versions */ #endif #endif #if defined(__clang__) /* Enable reserved-id-macro warning again. */ #pragma GCC diagnostic pop #endif #if defined(USE_LUA) #define USE_TIMERS #endif #if defined(_MSC_VER) /* 'type cast' : conversion from 'int' to 'HANDLE' of greater size */ #pragma warning(disable : 4306) /* conditional expression is constant: introduced by FD_SET(..) */ #pragma warning(disable : 4127) /* non-constant aggregate initializer: issued due to missing C99 support */ #pragma warning(disable : 4204) /* padding added after data member */ #pragma warning(disable : 4820) /* not defined as a preprocessor macro, replacing with '0' for '#if/#elif' */ #pragma warning(disable : 4668) /* no function prototype given: converting '()' to '(void)' */ #pragma warning(disable : 4255) /* function has been selected for automatic inline expansion */ #pragma warning(disable : 4711) #endif /* This code uses static_assert to check some conditions. * Unfortunately some compilers still do not support it, so we have a * replacement function here. */ #if defined(__STDC_VERSION__) && __STDC_VERSION__ > 201100L #define mg_static_assert _Static_assert #elif defined(__cplusplus) && __cplusplus >= 201103L #define mg_static_assert static_assert #else char static_assert_replacement[1]; #define mg_static_assert(cond, txt) \ extern char static_assert_replacement[(cond) ? 1 : -1] #endif mg_static_assert(sizeof(int) == 4 || sizeof(int) == 8, "int data type size check"); mg_static_assert(sizeof(void *) == 4 || sizeof(void *) == 8, "pointer data type size check"); mg_static_assert(sizeof(void *) >= sizeof(int), "data type size check"); /* Alternative queue is well tested and should be the new default */ #if defined(NO_ALTERNATIVE_QUEUE) #if defined(ALTERNATIVE_QUEUE) #error "Define ALTERNATIVE_QUEUE or NO_ALTERNATIVE_QUEUE or none, but not both" #endif #else #define ALTERNATIVE_QUEUE #endif /* DTL -- including winsock2.h works better if lean and mean */ #if !defined(WIN32_LEAN_AND_MEAN) #define WIN32_LEAN_AND_MEAN #endif #if defined(__SYMBIAN32__) /* According to https://en.wikipedia.org/wiki/Symbian#History, * Symbian is no longer maintained since 2014-01-01. * Recent versions of CivetWeb are no longer tested for Symbian. * It makes no sense, to support an abandoned operating system. */ #error "Symbian is no longer maintained. CivetWeb no longer supports Symbian." #define NO_SSL /* SSL is not supported */ #define NO_CGI /* CGI is not supported */ #define PATH_MAX FILENAME_MAX #endif /* __SYMBIAN32__ */ #if !defined(CIVETWEB_HEADER_INCLUDED) /* Include the header file here, so the CivetWeb interface is defined for the * entire implementation, including the following forward definitions. */ #include "civetweb.h" #endif #if !defined(DEBUG_TRACE) #if defined(DEBUG) static void DEBUG_TRACE_FUNC(const char *func, unsigned line, PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(3, 4); #define DEBUG_TRACE(fmt, ...) \ DEBUG_TRACE_FUNC(__func__, __LINE__, fmt, __VA_ARGS__) #define NEED_DEBUG_TRACE_FUNC #else #define DEBUG_TRACE(fmt, ...) \ do { \ } while (0) #endif /* DEBUG */ #endif /* DEBUG_TRACE */ #if !defined(DEBUG_ASSERT) #if defined(DEBUG) #define DEBUG_ASSERT(cond) \ do { \ if (!(cond)) { \ DEBUG_TRACE("ASSERTION FAILED: %s", #cond); \ exit(2); /* Exit with error */ \ } \ } while (0) #else #define DEBUG_ASSERT(cond) #endif /* DEBUG */ #endif #if !defined(IGNORE_UNUSED_RESULT) #define IGNORE_UNUSED_RESULT(a) ((void)((a) && 1)) #endif #if defined(__GNUC__) || defined(__MINGW32__) /* GCC unused function attribute seems fundamentally broken. * Several attempts to tell the compiler "THIS FUNCTION MAY BE USED * OR UNUSED" for individual functions failed. * Either the compiler creates an "unused-function" warning if a * function is not marked with __attribute__((unused)). * On the other hand, if the function is marked with this attribute, * but is used, the compiler raises a completely idiotic * "used-but-marked-unused" warning - and * #pragma GCC diagnostic ignored "-Wused-but-marked-unused" * raises error: unknown option after "#pragma GCC diagnostic". * Disable this warning completely, until the GCC guys sober up * again. */ #pragma GCC diagnostic ignored "-Wunused-function" #define FUNCTION_MAY_BE_UNUSED /* __attribute__((unused)) */ #else #define FUNCTION_MAY_BE_UNUSED #endif /* Some ANSI #includes are not available on Windows CE */ #if !defined(_WIN32_WCE) #include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <signal.h> #include <fcntl.h> #endif /* !_WIN32_WCE */ #if defined(__clang__) /* When using -Weverything, clang does not accept it's own headers * in a release build configuration. Disable what is too much in * -Weverything. */ #pragma clang diagnostic ignored "-Wdisabled-macro-expansion" #endif #if defined(__GNUC__) || defined(__MINGW32__) /* Who on earth came to the conclusion, using __DATE__ should rise * an "expansion of date or time macro is not reproducible" * warning. That's exactly what was intended by using this macro. * Just disable this nonsense warning. */ /* And disabling them does not work either: * #pragma clang diagnostic ignored "-Wno-error=date-time" * #pragma clang diagnostic ignored "-Wdate-time" * So we just have to disable ALL warnings for some lines * of code. * This seems to be a known GCC bug, not resolved since 2012: * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=53431 */ #endif #if defined(__MACH__) /* Apple OSX section */ #if defined(__clang__) #if (__clang_major__ == 3) && ((__clang_minor__ == 7) || (__clang_minor__ == 8)) /* Avoid warnings for Xcode 7. It seems it does no longer exist in Xcode 8 */ #pragma clang diagnostic ignored "-Wno-reserved-id-macro" #pragma clang diagnostic ignored "-Wno-keyword-macro" #endif #endif #define CLOCK_MONOTONIC (1) #define CLOCK_REALTIME (2) #include <sys/errno.h> #include <sys/time.h> #include <mach/clock.h> #include <mach/mach.h> #include <mach/mach_time.h> /* clock_gettime is not implemented on OSX prior to 10.12 */ static int _civet_clock_gettime(int clk_id, struct timespec *t) { memset(t, 0, sizeof(*t)); if (clk_id == CLOCK_REALTIME) { struct timeval now; int rv = gettimeofday(&now, NULL); if (rv) { return rv; } t->tv_sec = now.tv_sec; t->tv_nsec = now.tv_usec * 1000; return 0; } else if (clk_id == CLOCK_MONOTONIC) { static uint64_t clock_start_time = 0; static mach_timebase_info_data_t timebase_ifo = {0, 0}; uint64_t now = mach_absolute_time(); if (clock_start_time == 0) { kern_return_t mach_status = mach_timebase_info(&timebase_ifo); DEBUG_ASSERT(mach_status == KERN_SUCCESS); /* appease "unused variable" warning for release builds */ (void)mach_status; clock_start_time = now; } now = (uint64_t)((double)(now - clock_start_time) * (double)timebase_ifo.numer / (double)timebase_ifo.denom); t->tv_sec = now / 1000000000; t->tv_nsec = now % 1000000000; return 0; } return -1; /* EINVAL - Clock ID is unknown */ } /* if clock_gettime is declared, then __CLOCK_AVAILABILITY will be defined */ #if defined(__CLOCK_AVAILABILITY) /* If we compiled with Mac OSX 10.12 or later, then clock_gettime will be * declared but it may be NULL at runtime. So we need to check before using * it. */ static int _civet_safe_clock_gettime(int clk_id, struct timespec *t) { if (clock_gettime) { return clock_gettime(clk_id, t); } return _civet_clock_gettime(clk_id, t); } #define clock_gettime _civet_safe_clock_gettime #else #define clock_gettime _civet_clock_gettime #endif #endif #include <time.h> #include <stdlib.h> #include <stdarg.h> #include <string.h> #include <ctype.h> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdint.h> /********************************************************************/ /* CivetWeb configuration defines */ /********************************************************************/ /* Maximum number of threads that can be configured. * The number of threads actually created depends on the "num_threads" * configuration parameter, but this is the upper limit. */ #if !defined(MAX_WORKER_THREADS) #define MAX_WORKER_THREADS (1024 * 64) /* in threads (count) */ #endif /* Timeout interval for select/poll calls. * The timeouts depend on "*_timeout_ms" configuration values, but long * timeouts are split into timouts as small as SOCKET_TIMEOUT_QUANTUM. * This reduces the time required to stop the server. */ #if !defined(SOCKET_TIMEOUT_QUANTUM) #define SOCKET_TIMEOUT_QUANTUM (2000) /* in ms */ #endif /* Do not try to compress files smaller than this limit. */ #if !defined(MG_FILE_COMPRESSION_SIZE_LIMIT) #define MG_FILE_COMPRESSION_SIZE_LIMIT (1024) /* in bytes */ #endif #if !defined(PASSWORDS_FILE_NAME) #define PASSWORDS_FILE_NAME ".htpasswd" #endif /* Initial buffer size for all CGI environment variables. In case there is * not enough space, another block is allocated. */ #if !defined(CGI_ENVIRONMENT_SIZE) #define CGI_ENVIRONMENT_SIZE (4096) /* in bytes */ #endif /* Maximum number of environment variables. */ #if !defined(MAX_CGI_ENVIR_VARS) #define MAX_CGI_ENVIR_VARS (256) /* in variables (count) */ #endif /* General purpose buffer size. */ #if !defined(MG_BUF_LEN) /* in bytes */ #define MG_BUF_LEN (1024 * 8) #endif /* Size of the accepted socket queue (in case the old queue implementation * is used). */ #if !defined(MGSQLEN) #define MGSQLEN (20) /* count */ #endif /********************************************************************/ /* Helper makros */ #define ARRAY_SIZE(array) (sizeof(array) / sizeof(array[0])) /* Standard defines */ #if !defined(INT64_MAX) #define INT64_MAX (9223372036854775807) #endif #define SHUTDOWN_RD (0) #define SHUTDOWN_WR (1) #define SHUTDOWN_BOTH (2) mg_static_assert(MAX_WORKER_THREADS >= 1, "worker threads must be a positive number"); mg_static_assert(sizeof(size_t) == 4 || sizeof(size_t) == 8, "size_t data type size check"); #if defined(_WIN32) /* WINDOWS include block */ #include <winsock2.h> /* DTL add for SO_EXCLUSIVE */ #include <ws2tcpip.h> #include <windows.h> typedef const char *SOCK_OPT_TYPE; #if !defined(PATH_MAX) #define W_PATH_MAX (MAX_PATH) /* at most three UTF-8 chars per wchar_t */ #define PATH_MAX (W_PATH_MAX * 3) #else #define W_PATH_MAX ((PATH_MAX + 2) / 3) #endif mg_static_assert(PATH_MAX >= 1, "path length must be a positive number"); #if !defined(_IN_PORT_T) #if !defined(in_port_t) #define in_port_t u_short #endif #endif #if !defined(_WIN32_WCE) #include <process.h> #include <direct.h> #include <io.h> #else /* _WIN32_WCE */ #define NO_CGI /* WinCE has no pipes */ #define NO_POPEN /* WinCE has no popen */ typedef long off_t; #define errno ((int)(GetLastError())) #define strerror(x) (_ultoa(x, (char *)_alloca(sizeof(x) * 3), 10)) #endif /* _WIN32_WCE */ #define MAKEUQUAD(lo, hi) \ ((uint64_t)(((uint32_t)(lo)) | ((uint64_t)((uint32_t)(hi))) << 32)) #define RATE_DIFF (10000000) /* 100 nsecs */ #define EPOCH_DIFF (MAKEUQUAD(0xd53e8000, 0x019db1de)) #define SYS2UNIX_TIME(lo, hi) \ ((time_t)((MAKEUQUAD((lo), (hi)) - EPOCH_DIFF) / RATE_DIFF)) /* Visual Studio 6 does not know __func__ or __FUNCTION__ * The rest of MS compilers use __FUNCTION__, not C99 __func__ * Also use _strtoui64 on modern M$ compilers */ #if defined(_MSC_VER) #if (_MSC_VER < 1300) #define STRX(x) #x #define STR(x) STRX(x) #define __func__ __FILE__ ":" STR(__LINE__) #define strtoull(x, y, z) ((unsigned __int64)_atoi64(x)) #define strtoll(x, y, z) (_atoi64(x)) #else #define __func__ __FUNCTION__ #define strtoull(x, y, z) (_strtoui64(x, y, z)) #define strtoll(x, y, z) (_strtoi64(x, y, z)) #endif #endif /* _MSC_VER */ #define ERRNO ((int)(GetLastError())) #define NO_SOCKLEN_T #if defined(_WIN64) || defined(__MINGW64__) #if !defined(SSL_LIB) #define SSL_LIB "ssleay64.dll" #endif #if !defined(CRYPTO_LIB) #define CRYPTO_LIB "libeay64.dll" #endif #else #if !defined(SSL_LIB) #define SSL_LIB "ssleay32.dll" #endif #if !defined(CRYPTO_LIB) #define CRYPTO_LIB "libeay32.dll" #endif #endif #define O_NONBLOCK (0) #if !defined(W_OK) #define W_OK (2) /* http://msdn.microsoft.com/en-us/library/1w06ktdy.aspx */ #endif #if !defined(EWOULDBLOCK) #define EWOULDBLOCK WSAEWOULDBLOCK #endif /* !EWOULDBLOCK */ #define _POSIX_ #define INT64_FMT "I64d" #define UINT64_FMT "I64u" #define WINCDECL __cdecl #define vsnprintf_impl _vsnprintf #define access _access #define mg_sleep(x) (Sleep(x)) #define pipe(x) _pipe(x, MG_BUF_LEN, _O_BINARY) #if !defined(popen) #define popen(x, y) (_popen(x, y)) #endif #if !defined(pclose) #define pclose(x) (_pclose(x)) #endif #define close(x) (_close(x)) #define dlsym(x, y) (GetProcAddress((HINSTANCE)(x), (y))) #define RTLD_LAZY (0) #define fseeko(x, y, z) ((_lseeki64(_fileno(x), (y), (z)) == -1) ? -1 : 0) #define fdopen(x, y) (_fdopen((x), (y))) #define write(x, y, z) (_write((x), (y), (unsigned)z)) #define read(x, y, z) (_read((x), (y), (unsigned)z)) #define flockfile(x) (EnterCriticalSection(&global_log_file_lock)) #define funlockfile(x) (LeaveCriticalSection(&global_log_file_lock)) #define sleep(x) (Sleep((x)*1000)) #define rmdir(x) (_rmdir(x)) #if defined(_WIN64) || !defined(__MINGW32__) /* Only MinGW 32 bit is missing this function */ #define timegm(x) (_mkgmtime(x)) #else time_t timegm(struct tm *tm); #define NEED_TIMEGM #endif #if !defined(fileno) #define fileno(x) (_fileno(x)) #endif /* !fileno MINGW #defines fileno */ typedef HANDLE pthread_mutex_t; typedef DWORD pthread_key_t; typedef HANDLE pthread_t; typedef struct { CRITICAL_SECTION threadIdSec; struct mg_workerTLS *waiting_thread; /* The chain of threads */ } pthread_cond_t; #if !defined(__clockid_t_defined) typedef DWORD clockid_t; #endif #if !defined(CLOCK_MONOTONIC) #define CLOCK_MONOTONIC (1) #endif #if !defined(CLOCK_REALTIME) #define CLOCK_REALTIME (2) #endif #if !defined(CLOCK_THREAD) #define CLOCK_THREAD (3) #endif #if !defined(CLOCK_PROCESS) #define CLOCK_PROCESS (4) #endif #if defined(_MSC_VER) && (_MSC_VER >= 1900) #define _TIMESPEC_DEFINED #endif #if !defined(_TIMESPEC_DEFINED) struct timespec { time_t tv_sec; /* seconds */ long tv_nsec; /* nanoseconds */ }; #endif #if !defined(WIN_PTHREADS_TIME_H) #define MUST_IMPLEMENT_CLOCK_GETTIME #endif #if defined(MUST_IMPLEMENT_CLOCK_GETTIME) #define clock_gettime mg_clock_gettime static int clock_gettime(clockid_t clk_id, struct timespec *tp) { FILETIME ft; ULARGE_INTEGER li, li2; BOOL ok = FALSE; double d; static double perfcnt_per_sec = 0.0; static BOOL initialized = FALSE; if (!initialized) { QueryPerformanceFrequency((LARGE_INTEGER *)&li); perfcnt_per_sec = 1.0 / li.QuadPart; initialized = TRUE; } if (tp) { memset(tp, 0, sizeof(*tp)); if (clk_id == CLOCK_REALTIME) { /* BEGIN: CLOCK_REALTIME = wall clock (date and time) */ GetSystemTimeAsFileTime(&ft); li.LowPart = ft.dwLowDateTime; li.HighPart = ft.dwHighDateTime; li.QuadPart -= 116444736000000000; /* 1.1.1970 in filedate */ tp->tv_sec = (time_t)(li.QuadPart / 10000000); tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100; ok = TRUE; /* END: CLOCK_REALTIME */ } else if (clk_id == CLOCK_MONOTONIC) { /* BEGIN: CLOCK_MONOTONIC = stopwatch (time differences) */ QueryPerformanceCounter((LARGE_INTEGER *)&li); d = li.QuadPart * perfcnt_per_sec; tp->tv_sec = (time_t)d; d -= (double)tp->tv_sec; tp->tv_nsec = (long)(d * 1.0E9); ok = TRUE; /* END: CLOCK_MONOTONIC */ } else if (clk_id == CLOCK_THREAD) { /* BEGIN: CLOCK_THREAD = CPU usage of thread */ FILETIME t_create, t_exit, t_kernel, t_user; if (GetThreadTimes(GetCurrentThread(), &t_create, &t_exit, &t_kernel, &t_user)) { li.LowPart = t_user.dwLowDateTime; li.HighPart = t_user.dwHighDateTime; li2.LowPart = t_kernel.dwLowDateTime; li2.HighPart = t_kernel.dwHighDateTime; li.QuadPart += li2.QuadPart; tp->tv_sec = (time_t)(li.QuadPart / 10000000); tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100; ok = TRUE; } /* END: CLOCK_THREAD */ } else if (clk_id == CLOCK_PROCESS) { /* BEGIN: CLOCK_PROCESS = CPU usage of process */ FILETIME t_create, t_exit, t_kernel, t_user; if (GetProcessTimes(GetCurrentProcess(), &t_create, &t_exit, &t_kernel, &t_user)) { li.LowPart = t_user.dwLowDateTime; li.HighPart = t_user.dwHighDateTime; li2.LowPart = t_kernel.dwLowDateTime; li2.HighPart = t_kernel.dwHighDateTime; li.QuadPart += li2.QuadPart; tp->tv_sec = (time_t)(li.QuadPart / 10000000); tp->tv_nsec = (long)(li.QuadPart % 10000000) * 100; ok = TRUE; } /* END: CLOCK_PROCESS */ } else { /* BEGIN: unknown clock */ /* ok = FALSE; already set by init */ /* END: unknown clock */ } } return ok ? 0 : -1; } #endif #define pid_t HANDLE /* MINGW typedefs pid_t to int. Using #define here. */ static int pthread_mutex_lock(pthread_mutex_t *); static int pthread_mutex_unlock(pthread_mutex_t *); static void path_to_unicode(const struct mg_connection *conn, const char *path, wchar_t *wbuf, size_t wbuf_len); /* All file operations need to be rewritten to solve #246. */ struct mg_file; static const char * mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p); /* POSIX dirent interface */ struct dirent { char d_name[PATH_MAX]; }; typedef struct DIR { HANDLE handle; WIN32_FIND_DATAW info; struct dirent result; } DIR; #if defined(_WIN32) #if !defined(HAVE_POLL) struct pollfd { SOCKET fd; short events; short revents; }; #endif #endif /* Mark required libraries */ #if defined(_MSC_VER) #pragma comment(lib, "Ws2_32.lib") #endif #else /* defined(_WIN32) - WINDOWS vs UNIX include block */ #include <sys/wait.h> #include <sys/socket.h> #include <sys/poll.h> #include <netinet/in.h> #include <arpa/inet.h> #include <sys/time.h> #include <sys/utsname.h> #include <stdint.h> #include <inttypes.h> #include <netdb.h> #include <netinet/tcp.h> typedef const void *SOCK_OPT_TYPE; #if defined(ANDROID) typedef unsigned short int in_port_t; #endif #include <pwd.h> #include <unistd.h> #include <grp.h> #include <dirent.h> #define vsnprintf_impl vsnprintf #if !defined(NO_SSL_DL) && !defined(NO_SSL) #include <dlfcn.h> #endif #include <pthread.h> #if defined(__MACH__) #define SSL_LIB "libssl.dylib" #define CRYPTO_LIB "libcrypto.dylib" #else #if !defined(SSL_LIB) #define SSL_LIB "libssl.so" #endif #if !defined(CRYPTO_LIB) #define CRYPTO_LIB "libcrypto.so" #endif #endif #if !defined(O_BINARY) #define O_BINARY (0) #endif /* O_BINARY */ #define closesocket(a) (close(a)) #define mg_mkdir(conn, path, mode) (mkdir(path, mode)) #define mg_remove(conn, x) (remove(x)) #define mg_sleep(x) (usleep((x)*1000)) #define mg_opendir(conn, x) (opendir(x)) #define mg_closedir(x) (closedir(x)) #define mg_readdir(x) (readdir(x)) #define ERRNO (errno) #define INVALID_SOCKET (-1) #define INT64_FMT PRId64 #define UINT64_FMT PRIu64 typedef int SOCKET; #define WINCDECL #if defined(__hpux) /* HPUX 11 does not have monotonic, fall back to realtime */ #if !defined(CLOCK_MONOTONIC) #define CLOCK_MONOTONIC CLOCK_REALTIME #endif /* HPUX defines socklen_t incorrectly as size_t which is 64bit on * Itanium. Without defining _XOPEN_SOURCE or _XOPEN_SOURCE_EXTENDED * the prototypes use int* rather than socklen_t* which matches the * actual library expectation. When called with the wrong size arg * accept() returns a zero client inet addr and check_acl() always * fails. Since socklen_t is widely used below, just force replace * their typedef with int. - DTL */ #define socklen_t int #endif /* hpux */ #endif /* defined(_WIN32) - WINDOWS vs UNIX include block */ /* Maximum queue length for pending connections. This value is passed as * parameter to the "listen" socket call. */ #if !defined(SOMAXCONN) /* This symbol may be defined in winsock2.h so this must after that include */ #define SOMAXCONN (100) /* in pending connections (count) */ #endif /* In case our C library is missing "timegm", provide an implementation */ #if defined(NEED_TIMEGM) static inline int is_leap(int y) { return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0; } static inline int count_leap(int y) { return (y - 1969) / 4 - (y - 1901) / 100 + (y - 1601) / 400; } time_t timegm(struct tm *tm) { static const unsigned short ydays[] = { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365}; int year = tm->tm_year + 1900; int mon = tm->tm_mon; int mday = tm->tm_mday - 1; int hour = tm->tm_hour; int min = tm->tm_min; int sec = tm->tm_sec; if (year < 1970 || mon < 0 || mon > 11 || mday < 0 || (mday >= ydays[mon + 1] - ydays[mon] + (mon == 1 && is_leap(year) ? 1 : 0)) || hour < 0 || hour > 23 || min < 0 || min > 59 || sec < 0 || sec > 60) return -1; time_t res = year - 1970; res *= 365; res += mday; res += ydays[mon] + (mon > 1 && is_leap(year) ? 1 : 0); res += count_leap(year); res *= 24; res += hour; res *= 60; res += min; res *= 60; res += sec; return res; } #endif /* NEED_TIMEGM */ /* va_copy should always be a macro, C99 and C++11 - DTL */ #if !defined(va_copy) #define va_copy(x, y) ((x) = (y)) #endif #if defined(_WIN32) /* Create substitutes for POSIX functions in Win32. */ #if defined(__MINGW32__) /* Show no warning in case system functions are not used. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif static CRITICAL_SECTION global_log_file_lock; FUNCTION_MAY_BE_UNUSED static DWORD pthread_self(void) { return GetCurrentThreadId(); } FUNCTION_MAY_BE_UNUSED static int pthread_key_create( pthread_key_t *key, void (*_ignored)(void *) /* destructor not supported for Windows */ ) { (void)_ignored; if ((key != 0)) { *key = TlsAlloc(); return (*key != TLS_OUT_OF_INDEXES) ? 0 : -1; } return -2; } FUNCTION_MAY_BE_UNUSED static int pthread_key_delete(pthread_key_t key) { return TlsFree(key) ? 0 : 1; } FUNCTION_MAY_BE_UNUSED static int pthread_setspecific(pthread_key_t key, void *value) { return TlsSetValue(key, value) ? 0 : 1; } FUNCTION_MAY_BE_UNUSED static void * pthread_getspecific(pthread_key_t key) { return TlsGetValue(key); } #if defined(__MINGW32__) /* Enable unused function warning again */ #pragma GCC diagnostic pop #endif static struct pthread_mutex_undefined_struct *pthread_mutex_attr = NULL; #else static pthread_mutexattr_t pthread_mutex_attr; #endif /* _WIN32 */ #if defined(_WIN32_WCE) /* Create substitutes for POSIX functions in Win32. */ #if defined(__MINGW32__) /* Show no warning in case system functions are not used. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif FUNCTION_MAY_BE_UNUSED static time_t time(time_t *ptime) { time_t t; SYSTEMTIME st; FILETIME ft; GetSystemTime(&st); SystemTimeToFileTime(&st, &ft); t = SYS2UNIX_TIME(ft.dwLowDateTime, ft.dwHighDateTime); if (ptime != NULL) { *ptime = t; } return t; } FUNCTION_MAY_BE_UNUSED static struct tm * localtime_s(const time_t *ptime, struct tm *ptm) { int64_t t = ((int64_t)*ptime) * RATE_DIFF + EPOCH_DIFF; FILETIME ft, lft; SYSTEMTIME st; TIME_ZONE_INFORMATION tzinfo; if (ptm == NULL) { return NULL; } *(int64_t *)&ft = t; FileTimeToLocalFileTime(&ft, &lft); FileTimeToSystemTime(&lft, &st); ptm->tm_year = st.wYear - 1900; ptm->tm_mon = st.wMonth - 1; ptm->tm_wday = st.wDayOfWeek; ptm->tm_mday = st.wDay; ptm->tm_hour = st.wHour; ptm->tm_min = st.wMinute; ptm->tm_sec = st.wSecond; ptm->tm_yday = 0; /* hope nobody uses this */ ptm->tm_isdst = (GetTimeZoneInformation(&tzinfo) == TIME_ZONE_ID_DAYLIGHT) ? 1 : 0; return ptm; } FUNCTION_MAY_BE_UNUSED static struct tm * gmtime_s(const time_t *ptime, struct tm *ptm) { /* FIXME(lsm): fix this. */ return localtime_s(ptime, ptm); } static int mg_atomic_inc(volatile int *addr); static struct tm tm_array[MAX_WORKER_THREADS]; static int tm_index = 0; FUNCTION_MAY_BE_UNUSED static struct tm * localtime(const time_t *ptime) { int i = mg_atomic_inc(&tm_index) % (sizeof(tm_array) / sizeof(tm_array[0])); return localtime_s(ptime, tm_array + i); } FUNCTION_MAY_BE_UNUSED static struct tm * gmtime(const time_t *ptime) { int i = mg_atomic_inc(&tm_index) % ARRAY_SIZE(tm_array); return gmtime_s(ptime, tm_array + i); } FUNCTION_MAY_BE_UNUSED static size_t strftime(char *dst, size_t dst_size, const char *fmt, const struct tm *tm) { /* TODO: (void)mg_snprintf(NULL, dst, dst_size, "implement strftime() * for WinCE"); */ return 0; } #define _beginthreadex(psec, stack, func, prm, flags, ptid) \ (uintptr_t) CreateThread(psec, stack, func, prm, flags, ptid) #define remove(f) mg_remove(NULL, f) FUNCTION_MAY_BE_UNUSED static int rename(const char *a, const char *b) { wchar_t wa[W_PATH_MAX]; wchar_t wb[W_PATH_MAX]; path_to_unicode(NULL, a, wa, ARRAY_SIZE(wa)); path_to_unicode(NULL, b, wb, ARRAY_SIZE(wb)); return MoveFileW(wa, wb) ? 0 : -1; } struct stat { int64_t st_size; time_t st_mtime; }; FUNCTION_MAY_BE_UNUSED static int stat(const char *name, struct stat *st) { wchar_t wbuf[W_PATH_MAX]; WIN32_FILE_ATTRIBUTE_DATA attr; time_t creation_time, write_time; path_to_unicode(NULL, name, wbuf, ARRAY_SIZE(wbuf)); memset(&attr, 0, sizeof(attr)); GetFileAttributesExW(wbuf, GetFileExInfoStandard, &attr); st->st_size = (((int64_t)attr.nFileSizeHigh) << 32) + (int64_t)attr.nFileSizeLow; write_time = SYS2UNIX_TIME(attr.ftLastWriteTime.dwLowDateTime, attr.ftLastWriteTime.dwHighDateTime); creation_time = SYS2UNIX_TIME(attr.ftCreationTime.dwLowDateTime, attr.ftCreationTime.dwHighDateTime); if (creation_time > write_time) { st->st_mtime = creation_time; } else { st->st_mtime = write_time; } return 0; } #define access(x, a) 1 /* not required anyway */ /* WinCE-TODO: define stat, remove, rename, _rmdir, _lseeki64 */ /* Values from errno.h in Windows SDK (Visual Studio). */ #define EEXIST 17 #define EACCES 13 #define ENOENT 2 #if defined(__MINGW32__) /* Enable unused function warning again */ #pragma GCC diagnostic pop #endif #endif /* defined(_WIN32_WCE) */ #if defined(__GNUC__) || defined(__MINGW32__) /* Show no warning in case system functions are not used. */ #define GCC_VERSION \ (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) #if GCC_VERSION >= 40500 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif /* GCC_VERSION >= 40500 */ #endif /* defined(__GNUC__) || defined(__MINGW32__) */ #if defined(__clang__) /* Show no warning in case system functions are not used. */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif static pthread_mutex_t global_lock_mutex; #if defined(_WIN32) /* Forward declaration for Windows */ FUNCTION_MAY_BE_UNUSED static int pthread_mutex_lock(pthread_mutex_t *mutex); FUNCTION_MAY_BE_UNUSED static int pthread_mutex_unlock(pthread_mutex_t *mutex); #endif FUNCTION_MAY_BE_UNUSED static void mg_global_lock(void) { (void)pthread_mutex_lock(&global_lock_mutex); } FUNCTION_MAY_BE_UNUSED static void mg_global_unlock(void) { (void)pthread_mutex_unlock(&global_lock_mutex); } FUNCTION_MAY_BE_UNUSED static int mg_atomic_inc(volatile int *addr) { int ret; #if defined(_WIN32) && !defined(NO_ATOMICS) /* Depending on the SDK, this function uses either * (volatile unsigned int *) or (volatile LONG *), * so whatever you use, the other SDK is likely to raise a warning. */ ret = InterlockedIncrement((volatile long *)addr); #elif defined(__GNUC__) \ && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \ && !defined(NO_ATOMICS) ret = __sync_add_and_fetch(addr, 1); #else mg_global_lock(); ret = (++(*addr)); mg_global_unlock(); #endif return ret; } FUNCTION_MAY_BE_UNUSED static int mg_atomic_dec(volatile int *addr) { int ret; #if defined(_WIN32) && !defined(NO_ATOMICS) /* Depending on the SDK, this function uses either * (volatile unsigned int *) or (volatile LONG *), * so whatever you use, the other SDK is likely to raise a warning. */ ret = InterlockedDecrement((volatile long *)addr); #elif defined(__GNUC__) \ && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \ && !defined(NO_ATOMICS) ret = __sync_sub_and_fetch(addr, 1); #else mg_global_lock(); ret = (--(*addr)); mg_global_unlock(); #endif return ret; } #if defined(USE_SERVER_STATS) static int64_t mg_atomic_add(volatile int64_t *addr, int64_t value) { int64_t ret; #if defined(_WIN64) && !defined(NO_ATOMICS) ret = InterlockedAdd64(addr, value); #elif defined(__GNUC__) \ && ((__GNUC__ > 4) || ((__GNUC__ == 4) && (__GNUC_MINOR__ > 0))) \ && !defined(NO_ATOMICS) ret = __sync_add_and_fetch(addr, value); #else mg_global_lock(); *addr += value; ret = (*addr); mg_global_unlock(); #endif return ret; } #endif #if defined(__GNUC__) /* Show no warning in case system functions are not used. */ #if GCC_VERSION >= 40500 #pragma GCC diagnostic pop #endif /* GCC_VERSION >= 40500 */ #endif /* defined(__GNUC__) */ #if defined(__clang__) /* Show no warning in case system functions are not used. */ #pragma clang diagnostic pop #endif #if defined(USE_SERVER_STATS) struct mg_memory_stat { volatile int64_t totalMemUsed; volatile int64_t maxMemUsed; volatile int blockCount; }; static struct mg_memory_stat *get_memory_stat(struct mg_context *ctx); static void * mg_malloc_ex(size_t size, struct mg_context *ctx, const char *file, unsigned line) { void *data = malloc(size + 2 * sizeof(uintptr_t)); void *memory = 0; struct mg_memory_stat *mstat = get_memory_stat(ctx); #if defined(MEMORY_DEBUGGING) char mallocStr[256]; #else (void)file; (void)line; #endif if (data) { int64_t mmem = mg_atomic_add(&mstat->totalMemUsed, (int64_t)size); if (mmem > mstat->maxMemUsed) { /* could use atomic compare exchange, but this * seems overkill for statistics data */ mstat->maxMemUsed = mmem; } mg_atomic_inc(&mstat->blockCount); ((uintptr_t *)data)[0] = size; ((uintptr_t *)data)[1] = (uintptr_t)mstat; memory = (void *)(((char *)data) + 2 * sizeof(uintptr_t)); } #if defined(MEMORY_DEBUGGING) sprintf(mallocStr, "MEM: %p %5lu alloc %7lu %4lu --- %s:%u\n", memory, (unsigned long)size, (unsigned long)mstat->totalMemUsed, (unsigned long)mstat->blockCount, file, line); #if defined(_WIN32) OutputDebugStringA(mallocStr); #else DEBUG_TRACE("%s", mallocStr); #endif #endif return memory; } static void * mg_calloc_ex(size_t count, size_t size, struct mg_context *ctx, const char *file, unsigned line) { void *data = mg_malloc_ex(size * count, ctx, file, line); if (data) { memset(data, 0, size * count); } return data; } static void mg_free_ex(void *memory, const char *file, unsigned line) { void *data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t)); #if defined(MEMORY_DEBUGGING) char mallocStr[256]; #else (void)file; (void)line; #endif if (memory) { uintptr_t size = ((uintptr_t *)data)[0]; struct mg_memory_stat *mstat = (struct mg_memory_stat *)(((uintptr_t *)data)[1]); mg_atomic_add(&mstat->totalMemUsed, -(int64_t)size); mg_atomic_dec(&mstat->blockCount); #if defined(MEMORY_DEBUGGING) sprintf(mallocStr, "MEM: %p %5lu free %7lu %4lu --- %s:%u\n", memory, (unsigned long)size, (unsigned long)mstat->totalMemUsed, (unsigned long)mstat->blockCount, file, line); #if defined(_WIN32) OutputDebugStringA(mallocStr); #else DEBUG_TRACE("%s", mallocStr); #endif #endif free(data); } } static void * mg_realloc_ex(void *memory, size_t newsize, struct mg_context *ctx, const char *file, unsigned line) { void *data; void *_realloc; uintptr_t oldsize; #if defined(MEMORY_DEBUGGING) char mallocStr[256]; #else (void)file; (void)line; #endif if (newsize) { if (memory) { /* Reallocate existing block */ struct mg_memory_stat *mstat; data = (void *)(((char *)memory) - 2 * sizeof(uintptr_t)); oldsize = ((uintptr_t *)data)[0]; mstat = (struct mg_memory_stat *)((uintptr_t *)data)[1]; _realloc = realloc(data, newsize + 2 * sizeof(uintptr_t)); if (_realloc) { data = _realloc; mg_atomic_add(&mstat->totalMemUsed, -(int64_t)oldsize); #if defined(MEMORY_DEBUGGING) sprintf(mallocStr, "MEM: %p %5lu r-free %7lu %4lu --- %s:%u\n", memory, (unsigned long)oldsize, (unsigned long)mstat->totalMemUsed, (unsigned long)mstat->blockCount, file, line); #if defined(_WIN32) OutputDebugStringA(mallocStr); #else DEBUG_TRACE("%s", mallocStr); #endif #endif mg_atomic_add(&mstat->totalMemUsed, (int64_t)newsize); #if defined(MEMORY_DEBUGGING) sprintf(mallocStr, "MEM: %p %5lu r-alloc %7lu %4lu --- %s:%u\n", memory, (unsigned long)newsize, (unsigned long)mstat->totalMemUsed, (unsigned long)mstat->blockCount, file, line); #if defined(_WIN32) OutputDebugStringA(mallocStr); #else DEBUG_TRACE("%s", mallocStr); #endif #endif *(uintptr_t *)data = newsize; data = (void *)(((char *)data) + 2 * sizeof(uintptr_t)); } else { #if defined(MEMORY_DEBUGGING) #if defined(_WIN32) OutputDebugStringA("MEM: realloc failed\n"); #else DEBUG_TRACE("%s", "MEM: realloc failed\n"); #endif #endif return _realloc; } } else { /* Allocate new block */ data = mg_malloc_ex(newsize, ctx, file, line); } } else { /* Free existing block */ data = 0; mg_free_ex(memory, file, line); } return data; } #define mg_malloc(a) mg_malloc_ex(a, NULL, __FILE__, __LINE__) #define mg_calloc(a, b) mg_calloc_ex(a, b, NULL, __FILE__, __LINE__) #define mg_realloc(a, b) mg_realloc_ex(a, b, NULL, __FILE__, __LINE__) #define mg_free(a) mg_free_ex(a, __FILE__, __LINE__) #define mg_malloc_ctx(a, c) mg_malloc_ex(a, c, __FILE__, __LINE__) #define mg_calloc_ctx(a, b, c) mg_calloc_ex(a, b, c, __FILE__, __LINE__) #define mg_realloc_ctx(a, b, c) mg_realloc_ex(a, b, c, __FILE__, __LINE__) #else /* USE_SERVER_STATS */ static __inline void * mg_malloc(size_t a) { return malloc(a); } static __inline void * mg_calloc(size_t a, size_t b) { return calloc(a, b); } static __inline void * mg_realloc(void *a, size_t b) { return realloc(a, b); } static __inline void mg_free(void *a) { free(a); } #define mg_malloc_ctx(a, c) mg_malloc(a) #define mg_calloc_ctx(a, b, c) mg_calloc(a, b) #define mg_realloc_ctx(a, b, c) mg_realloc(a, b) #define mg_free_ctx(a, c) mg_free(a) #endif /* USE_SERVER_STATS */ static void mg_vsnprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt, va_list ap); static void mg_snprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(5, 6); /* This following lines are just meant as a reminder to use the mg-functions * for memory management */ #if defined(malloc) #undef malloc #endif #if defined(calloc) #undef calloc #endif #if defined(realloc) #undef realloc #endif #if defined(free) #undef free #endif #if defined(snprintf) #undef snprintf #endif #if defined(vsnprintf) #undef vsnprintf #endif #define malloc DO_NOT_USE_THIS_FUNCTION__USE_mg_malloc #define calloc DO_NOT_USE_THIS_FUNCTION__USE_mg_calloc #define realloc DO_NOT_USE_THIS_FUNCTION__USE_mg_realloc #define free DO_NOT_USE_THIS_FUNCTION__USE_mg_free #define snprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_snprintf #if defined(_WIN32) /* vsnprintf must not be used in any system, * but this define only works well for Windows. */ #define vsnprintf DO_NOT_USE_THIS_FUNCTION__USE_mg_vsnprintf #endif /* mg_init_library counter */ static int mg_init_library_called = 0; #if !defined(NO_SSL) static int mg_ssl_initialized = 0; #endif static pthread_key_t sTlsKey; /* Thread local storage index */ static int thread_idx_max = 0; #if defined(MG_LEGACY_INTERFACE) #define MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE #endif struct mg_workerTLS { int is_master; unsigned long thread_idx; #if defined(_WIN32) HANDLE pthread_cond_helper_mutex; struct mg_workerTLS *next_waiting_thread; #endif #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE) char txtbuf[4]; #endif }; #if defined(__GNUC__) || defined(__MINGW32__) /* Show no warning in case system functions are not used. */ #if GCC_VERSION >= 40500 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif /* GCC_VERSION >= 40500 */ #endif /* defined(__GNUC__) || defined(__MINGW32__) */ #if defined(__clang__) /* Show no warning in case system functions are not used. */ #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-function" #endif /* Get a unique thread ID as unsigned long, independent from the data type * of thread IDs defined by the operating system API. * If two calls to mg_current_thread_id return the same value, they calls * are done from the same thread. If they return different values, they are * done from different threads. (Provided this function is used in the same * process context and threads are not repeatedly created and deleted, but * CivetWeb does not do that). * This function must match the signature required for SSL id callbacks: * CRYPTO_set_id_callback */ FUNCTION_MAY_BE_UNUSED static unsigned long mg_current_thread_id(void) { #if defined(_WIN32) return GetCurrentThreadId(); #else #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" /* For every compiler, either "sizeof(pthread_t) > sizeof(unsigned long)" * or not, so one of the two conditions will be unreachable by construction. * Unfortunately the C standard does not define a way to check this at * compile time, since the #if preprocessor conditions can not use the sizeof * operator as an argument. */ #endif if (sizeof(pthread_t) > sizeof(unsigned long)) { /* This is the problematic case for CRYPTO_set_id_callback: * The OS pthread_t can not be cast to unsigned long. */ struct mg_workerTLS *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey); if (tls == NULL) { /* SSL called from an unknown thread: Create some thread index. */ tls = (struct mg_workerTLS *)mg_malloc(sizeof(struct mg_workerTLS)); tls->is_master = -2; /* -2 means "3rd party thread" */ tls->thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max); pthread_setspecific(sTlsKey, tls); } return tls->thread_idx; } else { /* pthread_t may be any data type, so a simple cast to unsigned long * can rise a warning/error, depending on the platform. * Here memcpy is used as an anything-to-anything cast. */ unsigned long ret = 0; pthread_t t = pthread_self(); memcpy(&ret, &t, sizeof(pthread_t)); return ret; } #if defined(__clang__) #pragma clang diagnostic pop #endif #endif } FUNCTION_MAY_BE_UNUSED static uint64_t mg_get_current_time_ns(void) { struct timespec tsnow; clock_gettime(CLOCK_REALTIME, &tsnow); return (((uint64_t)tsnow.tv_sec) * 1000000000) + (uint64_t)tsnow.tv_nsec; } #if defined(__GNUC__) /* Show no warning in case system functions are not used. */ #if GCC_VERSION >= 40500 #pragma GCC diagnostic pop #endif /* GCC_VERSION >= 40500 */ #endif /* defined(__GNUC__) */ #if defined(__clang__) /* Show no warning in case system functions are not used. */ #pragma clang diagnostic pop #endif #if defined(NEED_DEBUG_TRACE_FUNC) static void DEBUG_TRACE_FUNC(const char *func, unsigned line, const char *fmt, ...) { va_list args; uint64_t nsnow; static uint64_t nslast; struct timespec tsnow; /* Get some operating system independent thread id */ unsigned long thread_id = mg_current_thread_id(); clock_gettime(CLOCK_REALTIME, &tsnow); nsnow = ((uint64_t)tsnow.tv_sec) * ((uint64_t)1000000000) + ((uint64_t)tsnow.tv_nsec); if (!nslast) { nslast = nsnow; } flockfile(stdout); printf("*** %lu.%09lu %12" INT64_FMT " %lu %s:%u: ", (unsigned long)tsnow.tv_sec, (unsigned long)tsnow.tv_nsec, nsnow - nslast, thread_id, func, line); va_start(args, fmt); vprintf(fmt, args); va_end(args); putchar('\n'); fflush(stdout); funlockfile(stdout); nslast = nsnow; } #endif /* NEED_DEBUG_TRACE_FUNC */ #define MD5_STATIC static #include "md5.inl" /* Darwin prior to 7.0 and Win32 do not have socklen_t */ #if defined(NO_SOCKLEN_T) typedef int socklen_t; #endif /* NO_SOCKLEN_T */ #define IP_ADDR_STR_LEN (50) /* IPv6 hex string is 46 chars */ #if !defined(MSG_NOSIGNAL) #define MSG_NOSIGNAL (0) #endif #if defined(NO_SSL) typedef struct SSL SSL; /* dummy for SSL argument to push/pull */ typedef struct SSL_CTX SSL_CTX; #else #if defined(NO_SSL_DL) #include <openssl/ssl.h> #include <openssl/err.h> #include <openssl/crypto.h> #include <openssl/x509.h> #include <openssl/pem.h> #include <openssl/engine.h> #include <openssl/conf.h> #include <openssl/dh.h> #include <openssl/bn.h> #include <openssl/opensslv.h> #if defined(WOLFSSL_VERSION) /* Additional defines for WolfSSL, see * https://github.com/civetweb/civetweb/issues/583 */ #include "wolfssl_extras.inl" #endif #else /* SSL loaded dynamically from DLL. * I put the prototypes here to be independent from OpenSSL source * installation. */ typedef struct ssl_st SSL; typedef struct ssl_method_st SSL_METHOD; typedef struct ssl_ctx_st SSL_CTX; typedef struct x509_store_ctx_st X509_STORE_CTX; typedef struct x509_name X509_NAME; typedef struct asn1_integer ASN1_INTEGER; typedef struct bignum BIGNUM; typedef struct ossl_init_settings_st OPENSSL_INIT_SETTINGS; typedef struct evp_md EVP_MD; typedef struct x509 X509; #define SSL_CTRL_OPTIONS (32) #define SSL_CTRL_CLEAR_OPTIONS (77) #define SSL_CTRL_SET_ECDH_AUTO (94) #define OPENSSL_INIT_NO_LOAD_SSL_STRINGS 0x00100000L #define OPENSSL_INIT_LOAD_SSL_STRINGS 0x00200000L #define OPENSSL_INIT_LOAD_CRYPTO_STRINGS 0x00000002L #define SSL_VERIFY_NONE (0) #define SSL_VERIFY_PEER (1) #define SSL_VERIFY_FAIL_IF_NO_PEER_CERT (2) #define SSL_VERIFY_CLIENT_ONCE (4) #define SSL_OP_ALL ((long)(0x80000BFFUL)) #define SSL_OP_NO_SSLv2 (0x01000000L) #define SSL_OP_NO_SSLv3 (0x02000000L) #define SSL_OP_NO_TLSv1 (0x04000000L) #define SSL_OP_NO_TLSv1_2 (0x08000000L) #define SSL_OP_NO_TLSv1_1 (0x10000000L) #define SSL_OP_SINGLE_DH_USE (0x00100000L) #define SSL_OP_CIPHER_SERVER_PREFERENCE (0x00400000L) #define SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (0x00010000L) #define SSL_OP_NO_COMPRESSION (0x00020000L) #define SSL_CB_HANDSHAKE_START (0x10) #define SSL_CB_HANDSHAKE_DONE (0x20) #define SSL_ERROR_NONE (0) #define SSL_ERROR_SSL (1) #define SSL_ERROR_WANT_READ (2) #define SSL_ERROR_WANT_WRITE (3) #define SSL_ERROR_WANT_X509_LOOKUP (4) #define SSL_ERROR_SYSCALL (5) /* see errno */ #define SSL_ERROR_ZERO_RETURN (6) #define SSL_ERROR_WANT_CONNECT (7) #define SSL_ERROR_WANT_ACCEPT (8) #define TLSEXT_TYPE_server_name (0) #define TLSEXT_NAMETYPE_host_name (0) #define SSL_TLSEXT_ERR_OK (0) #define SSL_TLSEXT_ERR_ALERT_WARNING (1) #define SSL_TLSEXT_ERR_ALERT_FATAL (2) #define SSL_TLSEXT_ERR_NOACK (3) struct ssl_func { const char *name; /* SSL function name */ void (*ptr)(void); /* Function pointer */ }; #if defined(OPENSSL_API_1_1) #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr) #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr) #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr) #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr) #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr) #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr) #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr) #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr) #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr) #define TLS_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr) #define OPENSSL_init_ssl \ (*(int (*)(uint64_t opts, \ const OPENSSL_INIT_SETTINGS *settings))ssl_sw[10].ptr) #define SSL_CTX_use_PrivateKey_file \ (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr) #define SSL_CTX_use_certificate_file \ (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr) #define SSL_CTX_set_default_passwd_cb \ (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr) #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr) #define SSL_CTX_use_certificate_chain_file \ (*(int (*)(SSL_CTX *, const char *))ssl_sw[15].ptr) #define TLS_client_method (*(SSL_METHOD * (*)(void))ssl_sw[16].ptr) #define SSL_pending (*(int (*)(SSL *))ssl_sw[17].ptr) #define SSL_CTX_set_verify \ (*(void (*)(SSL_CTX *, \ int, \ int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[18].ptr) #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[19].ptr) #define SSL_CTX_load_verify_locations \ (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[20].ptr) #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[21].ptr) #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[22].ptr) #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[23].ptr) #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[24].ptr) #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[25].ptr) #define SSL_CIPHER_get_name \ (*(const char *(*)(const SSL_CIPHER *))ssl_sw[26].ptr) #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[27].ptr) #define SSL_CTX_set_session_id_context \ (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[28].ptr) #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[29].ptr) #define SSL_CTX_set_cipher_list \ (*(int (*)(SSL_CTX *, const char *))ssl_sw[30].ptr) #define SSL_CTX_set_options \ (*(unsigned long (*)(SSL_CTX *, unsigned long))ssl_sw[31].ptr) #define SSL_CTX_set_info_callback \ (*(void (*)(SSL_CTX * ctx, \ void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr) #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr) #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr) #define SSL_CTX_callback_ctrl \ (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr) #define SSL_get_servername \ (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr) #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr) #define SSL_CTX_clear_options(ctx, op) \ SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL) #define SSL_CTX_set_ecdh_auto(ctx, onoff) \ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL) #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53 #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54 #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \ SSL_CTX_callback_ctrl(ctx, \ SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \ (void (*)(void))cb) #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg) #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore) #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter) #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg)) #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0)) #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[0].ptr) #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[1].ptr) #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[2].ptr) #define CONF_modules_unload (*(void (*)(int))crypto_sw[3].ptr) #define X509_free (*(void (*)(X509 *))crypto_sw[4].ptr) #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[5].ptr) #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[6].ptr) #define X509_NAME_oneline \ (*(char *(*)(X509_NAME *, char *, int))crypto_sw[7].ptr) #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[8].ptr) #define EVP_get_digestbyname \ (*(const EVP_MD *(*)(const char *))crypto_sw[9].ptr) #define EVP_Digest \ (*(int (*)( \ const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \ crypto_sw[10].ptr) #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[11].ptr) #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[12].ptr) #define ASN1_INTEGER_to_BN \ (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[13].ptr) #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[14].ptr) #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[15].ptr) #define OPENSSL_free(a) CRYPTO_free(a) /* init_ssl_ctx() function updates this array. * It loads SSL library dynamically and changes NULLs to the actual addresses * of respective functions. The macros above (like SSL_connect()) are really * just calling these functions indirectly via the pointer. */ static struct ssl_func ssl_sw[] = {{"SSL_free", NULL}, {"SSL_accept", NULL}, {"SSL_connect", NULL}, {"SSL_read", NULL}, {"SSL_write", NULL}, {"SSL_get_error", NULL}, {"SSL_set_fd", NULL}, {"SSL_new", NULL}, {"SSL_CTX_new", NULL}, {"TLS_server_method", NULL}, {"OPENSSL_init_ssl", NULL}, {"SSL_CTX_use_PrivateKey_file", NULL}, {"SSL_CTX_use_certificate_file", NULL}, {"SSL_CTX_set_default_passwd_cb", NULL}, {"SSL_CTX_free", NULL}, {"SSL_CTX_use_certificate_chain_file", NULL}, {"TLS_client_method", NULL}, {"SSL_pending", NULL}, {"SSL_CTX_set_verify", NULL}, {"SSL_shutdown", NULL}, {"SSL_CTX_load_verify_locations", NULL}, {"SSL_CTX_set_default_verify_paths", NULL}, {"SSL_CTX_set_verify_depth", NULL}, {"SSL_get_peer_certificate", NULL}, {"SSL_get_version", NULL}, {"SSL_get_current_cipher", NULL}, {"SSL_CIPHER_get_name", NULL}, {"SSL_CTX_check_private_key", NULL}, {"SSL_CTX_set_session_id_context", NULL}, {"SSL_CTX_ctrl", NULL}, {"SSL_CTX_set_cipher_list", NULL}, {"SSL_CTX_set_options", NULL}, {"SSL_CTX_set_info_callback", NULL}, {"SSL_get_ex_data", NULL}, {"SSL_set_ex_data", NULL}, {"SSL_CTX_callback_ctrl", NULL}, {"SSL_get_servername", NULL}, {"SSL_set_SSL_CTX", NULL}, {NULL, NULL}}; /* Similar array as ssl_sw. These functions could be located in different * lib. */ static struct ssl_func crypto_sw[] = {{"ERR_get_error", NULL}, {"ERR_error_string", NULL}, {"ERR_remove_state", NULL}, {"CONF_modules_unload", NULL}, {"X509_free", NULL}, {"X509_get_subject_name", NULL}, {"X509_get_issuer_name", NULL}, {"X509_NAME_oneline", NULL}, {"X509_get_serialNumber", NULL}, {"EVP_get_digestbyname", NULL}, {"EVP_Digest", NULL}, {"i2d_X509", NULL}, {"BN_bn2hex", NULL}, {"ASN1_INTEGER_to_BN", NULL}, {"BN_free", NULL}, {"CRYPTO_free", NULL}, {NULL, NULL}}; #else #define SSL_free (*(void (*)(SSL *))ssl_sw[0].ptr) #define SSL_accept (*(int (*)(SSL *))ssl_sw[1].ptr) #define SSL_connect (*(int (*)(SSL *))ssl_sw[2].ptr) #define SSL_read (*(int (*)(SSL *, void *, int))ssl_sw[3].ptr) #define SSL_write (*(int (*)(SSL *, const void *, int))ssl_sw[4].ptr) #define SSL_get_error (*(int (*)(SSL *, int))ssl_sw[5].ptr) #define SSL_set_fd (*(int (*)(SSL *, SOCKET))ssl_sw[6].ptr) #define SSL_new (*(SSL * (*)(SSL_CTX *))ssl_sw[7].ptr) #define SSL_CTX_new (*(SSL_CTX * (*)(SSL_METHOD *))ssl_sw[8].ptr) #define SSLv23_server_method (*(SSL_METHOD * (*)(void))ssl_sw[9].ptr) #define SSL_library_init (*(int (*)(void))ssl_sw[10].ptr) #define SSL_CTX_use_PrivateKey_file \ (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[11].ptr) #define SSL_CTX_use_certificate_file \ (*(int (*)(SSL_CTX *, const char *, int))ssl_sw[12].ptr) #define SSL_CTX_set_default_passwd_cb \ (*(void (*)(SSL_CTX *, mg_callback_t))ssl_sw[13].ptr) #define SSL_CTX_free (*(void (*)(SSL_CTX *))ssl_sw[14].ptr) #define SSL_load_error_strings (*(void (*)(void))ssl_sw[15].ptr) #define SSL_CTX_use_certificate_chain_file \ (*(int (*)(SSL_CTX *, const char *))ssl_sw[16].ptr) #define SSLv23_client_method (*(SSL_METHOD * (*)(void))ssl_sw[17].ptr) #define SSL_pending (*(int (*)(SSL *))ssl_sw[18].ptr) #define SSL_CTX_set_verify \ (*(void (*)(SSL_CTX *, \ int, \ int (*verify_callback)(int, X509_STORE_CTX *)))ssl_sw[19].ptr) #define SSL_shutdown (*(int (*)(SSL *))ssl_sw[20].ptr) #define SSL_CTX_load_verify_locations \ (*(int (*)(SSL_CTX *, const char *, const char *))ssl_sw[21].ptr) #define SSL_CTX_set_default_verify_paths (*(int (*)(SSL_CTX *))ssl_sw[22].ptr) #define SSL_CTX_set_verify_depth (*(void (*)(SSL_CTX *, int))ssl_sw[23].ptr) #define SSL_get_peer_certificate (*(X509 * (*)(SSL *))ssl_sw[24].ptr) #define SSL_get_version (*(const char *(*)(SSL *))ssl_sw[25].ptr) #define SSL_get_current_cipher (*(SSL_CIPHER * (*)(SSL *))ssl_sw[26].ptr) #define SSL_CIPHER_get_name \ (*(const char *(*)(const SSL_CIPHER *))ssl_sw[27].ptr) #define SSL_CTX_check_private_key (*(int (*)(SSL_CTX *))ssl_sw[28].ptr) #define SSL_CTX_set_session_id_context \ (*(int (*)(SSL_CTX *, const unsigned char *, unsigned int))ssl_sw[29].ptr) #define SSL_CTX_ctrl (*(long (*)(SSL_CTX *, int, long, void *))ssl_sw[30].ptr) #define SSL_CTX_set_cipher_list \ (*(int (*)(SSL_CTX *, const char *))ssl_sw[31].ptr) #define SSL_CTX_set_info_callback \ (*(void (*)(SSL_CTX *, void (*callback)(SSL * s, int, int)))ssl_sw[32].ptr) #define SSL_get_ex_data (*(char *(*)(SSL *, int))ssl_sw[33].ptr) #define SSL_set_ex_data (*(void (*)(SSL *, int, char *))ssl_sw[34].ptr) #define SSL_CTX_callback_ctrl \ (*(long (*)(SSL_CTX *, int, void (*)(void)))ssl_sw[35].ptr) #define SSL_get_servername \ (*(const char *(*)(const SSL *, int type))ssl_sw[36].ptr) #define SSL_set_SSL_CTX (*(SSL_CTX * (*)(SSL *, SSL_CTX *))ssl_sw[37].ptr) #define SSL_CTX_set_options(ctx, op) \ SSL_CTX_ctrl((ctx), SSL_CTRL_OPTIONS, (op), NULL) #define SSL_CTX_clear_options(ctx, op) \ SSL_CTX_ctrl((ctx), SSL_CTRL_CLEAR_OPTIONS, (op), NULL) #define SSL_CTX_set_ecdh_auto(ctx, onoff) \ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_ECDH_AUTO, onoff, NULL) #define SSL_CTRL_SET_TLSEXT_SERVERNAME_CB 53 #define SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG 54 #define SSL_CTX_set_tlsext_servername_callback(ctx, cb) \ SSL_CTX_callback_ctrl(ctx, \ SSL_CTRL_SET_TLSEXT_SERVERNAME_CB, \ (void (*)(void))cb) #define SSL_CTX_set_tlsext_servername_arg(ctx, arg) \ SSL_CTX_ctrl(ctx, SSL_CTRL_SET_TLSEXT_SERVERNAME_ARG, 0, (void *)arg) #define X509_get_notBefore(x) ((x)->cert_info->validity->notBefore) #define X509_get_notAfter(x) ((x)->cert_info->validity->notAfter) #define SSL_set_app_data(s, arg) (SSL_set_ex_data(s, 0, (char *)arg)) #define SSL_get_app_data(s) (SSL_get_ex_data(s, 0)) #define CRYPTO_num_locks (*(int (*)(void))crypto_sw[0].ptr) #define CRYPTO_set_locking_callback \ (*(void (*)(void (*)(int, int, const char *, int)))crypto_sw[1].ptr) #define CRYPTO_set_id_callback \ (*(void (*)(unsigned long (*)(void)))crypto_sw[2].ptr) #define ERR_get_error (*(unsigned long (*)(void))crypto_sw[3].ptr) #define ERR_error_string (*(char *(*)(unsigned long, char *))crypto_sw[4].ptr) #define ERR_remove_state (*(void (*)(unsigned long))crypto_sw[5].ptr) #define ERR_free_strings (*(void (*)(void))crypto_sw[6].ptr) #define ENGINE_cleanup (*(void (*)(void))crypto_sw[7].ptr) #define CONF_modules_unload (*(void (*)(int))crypto_sw[8].ptr) #define CRYPTO_cleanup_all_ex_data (*(void (*)(void))crypto_sw[9].ptr) #define EVP_cleanup (*(void (*)(void))crypto_sw[10].ptr) #define X509_free (*(void (*)(X509 *))crypto_sw[11].ptr) #define X509_get_subject_name (*(X509_NAME * (*)(X509 *))crypto_sw[12].ptr) #define X509_get_issuer_name (*(X509_NAME * (*)(X509 *))crypto_sw[13].ptr) #define X509_NAME_oneline \ (*(char *(*)(X509_NAME *, char *, int))crypto_sw[14].ptr) #define X509_get_serialNumber (*(ASN1_INTEGER * (*)(X509 *))crypto_sw[15].ptr) #define i2c_ASN1_INTEGER \ (*(int (*)(ASN1_INTEGER *, unsigned char **))crypto_sw[16].ptr) #define EVP_get_digestbyname \ (*(const EVP_MD *(*)(const char *))crypto_sw[17].ptr) #define EVP_Digest \ (*(int (*)( \ const void *, size_t, void *, unsigned int *, const EVP_MD *, void *)) \ crypto_sw[18].ptr) #define i2d_X509 (*(int (*)(X509 *, unsigned char **))crypto_sw[19].ptr) #define BN_bn2hex (*(char *(*)(const BIGNUM *a))crypto_sw[20].ptr) #define ASN1_INTEGER_to_BN \ (*(BIGNUM * (*)(const ASN1_INTEGER *ai, BIGNUM *bn))crypto_sw[21].ptr) #define BN_free (*(void (*)(const BIGNUM *a))crypto_sw[22].ptr) #define CRYPTO_free (*(void (*)(void *addr))crypto_sw[23].ptr) #define OPENSSL_free(a) CRYPTO_free(a) /* init_ssl_ctx() function updates this array. * It loads SSL library dynamically and changes NULLs to the actual addresses * of respective functions. The macros above (like SSL_connect()) are really * just calling these functions indirectly via the pointer. */ static struct ssl_func ssl_sw[] = {{"SSL_free", NULL}, {"SSL_accept", NULL}, {"SSL_connect", NULL}, {"SSL_read", NULL}, {"SSL_write", NULL}, {"SSL_get_error", NULL}, {"SSL_set_fd", NULL}, {"SSL_new", NULL}, {"SSL_CTX_new", NULL}, {"SSLv23_server_method", NULL}, {"SSL_library_init", NULL}, {"SSL_CTX_use_PrivateKey_file", NULL}, {"SSL_CTX_use_certificate_file", NULL}, {"SSL_CTX_set_default_passwd_cb", NULL}, {"SSL_CTX_free", NULL}, {"SSL_load_error_strings", NULL}, {"SSL_CTX_use_certificate_chain_file", NULL}, {"SSLv23_client_method", NULL}, {"SSL_pending", NULL}, {"SSL_CTX_set_verify", NULL}, {"SSL_shutdown", NULL}, {"SSL_CTX_load_verify_locations", NULL}, {"SSL_CTX_set_default_verify_paths", NULL}, {"SSL_CTX_set_verify_depth", NULL}, {"SSL_get_peer_certificate", NULL}, {"SSL_get_version", NULL}, {"SSL_get_current_cipher", NULL}, {"SSL_CIPHER_get_name", NULL}, {"SSL_CTX_check_private_key", NULL}, {"SSL_CTX_set_session_id_context", NULL}, {"SSL_CTX_ctrl", NULL}, {"SSL_CTX_set_cipher_list", NULL}, {"SSL_CTX_set_info_callback", NULL}, {"SSL_get_ex_data", NULL}, {"SSL_set_ex_data", NULL}, {"SSL_CTX_callback_ctrl", NULL}, {"SSL_get_servername", NULL}, {"SSL_set_SSL_CTX", NULL}, {NULL, NULL}}; /* Similar array as ssl_sw. These functions could be located in different * lib. */ static struct ssl_func crypto_sw[] = {{"CRYPTO_num_locks", NULL}, {"CRYPTO_set_locking_callback", NULL}, {"CRYPTO_set_id_callback", NULL}, {"ERR_get_error", NULL}, {"ERR_error_string", NULL}, {"ERR_remove_state", NULL}, {"ERR_free_strings", NULL}, {"ENGINE_cleanup", NULL}, {"CONF_modules_unload", NULL}, {"CRYPTO_cleanup_all_ex_data", NULL}, {"EVP_cleanup", NULL}, {"X509_free", NULL}, {"X509_get_subject_name", NULL}, {"X509_get_issuer_name", NULL}, {"X509_NAME_oneline", NULL}, {"X509_get_serialNumber", NULL}, {"i2c_ASN1_INTEGER", NULL}, {"EVP_get_digestbyname", NULL}, {"EVP_Digest", NULL}, {"i2d_X509", NULL}, {"BN_bn2hex", NULL}, {"ASN1_INTEGER_to_BN", NULL}, {"BN_free", NULL}, {"CRYPTO_free", NULL}, {NULL, NULL}}; #endif /* OPENSSL_API_1_1 */ #endif /* NO_SSL_DL */ #endif /* NO_SSL */ #if !defined(NO_CACHING) static const char *month_names[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; #endif /* !NO_CACHING */ /* Unified socket address. For IPv6 support, add IPv6 address structure in * the * union u. */ union usa { struct sockaddr sa; struct sockaddr_in sin; #if defined(USE_IPV6) struct sockaddr_in6 sin6; #endif }; /* Describes a string (chunk of memory). */ struct vec { const char *ptr; size_t len; }; struct mg_file_stat { /* File properties filled by mg_stat: */ uint64_t size; time_t last_modified; int is_directory; /* Set to 1 if mg_stat is called for a directory */ int is_gzipped; /* Set to 1 if the content is gzipped, in which * case we need a "Content-Eencoding: gzip" header */ int location; /* 0 = nowhere, 1 = on disk, 2 = in memory */ }; struct mg_file_in_memory { char *p; uint32_t pos; char mode; }; struct mg_file_access { /* File properties filled by mg_fopen: */ FILE *fp; #if defined(MG_USE_OPEN_FILE) /* TODO (low): Remove obsolete "file in memory" implementation. * In an "early 2017" discussion at Google groups * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI * we decided to get rid of this feature (after some fade-out * phase). */ const char *membuf; #endif }; struct mg_file { struct mg_file_stat stat; struct mg_file_access access; }; #if defined(MG_USE_OPEN_FILE) #define STRUCT_FILE_INITIALIZER \ { \ { \ (uint64_t)0, (time_t)0, 0, 0, 0 \ } \ , \ { \ (FILE *) NULL, (const char *)NULL \ } \ } #else #define STRUCT_FILE_INITIALIZER \ { \ { \ (uint64_t)0, (time_t)0, 0, 0, 0 \ } \ , \ { \ (FILE *) NULL \ } \ } #endif /* Describes listening socket, or socket which was accept()-ed by the master * thread and queued for future handling by the worker thread. */ struct socket { SOCKET sock; /* Listening socket */ union usa lsa; /* Local socket address */ union usa rsa; /* Remote socket address */ unsigned char is_ssl; /* Is port SSL-ed */ unsigned char ssl_redir; /* Is port supposed to redirect everything to SSL * port */ unsigned char in_use; /* Is valid */ }; /* Enum const for all options must be in sync with * static struct mg_option config_options[] * This is tested in the unit test (test/private.c) * "Private Config Options" */ enum { LISTENING_PORTS, NUM_THREADS, RUN_AS_USER, CONFIG_TCP_NODELAY, /* Prepended CONFIG_ to avoid conflict with the * socket option typedef TCP_NODELAY. */ MAX_REQUEST_SIZE, LINGER_TIMEOUT, #if defined(__linux__) ALLOW_SENDFILE_CALL, #endif #if defined(_WIN32) CASE_SENSITIVE_FILES, #endif THROTTLE, ACCESS_LOG_FILE, ERROR_LOG_FILE, ENABLE_KEEP_ALIVE, REQUEST_TIMEOUT, KEEP_ALIVE_TIMEOUT, #if defined(USE_WEBSOCKET) WEBSOCKET_TIMEOUT, ENABLE_WEBSOCKET_PING_PONG, #endif DECODE_URL, #if defined(USE_LUA) LUA_BACKGROUND_SCRIPT, LUA_BACKGROUND_SCRIPT_PARAMS, #endif DOCUMENT_ROOT, CGI_EXTENSIONS, CGI_ENVIRONMENT, PUT_DELETE_PASSWORDS_FILE, CGI_INTERPRETER, PROTECT_URI, AUTHENTICATION_DOMAIN, ENABLE_AUTH_DOMAIN_CHECK, SSI_EXTENSIONS, ENABLE_DIRECTORY_LISTING, GLOBAL_PASSWORDS_FILE, INDEX_FILES, ACCESS_CONTROL_LIST, EXTRA_MIME_TYPES, SSL_CERTIFICATE, SSL_CERTIFICATE_CHAIN, URL_REWRITE_PATTERN, HIDE_FILES, SSL_DO_VERIFY_PEER, SSL_CA_PATH, SSL_CA_FILE, SSL_VERIFY_DEPTH, SSL_DEFAULT_VERIFY_PATHS, SSL_CIPHER_LIST, SSL_PROTOCOL_VERSION, SSL_SHORT_TRUST, #if defined(USE_LUA) LUA_PRELOAD_FILE, LUA_SCRIPT_EXTENSIONS, LUA_SERVER_PAGE_EXTENSIONS, #if defined(MG_EXPERIMENTAL_INTERFACES) LUA_DEBUG_PARAMS, #endif #endif #if defined(USE_DUKTAPE) DUKTAPE_SCRIPT_EXTENSIONS, #endif #if defined(USE_WEBSOCKET) WEBSOCKET_ROOT, #endif #if defined(USE_LUA) && defined(USE_WEBSOCKET) LUA_WEBSOCKET_EXTENSIONS, #endif ACCESS_CONTROL_ALLOW_ORIGIN, ACCESS_CONTROL_ALLOW_METHODS, ACCESS_CONTROL_ALLOW_HEADERS, ERROR_PAGES, #if !defined(NO_CACHING) STATIC_FILE_MAX_AGE, #endif #if !defined(NO_SSL) STRICT_HTTPS_MAX_AGE, #endif ADDITIONAL_HEADER, ALLOW_INDEX_SCRIPT_SUB_RES, NUM_OPTIONS }; /* Config option name, config types, default value. * Must be in the same order as the enum const above. */ static const struct mg_option config_options[] = { /* Once for each server */ {"listening_ports", MG_CONFIG_TYPE_STRING_LIST, "8080"}, {"num_threads", MG_CONFIG_TYPE_NUMBER, "50"}, {"run_as_user", MG_CONFIG_TYPE_STRING, NULL}, {"tcp_nodelay", MG_CONFIG_TYPE_NUMBER, "0"}, {"max_request_size", MG_CONFIG_TYPE_NUMBER, "16384"}, {"linger_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL}, #if defined(__linux__) {"allow_sendfile_call", MG_CONFIG_TYPE_BOOLEAN, "yes"}, #endif #if defined(_WIN32) {"case_sensitive", MG_CONFIG_TYPE_BOOLEAN, "no"}, #endif {"throttle", MG_CONFIG_TYPE_STRING_LIST, NULL}, {"access_log_file", MG_CONFIG_TYPE_FILE, NULL}, {"error_log_file", MG_CONFIG_TYPE_FILE, NULL}, {"enable_keep_alive", MG_CONFIG_TYPE_BOOLEAN, "no"}, {"request_timeout_ms", MG_CONFIG_TYPE_NUMBER, "30000"}, {"keep_alive_timeout_ms", MG_CONFIG_TYPE_NUMBER, "500"}, #if defined(USE_WEBSOCKET) {"websocket_timeout_ms", MG_CONFIG_TYPE_NUMBER, NULL}, {"enable_websocket_ping_pong", MG_CONFIG_TYPE_BOOLEAN, "no"}, #endif {"decode_url", MG_CONFIG_TYPE_BOOLEAN, "yes"}, #if defined(USE_LUA) {"lua_background_script", MG_CONFIG_TYPE_FILE, NULL}, {"lua_background_script_params", MG_CONFIG_TYPE_STRING_LIST, NULL}, #endif /* Once for each domain */ {"document_root", MG_CONFIG_TYPE_DIRECTORY, NULL}, {"cgi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.cgi$|**.pl$|**.php$"}, {"cgi_environment", MG_CONFIG_TYPE_STRING_LIST, NULL}, {"put_delete_auth_file", MG_CONFIG_TYPE_FILE, NULL}, {"cgi_interpreter", MG_CONFIG_TYPE_FILE, NULL}, {"protect_uri", MG_CONFIG_TYPE_STRING_LIST, NULL}, {"authentication_domain", MG_CONFIG_TYPE_STRING, "mydomain.com"}, {"enable_auth_domain_check", MG_CONFIG_TYPE_BOOLEAN, "yes"}, {"ssi_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.shtml$|**.shtm$"}, {"enable_directory_listing", MG_CONFIG_TYPE_BOOLEAN, "yes"}, {"global_auth_file", MG_CONFIG_TYPE_FILE, NULL}, {"index_files", MG_CONFIG_TYPE_STRING_LIST, #if defined(USE_LUA) "index.xhtml,index.html,index.htm," "index.lp,index.lsp,index.lua,index.cgi," "index.shtml,index.php"}, #else "index.xhtml,index.html,index.htm,index.cgi,index.shtml,index.php"}, #endif {"access_control_list", MG_CONFIG_TYPE_STRING_LIST, NULL}, {"extra_mime_types", MG_CONFIG_TYPE_STRING_LIST, NULL}, {"ssl_certificate", MG_CONFIG_TYPE_FILE, NULL}, {"ssl_certificate_chain", MG_CONFIG_TYPE_FILE, NULL}, {"url_rewrite_patterns", MG_CONFIG_TYPE_STRING_LIST, NULL}, {"hide_files_patterns", MG_CONFIG_TYPE_EXT_PATTERN, NULL}, {"ssl_verify_peer", MG_CONFIG_TYPE_YES_NO_OPTIONAL, "no"}, {"ssl_ca_path", MG_CONFIG_TYPE_DIRECTORY, NULL}, {"ssl_ca_file", MG_CONFIG_TYPE_FILE, NULL}, {"ssl_verify_depth", MG_CONFIG_TYPE_NUMBER, "9"}, {"ssl_default_verify_paths", MG_CONFIG_TYPE_BOOLEAN, "yes"}, {"ssl_cipher_list", MG_CONFIG_TYPE_STRING, NULL}, {"ssl_protocol_version", MG_CONFIG_TYPE_NUMBER, "0"}, {"ssl_short_trust", MG_CONFIG_TYPE_BOOLEAN, "no"}, #if defined(USE_LUA) {"lua_preload_file", MG_CONFIG_TYPE_FILE, NULL}, {"lua_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"}, {"lua_server_page_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lp$|**.lsp$"}, #if defined(MG_EXPERIMENTAL_INTERFACES) {"lua_debug", MG_CONFIG_TYPE_STRING, NULL}, #endif #endif #if defined(USE_DUKTAPE) /* The support for duktape is still in alpha version state. * The name of this config option might change. */ {"duktape_script_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.ssjs$"}, #endif #if defined(USE_WEBSOCKET) {"websocket_root", MG_CONFIG_TYPE_DIRECTORY, NULL}, #endif #if defined(USE_LUA) && defined(USE_WEBSOCKET) {"lua_websocket_pattern", MG_CONFIG_TYPE_EXT_PATTERN, "**.lua$"}, #endif {"access_control_allow_origin", MG_CONFIG_TYPE_STRING, "*"}, {"access_control_allow_methods", MG_CONFIG_TYPE_STRING, "*"}, {"access_control_allow_headers", MG_CONFIG_TYPE_STRING, "*"}, {"error_pages", MG_CONFIG_TYPE_DIRECTORY, NULL}, #if !defined(NO_CACHING) {"static_file_max_age", MG_CONFIG_TYPE_NUMBER, "3600"}, #endif #if !defined(NO_SSL) {"strict_transport_security_max_age", MG_CONFIG_TYPE_NUMBER, NULL}, #endif {"additional_header", MG_CONFIG_TYPE_STRING_MULTILINE, NULL}, {"allow_index_script_resource", MG_CONFIG_TYPE_BOOLEAN, "no"}, {NULL, MG_CONFIG_TYPE_UNKNOWN, NULL}}; /* Check if the config_options and the corresponding enum have compatible * sizes. */ mg_static_assert((sizeof(config_options) / sizeof(config_options[0])) == (NUM_OPTIONS + 1), "config_options and enum not sync"); enum { REQUEST_HANDLER, WEBSOCKET_HANDLER, AUTH_HANDLER }; struct mg_handler_info { /* Name/Pattern of the URI. */ char *uri; size_t uri_len; /* handler type */ int handler_type; /* Handler for http/https or authorization requests. */ mg_request_handler handler; unsigned int refcount; pthread_mutex_t refcount_mutex; /* Protects refcount */ pthread_cond_t refcount_cond; /* Signaled when handler refcount is decremented */ /* Handler for ws/wss (websocket) requests. */ mg_websocket_connect_handler connect_handler; mg_websocket_ready_handler ready_handler; mg_websocket_data_handler data_handler; mg_websocket_close_handler close_handler; /* accepted subprotocols for ws/wss requests. */ struct mg_websocket_subprotocols *subprotocols; /* Handler for authorization requests */ mg_authorization_handler auth_handler; /* User supplied argument for the handler function. */ void *cbdata; /* next handler in a linked list */ struct mg_handler_info *next; }; enum { CONTEXT_INVALID, CONTEXT_SERVER, CONTEXT_HTTP_CLIENT, CONTEXT_WS_CLIENT }; struct mg_domain_context { SSL_CTX *ssl_ctx; /* SSL context */ char *config[NUM_OPTIONS]; /* Civetweb configuration parameters */ struct mg_handler_info *handlers; /* linked list of uri handlers */ /* Server nonce */ uint64_t auth_nonce_mask; /* Mask for all nonce values */ unsigned long nonce_count; /* Used nonces, used for authentication */ #if defined(USE_LUA) && defined(USE_WEBSOCKET) /* linked list of shared lua websockets */ struct mg_shared_lua_websocket_list *shared_lua_websockets; #endif /* Linked list of domains */ struct mg_domain_context *next; }; struct mg_context { /* Part 1 - Physical context: * This holds threads, ports, timeouts, ... * set for the entire server, independent from the * addressed hostname. */ /* Connection related */ int context_type; /* See CONTEXT_* above */ struct socket *listening_sockets; struct pollfd *listening_socket_fds; unsigned int num_listening_sockets; struct mg_connection *worker_connections; /* The connection struct, pre- * allocated for each worker */ #if defined(USE_SERVER_STATS) int active_connections; int max_connections; int64_t total_connections; int64_t total_requests; int64_t total_data_read; int64_t total_data_written; #endif /* Thread related */ volatile int stop_flag; /* Should we stop event loop */ pthread_mutex_t thread_mutex; /* Protects (max|num)_threads */ pthread_t masterthreadid; /* The master thread ID */ unsigned int cfg_worker_threads; /* The number of configured worker threads. */ pthread_t *worker_threadids; /* The worker thread IDs */ /* Connection to thread dispatching */ #if defined(ALTERNATIVE_QUEUE) struct socket *client_socks; void **client_wait_events; #else struct socket queue[MGSQLEN]; /* Accepted sockets */ volatile int sq_head; /* Head of the socket queue */ volatile int sq_tail; /* Tail of the socket queue */ pthread_cond_t sq_full; /* Signaled when socket is produced */ pthread_cond_t sq_empty; /* Signaled when socket is consumed */ #endif /* Memory related */ unsigned int max_request_size; /* The max request size */ #if defined(USE_SERVER_STATS) struct mg_memory_stat ctx_memory; #endif /* Operating system related */ char *systemName; /* What operating system is running */ time_t start_time; /* Server start time, used for authentication * and for diagnstics. */ #if defined(USE_TIMERS) struct ttimers *timers; #endif /* Lua specific: Background operations and shared websockets */ #if defined(USE_LUA) void *lua_background_state; #endif /* Server nonce */ pthread_mutex_t nonce_mutex; /* Protects nonce_count */ /* Server callbacks */ struct mg_callbacks callbacks; /* User-defined callback function */ void *user_data; /* User-defined data */ /* Part 2 - Logical domain: * This holds hostname, TLS certificate, document root, ... * set for a domain hosted at the server. * There may be multiple domains hosted at one physical server. * The default domain "dd" is the first element of a list of * domains. */ struct mg_domain_context dd; /* default domain */ }; #if defined(USE_SERVER_STATS) static struct mg_memory_stat mg_common_memory = {0, 0, 0}; static struct mg_memory_stat * get_memory_stat(struct mg_context *ctx) { if (ctx) { return &(ctx->ctx_memory); } return &mg_common_memory; } #endif enum { CONNECTION_TYPE_INVALID, CONNECTION_TYPE_REQUEST, CONNECTION_TYPE_RESPONSE }; struct mg_connection { int connection_type; /* see CONNECTION_TYPE_* above */ struct mg_request_info request_info; struct mg_response_info response_info; struct mg_context *phys_ctx; struct mg_domain_context *dom_ctx; #if defined(USE_SERVER_STATS) int conn_state; /* 0 = undef, numerical value may change in different * versions. For the current definition, see * mg_get_connection_info_impl */ #endif const char *host; /* Host (HTTP/1.1 header or SNI) */ SSL *ssl; /* SSL descriptor */ SSL_CTX *client_ssl_ctx; /* SSL context for client connections */ struct socket client; /* Connected client */ time_t conn_birth_time; /* Time (wall clock) when connection was * established */ struct timespec req_time; /* Time (since system start) when the request * was received */ int64_t num_bytes_sent; /* Total bytes sent to client */ int64_t content_len; /* Content-Length header value */ int64_t consumed_content; /* How many bytes of content have been read */ int is_chunked; /* Transfer-Encoding is chunked: * 0 = not chunked, * 1 = chunked, do data read yet, * 2 = chunked, some data read, * 3 = chunked, all data read */ size_t chunk_remainder; /* Unread data from the last chunk */ char *buf; /* Buffer for received data */ char *path_info; /* PATH_INFO part of the URL */ int must_close; /* 1 if connection must be closed */ int accept_gzip; /* 1 if gzip encoding is accepted */ int in_error_handler; /* 1 if in handler for user defined error * pages */ #if defined(USE_WEBSOCKET) int in_websocket_handling; /* 1 if in read_websocket */ #endif int handled_requests; /* Number of requests handled by this connection */ int buf_size; /* Buffer size */ int request_len; /* Size of the request + headers in a buffer */ int data_len; /* Total size of data in a buffer */ int status_code; /* HTTP reply status code, e.g. 200 */ int throttle; /* Throttling, bytes/sec. <= 0 means no * throttle */ time_t last_throttle_time; /* Last time throttled data was sent */ int64_t last_throttle_bytes; /* Bytes sent this second */ pthread_mutex_t mutex; /* Used by mg_(un)lock_connection to ensure * atomic transmissions for websockets */ #if defined(USE_LUA) && defined(USE_WEBSOCKET) void *lua_websocket_state; /* Lua_State for a websocket connection */ #endif int thread_index; /* Thread index within ctx */ }; /* Directory entry */ struct de { struct mg_connection *conn; char *file_name; struct mg_file_stat file; }; #if defined(USE_WEBSOCKET) static int is_websocket_protocol(const struct mg_connection *conn); #else #define is_websocket_protocol(conn) (0) #endif #define mg_cry_internal(conn, fmt, ...) \ mg_cry_internal_wrap(conn, __func__, __LINE__, fmt, __VA_ARGS__) static void mg_cry_internal_wrap(const struct mg_connection *conn, const char *func, unsigned line, const char *fmt, ...) PRINTF_ARGS(4, 5); #if !defined(NO_THREAD_NAME) #if defined(_WIN32) && defined(_MSC_VER) /* Set the thread name for debugging purposes in Visual Studio * http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx */ #pragma pack(push, 8) typedef struct tagTHREADNAME_INFO { DWORD dwType; /* Must be 0x1000. */ LPCSTR szName; /* Pointer to name (in user addr space). */ DWORD dwThreadID; /* Thread ID (-1=caller thread). */ DWORD dwFlags; /* Reserved for future use, must be zero. */ } THREADNAME_INFO; #pragma pack(pop) #elif defined(__linux__) #include <sys/prctl.h> #include <sys/sendfile.h> #if defined(ALTERNATIVE_QUEUE) #include <sys/eventfd.h> #endif /* ALTERNATIVE_QUEUE */ #if defined(ALTERNATIVE_QUEUE) static void * event_create(void) { int evhdl = eventfd(0, EFD_CLOEXEC); int *ret; if (evhdl == -1) { /* Linux uses -1 on error, Windows NULL. */ /* However, Linux does not return 0 on success either. */ return 0; } ret = (int *)mg_malloc(sizeof(int)); if (ret) { *ret = evhdl; } else { (void)close(evhdl); } return (void *)ret; } static int event_wait(void *eventhdl) { uint64_t u; int evhdl, s; if (!eventhdl) { /* error */ return 0; } evhdl = *(int *)eventhdl; s = (int)read(evhdl, &u, sizeof(u)); if (s != sizeof(u)) { /* error */ return 0; } (void)u; /* the value is not required */ return 1; } static int event_signal(void *eventhdl) { uint64_t u = 1; int evhdl, s; if (!eventhdl) { /* error */ return 0; } evhdl = *(int *)eventhdl; s = (int)write(evhdl, &u, sizeof(u)); if (s != sizeof(u)) { /* error */ return 0; } return 1; } static void event_destroy(void *eventhdl) { int evhdl; if (!eventhdl) { /* error */ return; } evhdl = *(int *)eventhdl; close(evhdl); mg_free(eventhdl); } #endif #endif #if !defined(__linux__) && !defined(_WIN32) && defined(ALTERNATIVE_QUEUE) struct posix_event { pthread_mutex_t mutex; pthread_cond_t cond; }; static void * event_create(void) { struct posix_event *ret = mg_malloc(sizeof(struct posix_event)); if (ret == 0) { /* out of memory */ return 0; } if (0 != pthread_mutex_init(&(ret->mutex), NULL)) { /* pthread mutex not available */ mg_free(ret); return 0; } if (0 != pthread_cond_init(&(ret->cond), NULL)) { /* pthread cond not available */ pthread_mutex_destroy(&(ret->mutex)); mg_free(ret); return 0; } return (void *)ret; } static int event_wait(void *eventhdl) { struct posix_event *ev = (struct posix_event *)eventhdl; pthread_mutex_lock(&(ev->mutex)); pthread_cond_wait(&(ev->cond), &(ev->mutex)); pthread_mutex_unlock(&(ev->mutex)); return 1; } static int event_signal(void *eventhdl) { struct posix_event *ev = (struct posix_event *)eventhdl; pthread_mutex_lock(&(ev->mutex)); pthread_cond_signal(&(ev->cond)); pthread_mutex_unlock(&(ev->mutex)); return 1; } static void event_destroy(void *eventhdl) { struct posix_event *ev = (struct posix_event *)eventhdl; pthread_cond_destroy(&(ev->cond)); pthread_mutex_destroy(&(ev->mutex)); mg_free(ev); } #endif static void mg_set_thread_name(const char *name) { char threadName[16 + 1]; /* 16 = Max. thread length in Linux/OSX/.. */ mg_snprintf( NULL, NULL, threadName, sizeof(threadName), "civetweb-%s", name); #if defined(_WIN32) #if defined(_MSC_VER) /* Windows and Visual Studio Compiler */ __try { THREADNAME_INFO info; info.dwType = 0x1000; info.szName = threadName; info.dwThreadID = ~0U; info.dwFlags = 0; RaiseException(0x406D1388, 0, sizeof(info) / sizeof(ULONG_PTR), (ULONG_PTR *)&info); } __except(EXCEPTION_EXECUTE_HANDLER) { } #elif defined(__MINGW32__) /* No option known to set thread name for MinGW */ #endif #elif defined(_GNU_SOURCE) && defined(__GLIBC__) \ && ((__GLIBC__ > 2) || ((__GLIBC__ == 2) && (__GLIBC_MINOR__ >= 12))) /* pthread_setname_np first appeared in glibc in version 2.12*/ (void)pthread_setname_np(pthread_self(), threadName); #elif defined(__linux__) /* on linux we can use the old prctl function */ (void)prctl(PR_SET_NAME, threadName, 0, 0, 0); #endif } #else /* !defined(NO_THREAD_NAME) */ void mg_set_thread_name(const char *threadName) { } #endif #if defined(MG_LEGACY_INTERFACE) const char ** mg_get_valid_option_names(void) { /* This function is deprecated. Use mg_get_valid_options instead. */ static const char * data[2 * sizeof(config_options) / sizeof(config_options[0])] = {0}; int i; for (i = 0; config_options[i].name != NULL; i++) { data[i * 2] = config_options[i].name; data[i * 2 + 1] = config_options[i].default_value; } return data; } #endif const struct mg_option * mg_get_valid_options(void) { return config_options; } /* Do not open file (used in is_file_in_memory) */ #define MG_FOPEN_MODE_NONE (0) /* Open file for read only access */ #define MG_FOPEN_MODE_READ (1) /* Open file for writing, create and overwrite */ #define MG_FOPEN_MODE_WRITE (2) /* Open file for writing, create and append */ #define MG_FOPEN_MODE_APPEND (4) /* If a file is in memory, set all "stat" members and the membuf pointer of * output filep and return 1, otherwise return 0 and don't modify anything. */ static int open_file_in_memory(const struct mg_connection *conn, const char *path, struct mg_file *filep, int mode) { #if defined(MG_USE_OPEN_FILE) size_t size = 0; const char *buf = NULL; if (!conn) { return 0; } if ((mode != MG_FOPEN_MODE_NONE) && (mode != MG_FOPEN_MODE_READ)) { return 0; } if (conn->phys_ctx->callbacks.open_file) { buf = conn->phys_ctx->callbacks.open_file(conn, path, &size); if (buf != NULL) { if (filep == NULL) { /* This is a file in memory, but we cannot store the * properties * now. * Called from "is_file_in_memory" function. */ return 1; } /* NOTE: override filep->size only on success. Otherwise, it * might * break constructs like if (!mg_stat() || !mg_fopen()) ... */ filep->access.membuf = buf; filep->access.fp = NULL; /* Size was set by the callback */ filep->stat.size = size; /* Assume the data may change during runtime by setting * last_modified = now */ filep->stat.last_modified = time(NULL); filep->stat.is_directory = 0; filep->stat.is_gzipped = 0; } } return (buf != NULL); #else (void)conn; (void)path; (void)filep; (void)mode; return 0; #endif } static int is_file_in_memory(const struct mg_connection *conn, const char *path) { return open_file_in_memory(conn, path, NULL, MG_FOPEN_MODE_NONE); } static int is_file_opened(const struct mg_file_access *fileacc) { if (!fileacc) { return 0; } #if defined(MG_USE_OPEN_FILE) return (fileacc->membuf != NULL) || (fileacc->fp != NULL); #else return (fileacc->fp != NULL); #endif } static int mg_stat(const struct mg_connection *conn, const char *path, struct mg_file_stat *filep); /* mg_fopen will open a file either in memory or on the disk. * The input parameter path is a string in UTF-8 encoding. * The input parameter mode is MG_FOPEN_MODE_* * On success, either fp or membuf will be set in the output * struct file. All status members will also be set. * The function returns 1 on success, 0 on error. */ static int mg_fopen(const struct mg_connection *conn, const char *path, int mode, struct mg_file *filep) { int found; if (!filep) { return 0; } filep->access.fp = NULL; #if defined(MG_USE_OPEN_FILE) filep->access.membuf = NULL; #endif if (!is_file_in_memory(conn, path)) { /* filep is initialized in mg_stat: all fields with memset to, * some fields like size and modification date with values */ found = mg_stat(conn, path, &(filep->stat)); if ((mode == MG_FOPEN_MODE_READ) && (!found)) { /* file does not exist and will not be created */ return 0; } #if defined(_WIN32) { wchar_t wbuf[W_PATH_MAX]; path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf)); switch (mode) { case MG_FOPEN_MODE_READ: filep->access.fp = _wfopen(wbuf, L"rb"); break; case MG_FOPEN_MODE_WRITE: filep->access.fp = _wfopen(wbuf, L"wb"); break; case MG_FOPEN_MODE_APPEND: filep->access.fp = _wfopen(wbuf, L"ab"); break; } } #else /* Linux et al already use unicode. No need to convert. */ switch (mode) { case MG_FOPEN_MODE_READ: filep->access.fp = fopen(path, "r"); break; case MG_FOPEN_MODE_WRITE: filep->access.fp = fopen(path, "w"); break; case MG_FOPEN_MODE_APPEND: filep->access.fp = fopen(path, "a"); break; } #endif if (!found) { /* File did not exist before fopen was called. * Maybe it has been created now. Get stat info * like creation time now. */ found = mg_stat(conn, path, &(filep->stat)); (void)found; } /* file is on disk */ return (filep->access.fp != NULL); } else { #if defined(MG_USE_OPEN_FILE) /* is_file_in_memory returned true */ if (open_file_in_memory(conn, path, filep, mode)) { /* file is in memory */ return (filep->access.membuf != NULL); } #endif } /* Open failed */ return 0; } /* return 0 on success, just like fclose */ static int mg_fclose(struct mg_file_access *fileacc) { int ret = -1; if (fileacc != NULL) { if (fileacc->fp != NULL) { ret = fclose(fileacc->fp); #if defined(MG_USE_OPEN_FILE) } else if (fileacc->membuf != NULL) { ret = 0; #endif } /* reset all members of fileacc */ memset(fileacc, 0, sizeof(*fileacc)); } return ret; } static void mg_strlcpy(register char *dst, register const char *src, size_t n) { for (; *src != '\0' && n > 1; n--) { *dst++ = *src++; } *dst = '\0'; } static int lowercase(const char *s) { return tolower(*(const unsigned char *)s); } int mg_strncasecmp(const char *s1, const char *s2, size_t len) { int diff = 0; if (len > 0) { do { diff = lowercase(s1++) - lowercase(s2++); } while (diff == 0 && s1[-1] != '\0' && --len > 0); } return diff; } int mg_strcasecmp(const char *s1, const char *s2) { int diff; do { diff = lowercase(s1++) - lowercase(s2++); } while (diff == 0 && s1[-1] != '\0'); return diff; } static char * mg_strndup_ctx(const char *ptr, size_t len, struct mg_context *ctx) { char *p; (void)ctx; /* Avoid Visual Studio warning if USE_SERVER_STATS is not * defined */ if ((p = (char *)mg_malloc_ctx(len + 1, ctx)) != NULL) { mg_strlcpy(p, ptr, len + 1); } return p; } static char * mg_strdup_ctx(const char *str, struct mg_context *ctx) { return mg_strndup_ctx(str, strlen(str), ctx); } static char * mg_strdup(const char *str) { return mg_strndup_ctx(str, strlen(str), NULL); } static const char * mg_strcasestr(const char *big_str, const char *small_str) { size_t i, big_len = strlen(big_str), small_len = strlen(small_str); if (big_len >= small_len) { for (i = 0; i <= (big_len - small_len); i++) { if (mg_strncasecmp(big_str + i, small_str, small_len) == 0) { return big_str + i; } } } return NULL; } /* Return null terminated string of given maximum length. * Report errors if length is exceeded. */ static void mg_vsnprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt, va_list ap) { int n, ok; if (buflen == 0) { if (truncated) { *truncated = 1; } return; } #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" /* Using fmt as a non-literal is intended here, since it is mostly called * indirectly by mg_snprintf */ #endif n = (int)vsnprintf_impl(buf, buflen, fmt, ap); ok = (n >= 0) && ((size_t)n < buflen); #if defined(__clang__) #pragma clang diagnostic pop #endif if (ok) { if (truncated) { *truncated = 0; } } else { if (truncated) { *truncated = 1; } mg_cry_internal(conn, "truncating vsnprintf buffer: [%.*s]", (int)((buflen > 200) ? 200 : (buflen - 1)), buf); n = (int)buflen - 1; } buf[n] = '\0'; } static void mg_snprintf(const struct mg_connection *conn, int *truncated, char *buf, size_t buflen, const char *fmt, ...) { va_list ap; va_start(ap, fmt); mg_vsnprintf(conn, truncated, buf, buflen, fmt, ap); va_end(ap); } static int get_option_index(const char *name) { int i; for (i = 0; config_options[i].name != NULL; i++) { if (strcmp(config_options[i].name, name) == 0) { return i; } } return -1; } const char * mg_get_option(const struct mg_context *ctx, const char *name) { int i; if ((i = get_option_index(name)) == -1) { return NULL; } else if (!ctx || ctx->dd.config[i] == NULL) { return ""; } else { return ctx->dd.config[i]; } } #define mg_get_option DO_NOT_USE_THIS_FUNCTION_INTERNALLY__access_directly struct mg_context * mg_get_context(const struct mg_connection *conn) { return (conn == NULL) ? (struct mg_context *)NULL : (conn->phys_ctx); } void * mg_get_user_data(const struct mg_context *ctx) { return (ctx == NULL) ? NULL : ctx->user_data; } void mg_set_user_connection_data(struct mg_connection *conn, void *data) { if (conn != NULL) { conn->request_info.conn_data = data; } } void * mg_get_user_connection_data(const struct mg_connection *conn) { if (conn != NULL) { return conn->request_info.conn_data; } return NULL; } #if defined(MG_LEGACY_INTERFACE) /* Deprecated: Use mg_get_server_ports instead. */ size_t mg_get_ports(const struct mg_context *ctx, size_t size, int *ports, int *ssl) { size_t i; if (!ctx) { return 0; } for (i = 0; i < size && i < ctx->num_listening_sockets; i++) { ssl[i] = ctx->listening_sockets[i].is_ssl; ports[i] = #if defined(USE_IPV6) (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port) : #endif ntohs(ctx->listening_sockets[i].lsa.sin.sin_port); } return i; } #endif int mg_get_server_ports(const struct mg_context *ctx, int size, struct mg_server_ports *ports) { int i, cnt = 0; if (size <= 0) { return -1; } memset(ports, 0, sizeof(*ports) * (size_t)size); if (!ctx) { return -1; } if (!ctx->listening_sockets) { return -1; } for (i = 0; (i < size) && (i < (int)ctx->num_listening_sockets); i++) { ports[cnt].port = #if defined(USE_IPV6) (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) ? ntohs(ctx->listening_sockets[i].lsa.sin6.sin6_port) : #endif ntohs(ctx->listening_sockets[i].lsa.sin.sin_port); ports[cnt].is_ssl = ctx->listening_sockets[i].is_ssl; ports[cnt].is_redirect = ctx->listening_sockets[i].ssl_redir; if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET) { /* IPv4 */ ports[cnt].protocol = 1; cnt++; } else if (ctx->listening_sockets[i].lsa.sa.sa_family == AF_INET6) { /* IPv6 */ ports[cnt].protocol = 3; cnt++; } } return cnt; } static void sockaddr_to_string(char *buf, size_t len, const union usa *usa) { buf[0] = '\0'; if (!usa) { return; } if (usa->sa.sa_family == AF_INET) { getnameinfo(&usa->sa, sizeof(usa->sin), buf, (unsigned)len, NULL, 0, NI_NUMERICHOST); } #if defined(USE_IPV6) else if (usa->sa.sa_family == AF_INET6) { getnameinfo(&usa->sa, sizeof(usa->sin6), buf, (unsigned)len, NULL, 0, NI_NUMERICHOST); } #endif } /* Convert time_t to a string. According to RFC2616, Sec 14.18, this must be * included in all responses other than 100, 101, 5xx. */ static void gmt_time_string(char *buf, size_t buf_len, time_t *t) { #if !defined(REENTRANT_TIME) struct tm *tm; tm = ((t != NULL) ? gmtime(t) : NULL); if (tm != NULL) { #else struct tm _tm; struct tm *tm = &_tm; if (t != NULL) { gmtime_r(t, tm); #endif strftime(buf, buf_len, "%a, %d %b %Y %H:%M:%S GMT", tm); } else { mg_strlcpy(buf, "Thu, 01 Jan 1970 00:00:00 GMT", buf_len); buf[buf_len - 1] = '\0'; } } /* difftime for struct timespec. Return value is in seconds. */ static double mg_difftimespec(const struct timespec *ts_now, const struct timespec *ts_before) { return (double)(ts_now->tv_nsec - ts_before->tv_nsec) * 1.0E-9 + (double)(ts_now->tv_sec - ts_before->tv_sec); } #if defined(MG_EXTERNAL_FUNCTION_mg_cry_internal_impl) static void mg_cry_internal_impl(const struct mg_connection *conn, const char *func, unsigned line, const char *fmt, va_list ap); #include "external_mg_cry_internal_impl.inl" #else /* Print error message to the opened error log stream. */ static void mg_cry_internal_impl(const struct mg_connection *conn, const char *func, unsigned line, const char *fmt, va_list ap) { char buf[MG_BUF_LEN], src_addr[IP_ADDR_STR_LEN]; struct mg_file fi; time_t timestamp; /* Unused, in the RELEASE build */ (void)func; (void)line; #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif IGNORE_UNUSED_RESULT(vsnprintf_impl(buf, sizeof(buf), fmt, ap)); #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic pop #endif buf[sizeof(buf) - 1] = 0; DEBUG_TRACE("mg_cry called from %s:%u: %s", func, line, buf); if (!conn) { puts(buf); return; } /* Do not lock when getting the callback value, here and below. * I suppose this is fine, since function cannot disappear in the * same way string option can. */ if ((conn->phys_ctx->callbacks.log_message == NULL) || (conn->phys_ctx->callbacks.log_message(conn, buf) == 0)) { if (conn->dom_ctx->config[ERROR_LOG_FILE] != NULL) { if (mg_fopen(conn, conn->dom_ctx->config[ERROR_LOG_FILE], MG_FOPEN_MODE_APPEND, &fi) == 0) { fi.access.fp = NULL; } } else { fi.access.fp = NULL; } if (fi.access.fp != NULL) { flockfile(fi.access.fp); timestamp = time(NULL); sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); fprintf(fi.access.fp, "[%010lu] [error] [client %s] ", (unsigned long)timestamp, src_addr); if (conn->request_info.request_method != NULL) { fprintf(fi.access.fp, "%s %s: ", conn->request_info.request_method, conn->request_info.request_uri ? conn->request_info.request_uri : ""); } fprintf(fi.access.fp, "%s", buf); fputc('\n', fi.access.fp); fflush(fi.access.fp); funlockfile(fi.access.fp); (void)mg_fclose(&fi.access); /* Ignore errors. We can't call * mg_cry here anyway ;-) */ } } } #endif /* Externally provided function */ static void mg_cry_internal_wrap(const struct mg_connection *conn, const char *func, unsigned line, const char *fmt, ...) { va_list ap; va_start(ap, fmt); mg_cry_internal_impl(conn, func, line, fmt, ap); va_end(ap); } void mg_cry(const struct mg_connection *conn, const char *fmt, ...) { va_list ap; va_start(ap, fmt); mg_cry_internal_impl(conn, "user", 0, fmt, ap); va_end(ap); } #define mg_cry DO_NOT_USE_THIS_FUNCTION__USE_mg_cry_internal /* Return fake connection structure. Used for logging, if connection * is not applicable at the moment of logging. */ static struct mg_connection * fc(struct mg_context *ctx) { static struct mg_connection fake_connection; fake_connection.phys_ctx = ctx; fake_connection.dom_ctx = &(ctx->dd); return &fake_connection; } const char * mg_version(void) { return CIVETWEB_VERSION; } const struct mg_request_info * mg_get_request_info(const struct mg_connection *conn) { if (!conn) { return NULL; } #if defined(MG_ALLOW_USING_GET_REQUEST_INFO_FOR_RESPONSE) if (conn->connection_type == CONNECTION_TYPE_RESPONSE) { char txt[16]; struct mg_workerTLS *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey); sprintf(txt, "%03i", conn->response_info.status_code); if (strlen(txt) == 3) { memcpy(tls->txtbuf, txt, 4); } else { strcpy(tls->txtbuf, "ERR"); } ((struct mg_connection *)conn)->request_info.local_uri = ((struct mg_connection *)conn)->request_info.request_uri = tls->txtbuf; /* use thread safe buffer */ ((struct mg_connection *)conn)->request_info.num_headers = conn->response_info.num_headers; memcpy(((struct mg_connection *)conn)->request_info.http_headers, conn->response_info.http_headers, sizeof(conn->response_info.http_headers)); } else #endif if (conn->connection_type != CONNECTION_TYPE_REQUEST) { return NULL; } return &conn->request_info; } const struct mg_response_info * mg_get_response_info(const struct mg_connection *conn) { if (!conn) { return NULL; } if (conn->connection_type != CONNECTION_TYPE_RESPONSE) { return NULL; } return &conn->response_info; } static const char * get_proto_name(const struct mg_connection *conn) { #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunreachable-code" /* Depending on USE_WEBSOCKET and NO_SSL, some oft the protocols might be * not supported. Clang raises an "unreachable code" warning for parts of ?: * unreachable, but splitting into four different #ifdef clauses here is more * complicated. */ #endif const struct mg_request_info *ri = &conn->request_info; const char *proto = (is_websocket_protocol(conn) ? (ri->is_ssl ? "wss" : "ws") : (ri->is_ssl ? "https" : "http")); return proto; #if defined(__clang__) #pragma clang diagnostic pop #endif } int mg_get_request_link(const struct mg_connection *conn, char *buf, size_t buflen) { if ((buflen < 1) || (buf == 0) || (conn == 0)) { return -1; } else { int truncated = 0; const struct mg_request_info *ri = &conn->request_info; const char *proto = get_proto_name(conn); if (ri->local_uri == NULL) { return -1; } if ((ri->request_uri != NULL) && (0 != strcmp(ri->local_uri, ri->request_uri))) { /* The request uri is different from the local uri. * This is usually if an absolute URI, including server * name has been provided. */ mg_snprintf(conn, &truncated, buf, buflen, "%s://%s", proto, ri->request_uri); if (truncated) { return -1; } return 0; } else { /* The common case is a relative URI, so we have to * construct an absolute URI from server name and port */ #if defined(USE_IPV6) int is_ipv6 = (conn->client.lsa.sa.sa_family == AF_INET6); int port = is_ipv6 ? htons(conn->client.lsa.sin6.sin6_port) : htons(conn->client.lsa.sin.sin_port); #else int port = htons(conn->client.lsa.sin.sin_port); #endif int def_port = ri->is_ssl ? 443 : 80; int auth_domain_check_enabled = conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK] && (!mg_strcasecmp( conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes")); const char *server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN]; char portstr[16]; char server_ip[48]; if (port != def_port) { sprintf(portstr, ":%u", (unsigned)port); } else { portstr[0] = 0; } if (!auth_domain_check_enabled || !server_domain) { sockaddr_to_string(server_ip, sizeof(server_ip), &conn->client.lsa); server_domain = server_ip; } mg_snprintf(conn, &truncated, buf, buflen, "%s://%s%s%s", proto, server_domain, portstr, ri->local_uri); if (truncated) { return -1; } return 0; } } } /* Skip the characters until one of the delimiters characters found. * 0-terminate resulting word. Skip the delimiter and following whitespaces. * Advance pointer to buffer to the next word. Return found 0-terminated * word. * Delimiters can be quoted with quotechar. */ static char * skip_quoted(char **buf, const char *delimiters, const char *whitespace, char quotechar) { char *p, *begin_word, *end_word, *end_whitespace; begin_word = *buf; end_word = begin_word + strcspn(begin_word, delimiters); /* Check for quotechar */ if (end_word > begin_word) { p = end_word - 1; while (*p == quotechar) { /* While the delimiter is quoted, look for the next delimiter. */ /* This happens, e.g., in calls from parse_auth_header, * if the user name contains a " character. */ /* If there is anything beyond end_word, copy it. */ if (*end_word != '\0') { size_t end_off = strcspn(end_word + 1, delimiters); memmove(p, end_word, end_off + 1); p += end_off; /* p must correspond to end_word - 1 */ end_word += end_off + 1; } else { *p = '\0'; break; } } for (p++; p < end_word; p++) { *p = '\0'; } } if (*end_word == '\0') { *buf = end_word; } else { #if defined(__GNUC__) || defined(__MINGW32__) /* Disable spurious conversion warning for GCC */ #if GCC_VERSION >= 40500 #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wsign-conversion" #endif /* GCC_VERSION >= 40500 */ #endif /* defined(__GNUC__) || defined(__MINGW32__) */ end_whitespace = end_word + strspn(&end_word[1], whitespace) + 1; #if defined(__GNUC__) || defined(__MINGW32__) #if GCC_VERSION >= 40500 #pragma GCC diagnostic pop #endif /* GCC_VERSION >= 40500 */ #endif /* defined(__GNUC__) || defined(__MINGW32__) */ for (p = end_word; p < end_whitespace; p++) { *p = '\0'; } *buf = end_whitespace; } return begin_word; } /* Return HTTP header value, or NULL if not found. */ static const char * get_header(const struct mg_header *hdr, int num_hdr, const char *name) { int i; for (i = 0; i < num_hdr; i++) { if (!mg_strcasecmp(name, hdr[i].name)) { return hdr[i].value; } } return NULL; } #if defined(USE_WEBSOCKET) /* Retrieve requested HTTP header multiple values, and return the number of * found occurrences */ static int get_req_headers(const struct mg_request_info *ri, const char *name, const char **output, int output_max_size) { int i; int cnt = 0; if (ri) { for (i = 0; i < ri->num_headers && cnt < output_max_size; i++) { if (!mg_strcasecmp(name, ri->http_headers[i].name)) { output[cnt++] = ri->http_headers[i].value; } } } return cnt; } #endif const char * mg_get_header(const struct mg_connection *conn, const char *name) { if (!conn) { return NULL; } if (conn->connection_type == CONNECTION_TYPE_REQUEST) { return get_header(conn->request_info.http_headers, conn->request_info.num_headers, name); } if (conn->connection_type == CONNECTION_TYPE_RESPONSE) { return get_header(conn->response_info.http_headers, conn->response_info.num_headers, name); } return NULL; } static const char * get_http_version(const struct mg_connection *conn) { if (!conn) { return NULL; } if (conn->connection_type == CONNECTION_TYPE_REQUEST) { return conn->request_info.http_version; } if (conn->connection_type == CONNECTION_TYPE_RESPONSE) { return conn->response_info.http_version; } return NULL; } /* A helper function for traversing a comma separated list of values. * It returns a list pointer shifted to the next value, or NULL if the end * of the list found. * Value is stored in val vector. If value has form "x=y", then eq_val * vector is initialized to point to the "y" part, and val vector length * is adjusted to point only to "x". */ static const char * next_option(const char *list, struct vec *val, struct vec *eq_val) { int end; reparse: if (val == NULL || list == NULL || *list == '\0') { /* End of the list */ return NULL; } /* Skip over leading LWS */ while (*list == ' ' || *list == '\t') list++; val->ptr = list; if ((list = strchr(val->ptr, ',')) != NULL) { /* Comma found. Store length and shift the list ptr */ val->len = ((size_t)(list - val->ptr)); list++; } else { /* This value is the last one */ list = val->ptr + strlen(val->ptr); val->len = ((size_t)(list - val->ptr)); } /* Adjust length for trailing LWS */ end = (int)val->len - 1; while (end >= 0 && ((val->ptr[end] == ' ') || (val->ptr[end] == '\t'))) end--; val->len = (size_t)(end + 1); if (val->len == 0) { /* Ignore any empty entries. */ goto reparse; } if (eq_val != NULL) { /* Value has form "x=y", adjust pointers and lengths * so that val points to "x", and eq_val points to "y". */ eq_val->len = 0; eq_val->ptr = (const char *)memchr(val->ptr, '=', val->len); if (eq_val->ptr != NULL) { eq_val->ptr++; /* Skip over '=' character */ eq_val->len = ((size_t)(val->ptr - eq_val->ptr)) + val->len; val->len = ((size_t)(eq_val->ptr - val->ptr)) - 1; } } return list; } /* A helper function for checking if a comma separated list of values * contains * the given option (case insensitvely). * 'header' can be NULL, in which case false is returned. */ static int header_has_option(const char *header, const char *option) { struct vec opt_vec; struct vec eq_vec; DEBUG_ASSERT(option != NULL); DEBUG_ASSERT(option[0] != '\0'); while ((header = next_option(header, &opt_vec, &eq_vec)) != NULL) { if (mg_strncasecmp(option, opt_vec.ptr, opt_vec.len) == 0) return 1; } return 0; } /* Perform case-insensitive match of string against pattern */ static ptrdiff_t match_prefix(const char *pattern, size_t pattern_len, const char *str) { const char *or_str; ptrdiff_t i, j, len, res; if ((or_str = (const char *)memchr(pattern, '|', pattern_len)) != NULL) { res = match_prefix(pattern, (size_t)(or_str - pattern), str); return (res > 0) ? res : match_prefix(or_str + 1, (size_t)((pattern + pattern_len) - (or_str + 1)), str); } for (i = 0, j = 0; (i < (ptrdiff_t)pattern_len); i++, j++) { if ((pattern[i] == '?') && (str[j] != '\0')) { continue; } else if (pattern[i] == '$') { return (str[j] == '\0') ? j : -1; } else if (pattern[i] == '*') { i++; if (pattern[i] == '*') { i++; len = strlen(str + j); } else { len = strcspn(str + j, "/"); } if (i == (ptrdiff_t)pattern_len) { return j + len; } do { res = match_prefix(pattern + i, pattern_len - i, str + j + len); } while (res == -1 && len-- > 0); return (res == -1) ? -1 : j + res + len; } else if (lowercase(&pattern[i]) != lowercase(&str[j])) { return -1; } } return (ptrdiff_t)j; } /* HTTP 1.1 assumes keep alive if "Connection:" header is not set * This function must tolerate situations when connection info is not * set up, for example if request parsing failed. */ static int should_keep_alive(const struct mg_connection *conn) { const char *http_version; const char *header; /* First satisfy needs of the server */ if ((conn == NULL) || conn->must_close) { /* Close, if civetweb framework needs to close */ return 0; } if (mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes") != 0) { /* Close, if keep alive is not enabled */ return 0; } /* Check explicit wish of the client */ header = mg_get_header(conn, "Connection"); if (header) { /* If there is a connection header from the client, obey */ if (header_has_option(header, "keep-alive")) { return 1; } return 0; } /* Use default of the standard */ http_version = get_http_version(conn); if (http_version && (0 == strcmp(http_version, "1.1"))) { /* HTTP 1.1 default is keep alive */ return 1; } /* HTTP 1.0 (and earlier) default is to close the connection */ return 0; } static int should_decode_url(const struct mg_connection *conn) { if (!conn || !conn->dom_ctx) { return 0; } return (mg_strcasecmp(conn->dom_ctx->config[DECODE_URL], "yes") == 0); } static const char * suggest_connection_header(const struct mg_connection *conn) { return should_keep_alive(conn) ? "keep-alive" : "close"; } static int send_no_cache_header(struct mg_connection *conn) { /* Send all current and obsolete cache opt-out directives. */ return mg_printf(conn, "Cache-Control: no-cache, no-store, " "must-revalidate, private, max-age=0\r\n" "Pragma: no-cache\r\n" "Expires: 0\r\n"); } static int send_static_cache_header(struct mg_connection *conn) { #if !defined(NO_CACHING) /* Read the server config to check how long a file may be cached. * The configuration is in seconds. */ int max_age = atoi(conn->dom_ctx->config[STATIC_FILE_MAX_AGE]); if (max_age <= 0) { /* 0 means "do not cache". All values <0 are reserved * and may be used differently in the future. */ /* If a file should not be cached, do not only send * max-age=0, but also pragmas and Expires headers. */ return send_no_cache_header(conn); } /* Use "Cache-Control: max-age" instead of "Expires" header. * Reason: see https://www.mnot.net/blog/2007/05/15/expires_max-age */ /* See also https://www.mnot.net/cache_docs/ */ /* According to RFC 2616, Section 14.21, caching times should not exceed * one year. A year with 365 days corresponds to 31536000 seconds, a * leap * year to 31622400 seconds. For the moment, we just send whatever has * been configured, still the behavior for >1 year should be considered * as undefined. */ return mg_printf(conn, "Cache-Control: max-age=%u\r\n", (unsigned)max_age); #else /* NO_CACHING */ return send_no_cache_header(conn); #endif /* !NO_CACHING */ } static int send_additional_header(struct mg_connection *conn) { int i = 0; const char *header = conn->dom_ctx->config[ADDITIONAL_HEADER]; #if !defined(NO_SSL) if (conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]) { int max_age = atoi(conn->dom_ctx->config[STRICT_HTTPS_MAX_AGE]); if (max_age >= 0) { i += mg_printf(conn, "Strict-Transport-Security: max-age=%u\r\n", (unsigned)max_age); } } #endif if (header && header[0]) { i += mg_printf(conn, "%s\r\n", header); } return i; } static void handle_file_based_request(struct mg_connection *conn, const char *path, struct mg_file *filep); const char * mg_get_response_code_text(const struct mg_connection *conn, int response_code) { /* See IANA HTTP status code assignment: * http://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml */ switch (response_code) { /* RFC2616 Section 10.1 - Informational 1xx */ case 100: return "Continue"; /* RFC2616 Section 10.1.1 */ case 101: return "Switching Protocols"; /* RFC2616 Section 10.1.2 */ case 102: return "Processing"; /* RFC2518 Section 10.1 */ /* RFC2616 Section 10.2 - Successful 2xx */ case 200: return "OK"; /* RFC2616 Section 10.2.1 */ case 201: return "Created"; /* RFC2616 Section 10.2.2 */ case 202: return "Accepted"; /* RFC2616 Section 10.2.3 */ case 203: return "Non-Authoritative Information"; /* RFC2616 Section 10.2.4 */ case 204: return "No Content"; /* RFC2616 Section 10.2.5 */ case 205: return "Reset Content"; /* RFC2616 Section 10.2.6 */ case 206: return "Partial Content"; /* RFC2616 Section 10.2.7 */ case 207: return "Multi-Status"; /* RFC2518 Section 10.2, RFC4918 Section 11.1 */ case 208: return "Already Reported"; /* RFC5842 Section 7.1 */ case 226: return "IM used"; /* RFC3229 Section 10.4.1 */ /* RFC2616 Section 10.3 - Redirection 3xx */ case 300: return "Multiple Choices"; /* RFC2616 Section 10.3.1 */ case 301: return "Moved Permanently"; /* RFC2616 Section 10.3.2 */ case 302: return "Found"; /* RFC2616 Section 10.3.3 */ case 303: return "See Other"; /* RFC2616 Section 10.3.4 */ case 304: return "Not Modified"; /* RFC2616 Section 10.3.5 */ case 305: return "Use Proxy"; /* RFC2616 Section 10.3.6 */ case 307: return "Temporary Redirect"; /* RFC2616 Section 10.3.8 */ case 308: return "Permanent Redirect"; /* RFC7238 Section 3 */ /* RFC2616 Section 10.4 - Client Error 4xx */ case 400: return "Bad Request"; /* RFC2616 Section 10.4.1 */ case 401: return "Unauthorized"; /* RFC2616 Section 10.4.2 */ case 402: return "Payment Required"; /* RFC2616 Section 10.4.3 */ case 403: return "Forbidden"; /* RFC2616 Section 10.4.4 */ case 404: return "Not Found"; /* RFC2616 Section 10.4.5 */ case 405: return "Method Not Allowed"; /* RFC2616 Section 10.4.6 */ case 406: return "Not Acceptable"; /* RFC2616 Section 10.4.7 */ case 407: return "Proxy Authentication Required"; /* RFC2616 Section 10.4.8 */ case 408: return "Request Time-out"; /* RFC2616 Section 10.4.9 */ case 409: return "Conflict"; /* RFC2616 Section 10.4.10 */ case 410: return "Gone"; /* RFC2616 Section 10.4.11 */ case 411: return "Length Required"; /* RFC2616 Section 10.4.12 */ case 412: return "Precondition Failed"; /* RFC2616 Section 10.4.13 */ case 413: return "Request Entity Too Large"; /* RFC2616 Section 10.4.14 */ case 414: return "Request-URI Too Large"; /* RFC2616 Section 10.4.15 */ case 415: return "Unsupported Media Type"; /* RFC2616 Section 10.4.16 */ case 416: return "Requested range not satisfiable"; /* RFC2616 Section 10.4.17 */ case 417: return "Expectation Failed"; /* RFC2616 Section 10.4.18 */ case 421: return "Misdirected Request"; /* RFC7540 Section 9.1.2 */ case 422: return "Unproccessable entity"; /* RFC2518 Section 10.3, RFC4918 * Section 11.2 */ case 423: return "Locked"; /* RFC2518 Section 10.4, RFC4918 Section 11.3 */ case 424: return "Failed Dependency"; /* RFC2518 Section 10.5, RFC4918 * Section 11.4 */ case 426: return "Upgrade Required"; /* RFC 2817 Section 4 */ case 428: return "Precondition Required"; /* RFC 6585, Section 3 */ case 429: return "Too Many Requests"; /* RFC 6585, Section 4 */ case 431: return "Request Header Fields Too Large"; /* RFC 6585, Section 5 */ case 451: return "Unavailable For Legal Reasons"; /* draft-tbray-http-legally-restricted-status-05, * Section 3 */ /* RFC2616 Section 10.5 - Server Error 5xx */ case 500: return "Internal Server Error"; /* RFC2616 Section 10.5.1 */ case 501: return "Not Implemented"; /* RFC2616 Section 10.5.2 */ case 502: return "Bad Gateway"; /* RFC2616 Section 10.5.3 */ case 503: return "Service Unavailable"; /* RFC2616 Section 10.5.4 */ case 504: return "Gateway Time-out"; /* RFC2616 Section 10.5.5 */ case 505: return "HTTP Version not supported"; /* RFC2616 Section 10.5.6 */ case 506: return "Variant Also Negotiates"; /* RFC 2295, Section 8.1 */ case 507: return "Insufficient Storage"; /* RFC2518 Section 10.6, RFC4918 * Section 11.5 */ case 508: return "Loop Detected"; /* RFC5842 Section 7.1 */ case 510: return "Not Extended"; /* RFC 2774, Section 7 */ case 511: return "Network Authentication Required"; /* RFC 6585, Section 6 */ /* Other status codes, not shown in the IANA HTTP status code * assignment. * E.g., "de facto" standards due to common use, ... */ case 418: return "I am a teapot"; /* RFC2324 Section 2.3.2 */ case 419: return "Authentication Timeout"; /* common use */ case 420: return "Enhance Your Calm"; /* common use */ case 440: return "Login Timeout"; /* common use */ case 509: return "Bandwidth Limit Exceeded"; /* common use */ default: /* This error code is unknown. This should not happen. */ if (conn) { mg_cry_internal(conn, "Unknown HTTP response code: %u", response_code); } /* Return at least a category according to RFC 2616 Section 10. */ if (response_code >= 100 && response_code < 200) { /* Unknown informational status code */ return "Information"; } if (response_code >= 200 && response_code < 300) { /* Unknown success code */ return "Success"; } if (response_code >= 300 && response_code < 400) { /* Unknown redirection code */ return "Redirection"; } if (response_code >= 400 && response_code < 500) { /* Unknown request error code */ return "Client Error"; } if (response_code >= 500 && response_code < 600) { /* Unknown server error code */ return "Server Error"; } /* Response code not even within reasonable range */ return ""; } } static int mg_send_http_error_impl(struct mg_connection *conn, int status, const char *fmt, va_list args) { char errmsg_buf[MG_BUF_LEN]; char path_buf[PATH_MAX]; va_list ap; int len, i, page_handler_found, scope, truncated, has_body; char date[64]; time_t curtime = time(NULL); const char *error_handler = NULL; struct mg_file error_page_file = STRUCT_FILE_INITIALIZER; const char *error_page_file_ext, *tstr; int handled_by_callback = 0; const char *status_text = mg_get_response_code_text(conn, status); if ((conn == NULL) || (fmt == NULL)) { return -2; } /* Set status (for log) */ conn->status_code = status; /* Errors 1xx, 204 and 304 MUST NOT send a body */ has_body = ((status > 199) && (status != 204) && (status != 304)); /* Prepare message in buf, if required */ if (has_body || (!conn->in_error_handler && (conn->phys_ctx->callbacks.http_error != NULL))) { /* Store error message in errmsg_buf */ va_copy(ap, args); mg_vsnprintf(conn, NULL, errmsg_buf, sizeof(errmsg_buf), fmt, ap); va_end(ap); /* In a debug build, print all html errors */ DEBUG_TRACE("Error %i - [%s]", status, errmsg_buf); } /* If there is a http_error callback, call it. * But don't do it recursively, if callback calls mg_send_http_error again. */ if (!conn->in_error_handler && (conn->phys_ctx->callbacks.http_error != NULL)) { /* Mark in_error_handler to avoid recursion and call user callback. */ conn->in_error_handler = 1; handled_by_callback = (conn->phys_ctx->callbacks.http_error(conn, status, errmsg_buf) == 0); conn->in_error_handler = 0; } if (!handled_by_callback) { /* Check for recursion */ if (conn->in_error_handler) { DEBUG_TRACE( "Recursion when handling error %u - fall back to default", status); } else { /* Send user defined error pages, if defined */ error_handler = conn->dom_ctx->config[ERROR_PAGES]; error_page_file_ext = conn->dom_ctx->config[INDEX_FILES]; page_handler_found = 0; if (error_handler != NULL) { for (scope = 1; (scope <= 3) && !page_handler_found; scope++) { switch (scope) { case 1: /* Handler for specific error, e.g. 404 error */ mg_snprintf(conn, &truncated, path_buf, sizeof(path_buf) - 32, "%serror%03u.", error_handler, status); break; case 2: /* Handler for error group, e.g., 5xx error * handler * for all server errors (500-599) */ mg_snprintf(conn, &truncated, path_buf, sizeof(path_buf) - 32, "%serror%01uxx.", error_handler, status / 100); break; default: /* Handler for all errors */ mg_snprintf(conn, &truncated, path_buf, sizeof(path_buf) - 32, "%serror.", error_handler); break; } /* String truncation in buf may only occur if * error_handler is too long. This string is * from the config, not from a client. */ (void)truncated; len = (int)strlen(path_buf); tstr = strchr(error_page_file_ext, '.'); while (tstr) { for (i = 1; (i < 32) && (tstr[i] != 0) && (tstr[i] != ','); i++) { /* buffer overrun is not possible here, since * (i < 32) && (len < sizeof(path_buf) - 32) * ==> (i + len) < sizeof(path_buf) */ path_buf[len + i - 1] = tstr[i]; } /* buffer overrun is not possible here, since * (i <= 32) && (len < sizeof(path_buf) - 32) * ==> (i + len) <= sizeof(path_buf) */ path_buf[len + i - 1] = 0; if (mg_stat(conn, path_buf, &error_page_file.stat)) { DEBUG_TRACE("Check error page %s - found", path_buf); page_handler_found = 1; break; } DEBUG_TRACE("Check error page %s - not found", path_buf); tstr = strchr(tstr + i, '.'); } } } if (page_handler_found) { conn->in_error_handler = 1; handle_file_based_request(conn, path_buf, &error_page_file); conn->in_error_handler = 0; return 0; } } /* No custom error page. Send default error page. */ gmt_time_string(date, sizeof(date), &curtime); conn->must_close = 1; mg_printf(conn, "HTTP/1.1 %d %s\r\n", status, status_text); send_no_cache_header(conn); send_additional_header(conn); if (has_body) { mg_printf(conn, "%s", "Content-Type: text/plain; charset=utf-8\r\n"); } mg_printf(conn, "Date: %s\r\n" "Connection: close\r\n\r\n", date); /* HTTP responses 1xx, 204 and 304 MUST NOT send a body */ if (has_body) { /* For other errors, send a generic error message. */ mg_printf(conn, "Error %d: %s\n", status, status_text); mg_write(conn, errmsg_buf, strlen(errmsg_buf)); } else { /* No body allowed. Close the connection. */ DEBUG_TRACE("Error %i", status); } } return 0; } int mg_send_http_error(struct mg_connection *conn, int status, const char *fmt, ...) { va_list ap; int ret; va_start(ap, fmt); ret = mg_send_http_error_impl(conn, status, fmt, ap); va_end(ap); return ret; } int mg_send_http_ok(struct mg_connection *conn, const char *mime_type, long long content_length) { char date[64]; time_t curtime = time(NULL); if ((mime_type == NULL) || (*mime_type == 0)) { /* Parameter error */ return -2; } gmt_time_string(date, sizeof(date), &curtime); mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Content-Type: %s\r\n" "Date: %s\r\n" "Connection: %s\r\n", mime_type, date, suggest_connection_header(conn)); send_no_cache_header(conn); send_additional_header(conn); if (content_length < 0) { mg_printf(conn, "Transfer-Encoding: chunked\r\n\r\n"); } else { mg_printf(conn, "Content-Length: %" UINT64_FMT "\r\n\r\n", (uint64_t)content_length); } return 0; } int mg_send_http_redirect(struct mg_connection *conn, const char *target_url, int redirect_code) { /* Send a 30x redirect response. * * Redirect types (status codes): * * Status | Perm/Temp | Method | Version * 301 | permanent | POST->GET undefined | HTTP/1.0 * 302 | temporary | POST->GET undefined | HTTP/1.0 * 303 | temporary | always use GET | HTTP/1.1 * 307 | temporary | always keep method | HTTP/1.1 * 308 | permanent | always keep method | HTTP/1.1 */ const char *redirect_text; int ret; size_t content_len = 0; char reply[MG_BUF_LEN]; /* In case redirect_code=0, use 307. */ if (redirect_code == 0) { redirect_code = 307; } /* In case redirect_code is none of the above, return error. */ if ((redirect_code != 301) && (redirect_code != 302) && (redirect_code != 303) && (redirect_code != 307) && (redirect_code != 308)) { /* Parameter error */ return -2; } /* Get proper text for response code */ redirect_text = mg_get_response_code_text(conn, redirect_code); /* If target_url is not defined, redirect to "/". */ if ((target_url == NULL) || (*target_url == 0)) { target_url = "/"; } #if defined(MG_SEND_REDIRECT_BODY) /* TODO: condition name? */ /* Prepare a response body with a hyperlink. * * According to RFC2616 (and RFC1945 before): * Unless the request method was HEAD, the entity of the * response SHOULD contain a short hypertext note with a hyperlink to * the new URI(s). * * However, this response body is not useful in M2M communication. * Probably the original reason in the RFC was, clients not supporting * a 30x HTTP redirect could still show the HTML page and let the user * press the link. Since current browsers support 30x HTTP, the additional * HTML body does not seem to make sense anymore. * * The new RFC7231 (Section 6.4) does no longer recommend it ("SHOULD"), * but it only notes: * The server's response payload usually contains a short * hypertext note with a hyperlink to the new URI(s). * * Deactivated by default. If you need the 30x body, set the define. */ mg_snprintf( conn, NULL /* ignore truncation */, reply, sizeof(reply), "<html><head>%s</head><body><a href=\"%s\">%s</a></body></html>", redirect_text, target_url, target_url); content_len = strlen(reply); #else reply[0] = 0; #endif /* Do not send any additional header. For all other options, * including caching, there are suitable defaults. */ ret = mg_printf(conn, "HTTP/1.1 %i %s\r\n" "Location: %s\r\n" "Content-Length: %u\r\n" "Connection: %s\r\n\r\n", redirect_code, redirect_text, target_url, (unsigned int)content_len, suggest_connection_header(conn)); /* Send response body */ if (ret > 0) { /* ... unless it is a HEAD request */ if (0 != strcmp(conn->request_info.request_method, "HEAD")) { ret = mg_write(conn, reply, content_len); } } return (ret > 0) ? ret : -1; } #if defined(_WIN32) /* Create substitutes for POSIX functions in Win32. */ #if defined(__MINGW32__) /* Show no warning in case system functions are not used. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif FUNCTION_MAY_BE_UNUSED static int pthread_mutex_init(pthread_mutex_t *mutex, void *unused) { (void)unused; *mutex = CreateMutex(NULL, FALSE, NULL); return (*mutex == NULL) ? -1 : 0; } FUNCTION_MAY_BE_UNUSED static int pthread_mutex_destroy(pthread_mutex_t *mutex) { return (CloseHandle(*mutex) == 0) ? -1 : 0; } FUNCTION_MAY_BE_UNUSED static int pthread_mutex_lock(pthread_mutex_t *mutex) { return (WaitForSingleObject(*mutex, (DWORD)INFINITE) == WAIT_OBJECT_0) ? 0 : -1; } #if defined(ENABLE_UNUSED_PTHREAD_FUNCTIONS) FUNCTION_MAY_BE_UNUSED static int pthread_mutex_trylock(pthread_mutex_t *mutex) { switch (WaitForSingleObject(*mutex, 0)) { case WAIT_OBJECT_0: return 0; case WAIT_TIMEOUT: return -2; /* EBUSY */ } return -1; } #endif FUNCTION_MAY_BE_UNUSED static int pthread_mutex_unlock(pthread_mutex_t *mutex) { return (ReleaseMutex(*mutex) == 0) ? -1 : 0; } FUNCTION_MAY_BE_UNUSED static int pthread_cond_init(pthread_cond_t *cv, const void *unused) { (void)unused; InitializeCriticalSection(&cv->threadIdSec); cv->waiting_thread = NULL; return 0; } FUNCTION_MAY_BE_UNUSED static int pthread_cond_timedwait(pthread_cond_t *cv, pthread_mutex_t *mutex, FUNCTION_MAY_BE_UNUSED const struct timespec *abstime) { struct mg_workerTLS **ptls, *tls = (struct mg_workerTLS *)pthread_getspecific(sTlsKey); int ok; int64_t nsnow, nswaitabs, nswaitrel; DWORD mswaitrel; EnterCriticalSection(&cv->threadIdSec); /* Add this thread to cv's waiting list */ ptls = &cv->waiting_thread; for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) ; tls->next_waiting_thread = NULL; *ptls = tls; LeaveCriticalSection(&cv->threadIdSec); if (abstime) { nsnow = mg_get_current_time_ns(); nswaitabs = (((int64_t)abstime->tv_sec) * 1000000000) + abstime->tv_nsec; nswaitrel = nswaitabs - nsnow; if (nswaitrel < 0) { nswaitrel = 0; } mswaitrel = (DWORD)(nswaitrel / 1000000); } else { mswaitrel = (DWORD)INFINITE; } pthread_mutex_unlock(mutex); ok = (WAIT_OBJECT_0 == WaitForSingleObject(tls->pthread_cond_helper_mutex, mswaitrel)); if (!ok) { ok = 1; EnterCriticalSection(&cv->threadIdSec); ptls = &cv->waiting_thread; for (; *ptls != NULL; ptls = &(*ptls)->next_waiting_thread) { if (*ptls == tls) { *ptls = tls->next_waiting_thread; ok = 0; break; } } LeaveCriticalSection(&cv->threadIdSec); if (ok) { WaitForSingleObject(tls->pthread_cond_helper_mutex, (DWORD)INFINITE); } } /* This thread has been removed from cv's waiting list */ pthread_mutex_lock(mutex); return ok ? 0 : -1; } FUNCTION_MAY_BE_UNUSED static int pthread_cond_wait(pthread_cond_t *cv, pthread_mutex_t *mutex) { return pthread_cond_timedwait(cv, mutex, NULL); } FUNCTION_MAY_BE_UNUSED static int pthread_cond_signal(pthread_cond_t *cv) { HANDLE wkup = NULL; BOOL ok = FALSE; EnterCriticalSection(&cv->threadIdSec); if (cv->waiting_thread) { wkup = cv->waiting_thread->pthread_cond_helper_mutex; cv->waiting_thread = cv->waiting_thread->next_waiting_thread; ok = SetEvent(wkup); DEBUG_ASSERT(ok); } LeaveCriticalSection(&cv->threadIdSec); return ok ? 0 : 1; } FUNCTION_MAY_BE_UNUSED static int pthread_cond_broadcast(pthread_cond_t *cv) { EnterCriticalSection(&cv->threadIdSec); while (cv->waiting_thread) { pthread_cond_signal(cv); } LeaveCriticalSection(&cv->threadIdSec); return 0; } FUNCTION_MAY_BE_UNUSED static int pthread_cond_destroy(pthread_cond_t *cv) { EnterCriticalSection(&cv->threadIdSec); DEBUG_ASSERT(cv->waiting_thread == NULL); LeaveCriticalSection(&cv->threadIdSec); DeleteCriticalSection(&cv->threadIdSec); return 0; } #if defined(ALTERNATIVE_QUEUE) FUNCTION_MAY_BE_UNUSED static void * event_create(void) { return (void *)CreateEvent(NULL, FALSE, FALSE, NULL); } FUNCTION_MAY_BE_UNUSED static int event_wait(void *eventhdl) { int res = WaitForSingleObject((HANDLE)eventhdl, (DWORD)INFINITE); return (res == WAIT_OBJECT_0); } FUNCTION_MAY_BE_UNUSED static int event_signal(void *eventhdl) { return (int)SetEvent((HANDLE)eventhdl); } FUNCTION_MAY_BE_UNUSED static void event_destroy(void *eventhdl) { CloseHandle((HANDLE)eventhdl); } #endif #if defined(__MINGW32__) /* Enable unused function warning again */ #pragma GCC diagnostic pop #endif /* For Windows, change all slashes to backslashes in path names. */ static void change_slashes_to_backslashes(char *path) { int i; for (i = 0; path[i] != '\0'; i++) { if (path[i] == '/') { path[i] = '\\'; } /* remove double backslash (check i > 0 to preserve UNC paths, * like \\server\file.txt) */ if ((path[i] == '\\') && (i > 0)) { while ((path[i + 1] == '\\') || (path[i + 1] == '/')) { (void)memmove(path + i + 1, path + i + 2, strlen(path + i + 1)); } } } } static int mg_wcscasecmp(const wchar_t *s1, const wchar_t *s2) { int diff; do { diff = tolower(*s1) - tolower(*s2); s1++; s2++; } while ((diff == 0) && (s1[-1] != '\0')); return diff; } /* Encode 'path' which is assumed UTF-8 string, into UNICODE string. * wbuf and wbuf_len is a target buffer and its length. */ static void path_to_unicode(const struct mg_connection *conn, const char *path, wchar_t *wbuf, size_t wbuf_len) { char buf[PATH_MAX], buf2[PATH_MAX]; wchar_t wbuf2[W_PATH_MAX + 1]; DWORD long_len, err; int (*fcompare)(const wchar_t *, const wchar_t *) = mg_wcscasecmp; mg_strlcpy(buf, path, sizeof(buf)); change_slashes_to_backslashes(buf); /* Convert to Unicode and back. If doubly-converted string does not * match the original, something is fishy, reject. */ memset(wbuf, 0, wbuf_len * sizeof(wchar_t)); MultiByteToWideChar(CP_UTF8, 0, buf, -1, wbuf, (int)wbuf_len); WideCharToMultiByte( CP_UTF8, 0, wbuf, (int)wbuf_len, buf2, sizeof(buf2), NULL, NULL); if (strcmp(buf, buf2) != 0) { wbuf[0] = L'\0'; } /* Windows file systems are not case sensitive, but you can still use * uppercase and lowercase letters (on all modern file systems). * The server can check if the URI uses the same upper/lowercase * letters an the file system, effectively making Windows servers * case sensitive (like Linux servers are). It is still not possible * to use two files with the same name in different cases on Windows * (like /a and /A) - this would be possible in Linux. * As a default, Windows is not case sensitive, but the case sensitive * file name check can be activated by an additional configuration. */ if (conn) { if (conn->dom_ctx->config[CASE_SENSITIVE_FILES] && !mg_strcasecmp(conn->dom_ctx->config[CASE_SENSITIVE_FILES], "yes")) { /* Use case sensitive compare function */ fcompare = wcscmp; } } (void)conn; /* conn is currently unused */ #if !defined(_WIN32_WCE) /* Only accept a full file path, not a Windows short (8.3) path. */ memset(wbuf2, 0, ARRAY_SIZE(wbuf2) * sizeof(wchar_t)); long_len = GetLongPathNameW(wbuf, wbuf2, ARRAY_SIZE(wbuf2) - 1); if (long_len == 0) { err = GetLastError(); if (err == ERROR_FILE_NOT_FOUND) { /* File does not exist. This is not always a problem here. */ return; } } if ((long_len >= ARRAY_SIZE(wbuf2)) || (fcompare(wbuf, wbuf2) != 0)) { /* Short name is used. */ wbuf[0] = L'\0'; } #else (void)long_len; (void)wbuf2; (void)err; if (strchr(path, '~')) { wbuf[0] = L'\0'; } #endif } /* Windows happily opens files with some garbage at the end of file name. * For example, fopen("a.cgi ", "r") on Windows successfully opens * "a.cgi", despite one would expect an error back. * This function returns non-0 if path ends with some garbage. */ static int path_cannot_disclose_cgi(const char *path) { static const char *allowed_last_characters = "_-"; int last = path[strlen(path) - 1]; return isalnum(last) || strchr(allowed_last_characters, last) != NULL; } static int mg_stat(const struct mg_connection *conn, const char *path, struct mg_file_stat *filep) { wchar_t wbuf[W_PATH_MAX]; WIN32_FILE_ATTRIBUTE_DATA info; time_t creation_time; if (!filep) { return 0; } memset(filep, 0, sizeof(*filep)); if (conn && is_file_in_memory(conn, path)) { /* filep->is_directory = 0; filep->gzipped = 0; .. already done by * memset */ /* Quick fix (for 1.9.x): */ /* mg_stat must fill all fields, also for files in memory */ struct mg_file tmp_file = STRUCT_FILE_INITIALIZER; open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE); filep->size = tmp_file.stat.size; filep->location = 2; /* TODO: for 1.10: restructure how files in memory are handled */ /* The "file in memory" feature is a candidate for deletion. * Please join the discussion at * https://groups.google.com/forum/#!topic/civetweb/h9HT4CmeYqI */ filep->last_modified = time(NULL); /* TODO */ /* last_modified = now ... assumes the file may change during * runtime, * so every mg_fopen call may return different data */ /* last_modified = conn->phys_ctx.start_time; * May be used it the data does not change during runtime. This * allows * browser caching. Since we do not know, we have to assume the file * in memory may change. */ return 1; } path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf)); if (GetFileAttributesExW(wbuf, GetFileExInfoStandard, &info) != 0) { filep->size = MAKEUQUAD(info.nFileSizeLow, info.nFileSizeHigh); filep->last_modified = SYS2UNIX_TIME(info.ftLastWriteTime.dwLowDateTime, info.ftLastWriteTime.dwHighDateTime); /* On Windows, the file creation time can be higher than the * modification time, e.g. when a file is copied. * Since the Last-Modified timestamp is used for caching * it should be based on the most recent timestamp. */ creation_time = SYS2UNIX_TIME(info.ftCreationTime.dwLowDateTime, info.ftCreationTime.dwHighDateTime); if (creation_time > filep->last_modified) { filep->last_modified = creation_time; } filep->is_directory = info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY; /* If file name is fishy, reset the file structure and return * error. * Note it is important to reset, not just return the error, cause * functions like is_file_opened() check the struct. */ if (!filep->is_directory && !path_cannot_disclose_cgi(path)) { memset(filep, 0, sizeof(*filep)); return 0; } return 1; } return 0; } static int mg_remove(const struct mg_connection *conn, const char *path) { wchar_t wbuf[W_PATH_MAX]; path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf)); return DeleteFileW(wbuf) ? 0 : -1; } static int mg_mkdir(const struct mg_connection *conn, const char *path, int mode) { wchar_t wbuf[W_PATH_MAX]; (void)mode; path_to_unicode(conn, path, wbuf, ARRAY_SIZE(wbuf)); return CreateDirectoryW(wbuf, NULL) ? 0 : -1; } /* Create substitutes for POSIX functions in Win32. */ #if defined(__MINGW32__) /* Show no warning in case system functions are not used. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif /* Implementation of POSIX opendir/closedir/readdir for Windows. */ FUNCTION_MAY_BE_UNUSED static DIR * mg_opendir(const struct mg_connection *conn, const char *name) { DIR *dir = NULL; wchar_t wpath[W_PATH_MAX]; DWORD attrs; if (name == NULL) { SetLastError(ERROR_BAD_ARGUMENTS); } else if ((dir = (DIR *)mg_malloc(sizeof(*dir))) == NULL) { SetLastError(ERROR_NOT_ENOUGH_MEMORY); } else { path_to_unicode(conn, name, wpath, ARRAY_SIZE(wpath)); attrs = GetFileAttributesW(wpath); if ((wcslen(wpath) + 2 < ARRAY_SIZE(wpath)) && (attrs != 0xFFFFFFFF) && ((attrs & FILE_ATTRIBUTE_DIRECTORY) != 0)) { (void)wcscat(wpath, L"\\*"); dir->handle = FindFirstFileW(wpath, &dir->info); dir->result.d_name[0] = '\0'; } else { mg_free(dir); dir = NULL; } } return dir; } FUNCTION_MAY_BE_UNUSED static int mg_closedir(DIR *dir) { int result = 0; if (dir != NULL) { if (dir->handle != INVALID_HANDLE_VALUE) result = FindClose(dir->handle) ? 0 : -1; mg_free(dir); } else { result = -1; SetLastError(ERROR_BAD_ARGUMENTS); } return result; } FUNCTION_MAY_BE_UNUSED static struct dirent * mg_readdir(DIR *dir) { struct dirent *result = 0; if (dir) { if (dir->handle != INVALID_HANDLE_VALUE) { result = &dir->result; (void)WideCharToMultiByte(CP_UTF8, 0, dir->info.cFileName, -1, result->d_name, sizeof(result->d_name), NULL, NULL); if (!FindNextFileW(dir->handle, &dir->info)) { (void)FindClose(dir->handle); dir->handle = INVALID_HANDLE_VALUE; } } else { SetLastError(ERROR_FILE_NOT_FOUND); } } else { SetLastError(ERROR_BAD_ARGUMENTS); } return result; } #if !defined(HAVE_POLL) #define POLLIN (1) /* Data ready - read will not block. */ #define POLLPRI (2) /* Priority data ready. */ #define POLLOUT (4) /* Send queue not full - write will not block. */ FUNCTION_MAY_BE_UNUSED static int poll(struct pollfd *pfd, unsigned int n, int milliseconds) { struct timeval tv; fd_set rset; fd_set wset; unsigned int i; int result; SOCKET maxfd = 0; memset(&tv, 0, sizeof(tv)); tv.tv_sec = milliseconds / 1000; tv.tv_usec = (milliseconds % 1000) * 1000; FD_ZERO(&rset); FD_ZERO(&wset); for (i = 0; i < n; i++) { if (pfd[i].events & POLLIN) { FD_SET((SOCKET)pfd[i].fd, &rset); } else if (pfd[i].events & POLLOUT) { FD_SET((SOCKET)pfd[i].fd, &wset); } pfd[i].revents = 0; if (pfd[i].fd > maxfd) { maxfd = pfd[i].fd; } } if ((result = select((int)maxfd + 1, &rset, &wset, NULL, &tv)) > 0) { for (i = 0; i < n; i++) { if (FD_ISSET(pfd[i].fd, &rset)) { pfd[i].revents |= POLLIN; } if (FD_ISSET(pfd[i].fd, &wset)) { pfd[i].revents |= POLLOUT; } } } /* We should subtract the time used in select from remaining * "milliseconds", in particular if called from mg_poll with a * timeout quantum. * Unfortunately, the remaining time is not stored in "tv" in all * implementations, so the result in "tv" must be considered undefined. * See http://man7.org/linux/man-pages/man2/select.2.html */ return result; } #endif /* HAVE_POLL */ #if defined(__MINGW32__) /* Enable unused function warning again */ #pragma GCC diagnostic pop #endif static void set_close_on_exec(SOCKET sock, struct mg_connection *conn /* may be null */) { (void)conn; /* Unused. */ #if defined(_WIN32_WCE) (void)sock; #else (void)SetHandleInformation((HANDLE)(intptr_t)sock, HANDLE_FLAG_INHERIT, 0); #endif } int mg_start_thread(mg_thread_func_t f, void *p) { #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) /* Compile-time option to control stack size, e.g. * -DUSE_STACK_SIZE=16384 */ return ((_beginthread((void(__cdecl *)(void *))f, USE_STACK_SIZE, p) == ((uintptr_t)(-1L))) ? -1 : 0); #else return ( (_beginthread((void(__cdecl *)(void *))f, 0, p) == ((uintptr_t)(-1L))) ? -1 : 0); #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */ } /* Start a thread storing the thread context. */ static int mg_start_thread_with_id(unsigned(__stdcall *f)(void *), void *p, pthread_t *threadidptr) { uintptr_t uip; HANDLE threadhandle; int result = -1; uip = _beginthreadex(NULL, 0, (unsigned(__stdcall *)(void *))f, p, 0, NULL); threadhandle = (HANDLE)uip; if ((uip != (uintptr_t)(-1L)) && (threadidptr != NULL)) { *threadidptr = threadhandle; result = 0; } return result; } /* Wait for a thread to finish. */ static int mg_join_thread(pthread_t threadid) { int result; DWORD dwevent; result = -1; dwevent = WaitForSingleObject(threadid, (DWORD)INFINITE); if (dwevent == WAIT_FAILED) { DEBUG_TRACE("WaitForSingleObject() failed, error %d", ERRNO); } else { if (dwevent == WAIT_OBJECT_0) { CloseHandle(threadid); result = 0; } } return result; } #if !defined(NO_SSL_DL) && !defined(NO_SSL) /* If SSL is loaded dynamically, dlopen/dlclose is required. */ /* Create substitutes for POSIX functions in Win32. */ #if defined(__MINGW32__) /* Show no warning in case system functions are not used. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wunused-function" #endif FUNCTION_MAY_BE_UNUSED static HANDLE dlopen(const char *dll_name, int flags) { wchar_t wbuf[W_PATH_MAX]; (void)flags; path_to_unicode(NULL, dll_name, wbuf, ARRAY_SIZE(wbuf)); return LoadLibraryW(wbuf); } FUNCTION_MAY_BE_UNUSED static int dlclose(void *handle) { int result; if (FreeLibrary((HMODULE)handle) != 0) { result = 0; } else { result = -1; } return result; } #if defined(__MINGW32__) /* Enable unused function warning again */ #pragma GCC diagnostic pop #endif #endif #if !defined(NO_CGI) #define SIGKILL (0) static int kill(pid_t pid, int sig_num) { (void)TerminateProcess((HANDLE)pid, (UINT)sig_num); (void)CloseHandle((HANDLE)pid); return 0; } #ifndef WNOHANG #define WNOHANG (1) #endif static pid_t waitpid(pid_t pid, int *status, int flags) { DWORD timeout = INFINITE; DWORD waitres; (void)status; /* Currently not used by any client here */ if ((flags | WNOHANG) == WNOHANG) { timeout = 0; } waitres = WaitForSingleObject((HANDLE)pid, timeout); if (waitres == WAIT_OBJECT_0) { return pid; } if (waitres == WAIT_TIMEOUT) { return 0; } return (pid_t)-1; } static void trim_trailing_whitespaces(char *s) { char *e = s + strlen(s) - 1; while ((e > s) && isspace(*(unsigned char *)e)) { *e-- = '\0'; } } static pid_t spawn_process(struct mg_connection *conn, const char *prog, char *envblk, char *envp[], int fdin[2], int fdout[2], int fderr[2], const char *dir) { HANDLE me; char *p, *interp, full_interp[PATH_MAX], full_dir[PATH_MAX], cmdline[PATH_MAX], buf[PATH_MAX]; int truncated; struct mg_file file = STRUCT_FILE_INITIALIZER; STARTUPINFOA si; PROCESS_INFORMATION pi = {0}; (void)envp; memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW; si.wShowWindow = SW_HIDE; me = GetCurrentProcess(); DuplicateHandle(me, (HANDLE)_get_osfhandle(fdin[0]), me, &si.hStdInput, 0, TRUE, DUPLICATE_SAME_ACCESS); DuplicateHandle(me, (HANDLE)_get_osfhandle(fdout[1]), me, &si.hStdOutput, 0, TRUE, DUPLICATE_SAME_ACCESS); DuplicateHandle(me, (HANDLE)_get_osfhandle(fderr[1]), me, &si.hStdError, 0, TRUE, DUPLICATE_SAME_ACCESS); /* Mark handles that should not be inherited. See * https://msdn.microsoft.com/en-us/library/windows/desktop/ms682499%28v=vs.85%29.aspx */ SetHandleInformation((HANDLE)_get_osfhandle(fdin[1]), HANDLE_FLAG_INHERIT, 0); SetHandleInformation((HANDLE)_get_osfhandle(fdout[0]), HANDLE_FLAG_INHERIT, 0); SetHandleInformation((HANDLE)_get_osfhandle(fderr[0]), HANDLE_FLAG_INHERIT, 0); /* If CGI file is a script, try to read the interpreter line */ interp = conn->dom_ctx->config[CGI_INTERPRETER]; if (interp == NULL) { buf[0] = buf[1] = '\0'; /* Read the first line of the script into the buffer */ mg_snprintf( conn, &truncated, cmdline, sizeof(cmdline), "%s/%s", dir, prog); if (truncated) { pi.hProcess = (pid_t)-1; goto spawn_cleanup; } if (mg_fopen(conn, cmdline, MG_FOPEN_MODE_READ, &file)) { #if defined(MG_USE_OPEN_FILE) p = (char *)file.access.membuf; #else p = (char *)NULL; #endif mg_fgets(buf, sizeof(buf), &file, &p); (void)mg_fclose(&file.access); /* ignore error on read only file */ buf[sizeof(buf) - 1] = '\0'; } if ((buf[0] == '#') && (buf[1] == '!')) { trim_trailing_whitespaces(buf + 2); } else { buf[2] = '\0'; } interp = buf + 2; } if (interp[0] != '\0') { GetFullPathNameA(interp, sizeof(full_interp), full_interp, NULL); interp = full_interp; } GetFullPathNameA(dir, sizeof(full_dir), full_dir, NULL); if (interp[0] != '\0') { mg_snprintf(conn, &truncated, cmdline, sizeof(cmdline), "\"%s\" \"%s\\%s\"", interp, full_dir, prog); } else { mg_snprintf(conn, &truncated, cmdline, sizeof(cmdline), "\"%s\\%s\"", full_dir, prog); } if (truncated) { pi.hProcess = (pid_t)-1; goto spawn_cleanup; } DEBUG_TRACE("Running [%s]", cmdline); if (CreateProcessA(NULL, cmdline, NULL, NULL, TRUE, CREATE_NEW_PROCESS_GROUP, envblk, NULL, &si, &pi) == 0) { mg_cry_internal( conn, "%s: CreateProcess(%s): %ld", __func__, cmdline, (long)ERRNO); pi.hProcess = (pid_t)-1; /* goto spawn_cleanup; */ } spawn_cleanup: (void)CloseHandle(si.hStdOutput); (void)CloseHandle(si.hStdError); (void)CloseHandle(si.hStdInput); if (pi.hThread != NULL) { (void)CloseHandle(pi.hThread); } return (pid_t)pi.hProcess; } #endif /* !NO_CGI */ static int set_blocking_mode(SOCKET sock) { unsigned long non_blocking = 0; return ioctlsocket(sock, (long)FIONBIO, &non_blocking); } static int set_non_blocking_mode(SOCKET sock) { unsigned long non_blocking = 1; return ioctlsocket(sock, (long)FIONBIO, &non_blocking); } #else static int mg_stat(const struct mg_connection *conn, const char *path, struct mg_file_stat *filep) { struct stat st; if (!filep) { return 0; } memset(filep, 0, sizeof(*filep)); if (conn && is_file_in_memory(conn, path)) { /* Quick fix (for 1.9.x): */ /* mg_stat must fill all fields, also for files in memory */ struct mg_file tmp_file = STRUCT_FILE_INITIALIZER; open_file_in_memory(conn, path, &tmp_file, MG_FOPEN_MODE_NONE); filep->size = tmp_file.stat.size; filep->last_modified = time(NULL); filep->location = 2; /* TODO: remove legacy "files in memory" feature */ return 1; } if (0 == stat(path, &st)) { filep->size = (uint64_t)(st.st_size); filep->last_modified = st.st_mtime; filep->is_directory = S_ISDIR(st.st_mode); return 1; } return 0; } static void set_close_on_exec(SOCKET fd, struct mg_connection *conn /* may be null */) { if (fcntl(fd, F_SETFD, FD_CLOEXEC) != 0) { if (conn) { mg_cry_internal(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s", __func__, strerror(ERRNO)); } } } int mg_start_thread(mg_thread_func_t func, void *param) { pthread_t thread_id; pthread_attr_t attr; int result; (void)pthread_attr_init(&attr); (void)pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) /* Compile-time option to control stack size, * e.g. -DUSE_STACK_SIZE=16384 */ (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE); #endif /* defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) */ result = pthread_create(&thread_id, &attr, func, param); pthread_attr_destroy(&attr); return result; } /* Start a thread storing the thread context. */ static int mg_start_thread_with_id(mg_thread_func_t func, void *param, pthread_t *threadidptr) { pthread_t thread_id; pthread_attr_t attr; int result; (void)pthread_attr_init(&attr); #if defined(USE_STACK_SIZE) && (USE_STACK_SIZE > 1) /* Compile-time option to control stack size, * e.g. -DUSE_STACK_SIZE=16384 */ (void)pthread_attr_setstacksize(&attr, USE_STACK_SIZE); #endif /* defined(USE_STACK_SIZE) && USE_STACK_SIZE > 1 */ result = pthread_create(&thread_id, &attr, func, param); pthread_attr_destroy(&attr); if ((result == 0) && (threadidptr != NULL)) { *threadidptr = thread_id; } return result; } /* Wait for a thread to finish. */ static int mg_join_thread(pthread_t threadid) { int result; result = pthread_join(threadid, NULL); return result; } #if !defined(NO_CGI) static pid_t spawn_process(struct mg_connection *conn, const char *prog, char *envblk, char *envp[], int fdin[2], int fdout[2], int fderr[2], const char *dir) { pid_t pid; const char *interp; (void)envblk; if (conn == NULL) { return 0; } if ((pid = fork()) == -1) { /* Parent */ mg_send_http_error(conn, 500, "Error: Creating CGI process\nfork(): %s", strerror(ERRNO)); } else if (pid == 0) { /* Child */ if (chdir(dir) != 0) { mg_cry_internal( conn, "%s: chdir(%s): %s", __func__, dir, strerror(ERRNO)); } else if (dup2(fdin[0], 0) == -1) { mg_cry_internal(conn, "%s: dup2(%d, 0): %s", __func__, fdin[0], strerror(ERRNO)); } else if (dup2(fdout[1], 1) == -1) { mg_cry_internal(conn, "%s: dup2(%d, 1): %s", __func__, fdout[1], strerror(ERRNO)); } else if (dup2(fderr[1], 2) == -1) { mg_cry_internal(conn, "%s: dup2(%d, 2): %s", __func__, fderr[1], strerror(ERRNO)); } else { /* Keep stderr and stdout in two different pipes. * Stdout will be sent back to the client, * stderr should go into a server error log. */ (void)close(fdin[0]); (void)close(fdout[1]); (void)close(fderr[1]); /* Close write end fdin and read end fdout and fderr */ (void)close(fdin[1]); (void)close(fdout[0]); (void)close(fderr[0]); /* After exec, all signal handlers are restored to their default * values, with one exception of SIGCHLD. According to * POSIX.1-2001 and Linux's implementation, SIGCHLD's handler * will leave unchanged after exec if it was set to be ignored. * Restore it to default action. */ signal(SIGCHLD, SIG_DFL); interp = conn->dom_ctx->config[CGI_INTERPRETER]; if (interp == NULL) { (void)execle(prog, prog, NULL, envp); mg_cry_internal(conn, "%s: execle(%s): %s", __func__, prog, strerror(ERRNO)); } else { (void)execle(interp, interp, prog, NULL, envp); mg_cry_internal(conn, "%s: execle(%s %s): %s", __func__, interp, prog, strerror(ERRNO)); } } exit(EXIT_FAILURE); } return pid; } #endif /* !NO_CGI */ static int set_non_blocking_mode(SOCKET sock) { int flags = fcntl(sock, F_GETFL, 0); if (flags < 0) { return -1; } if (fcntl(sock, F_SETFL, (flags | O_NONBLOCK)) < 0) { return -1; } return 0; } static int set_blocking_mode(SOCKET sock) { int flags = fcntl(sock, F_GETFL, 0); if (flags < 0) { return -1; } if (fcntl(sock, F_SETFL, flags & (~(int)(O_NONBLOCK))) < 0) { return -1; } return 0; } #endif /* _WIN32 / else */ /* End of initial operating system specific define block. */ /* Get a random number (independent of C rand function) */ static uint64_t get_random(void) { static uint64_t lfsr = 0; /* Linear feedback shift register */ static uint64_t lcg = 0; /* Linear congruential generator */ uint64_t now = mg_get_current_time_ns(); if (lfsr == 0) { /* lfsr will be only 0 if has not been initialized, * so this code is called only once. */ lfsr = mg_get_current_time_ns(); lcg = mg_get_current_time_ns(); } else { /* Get the next step of both random number generators. */ lfsr = (lfsr >> 1) | ((((lfsr >> 0) ^ (lfsr >> 1) ^ (lfsr >> 3) ^ (lfsr >> 4)) & 1) << 63); lcg = lcg * 6364136223846793005LL + 1442695040888963407LL; } /* Combining two pseudo-random number generators and a high resolution * part * of the current server time will make it hard (impossible?) to guess * the * next number. */ return (lfsr ^ lcg ^ now); } static int mg_poll(struct pollfd *pfd, unsigned int n, int milliseconds, volatile int *stop_server) { /* Call poll, but only for a maximum time of a few seconds. * This will allow to stop the server after some seconds, instead * of having to wait for a long socket timeout. */ int ms_now = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */ do { int result; if (*stop_server) { /* Shut down signal */ return -2; } if ((milliseconds >= 0) && (milliseconds < ms_now)) { ms_now = milliseconds; } result = poll(pfd, n, ms_now); if (result != 0) { /* Poll returned either success (1) or error (-1). * Forward both to the caller. */ return result; } /* Poll returned timeout (0). */ if (milliseconds > 0) { milliseconds -= ms_now; } } while (milliseconds != 0); /* timeout: return 0 */ return 0; } /* Write data to the IO channel - opened file descriptor, socket or SSL * descriptor. * Return value: * >=0 .. number of bytes successfully written * -1 .. timeout * -2 .. error */ static int push_inner(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int len, double timeout) { uint64_t start = 0, now = 0, timeout_ns = 0; int n, err; unsigned ms_wait = SOCKET_TIMEOUT_QUANTUM; /* Sleep quantum in ms */ #if defined(_WIN32) typedef int len_t; #else typedef size_t len_t; #endif if (timeout > 0) { now = mg_get_current_time_ns(); start = now; timeout_ns = (uint64_t)(timeout * 1.0E9); } if (ctx == NULL) { return -2; } #if defined(NO_SSL) if (ssl) { return -2; } #endif /* Try to read until it succeeds, fails, times out, or the server * shuts down. */ for (;;) { #if !defined(NO_SSL) if (ssl != NULL) { n = SSL_write(ssl, buf, len); if (n <= 0) { err = SSL_get_error(ssl, n); if ((err == SSL_ERROR_SYSCALL) && (n == -1)) { err = ERRNO; } else if ((err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)) { n = 0; } else { DEBUG_TRACE("SSL_write() failed, error %d", err); return -2; } } else { err = 0; } } else #endif if (fp != NULL) { n = (int)fwrite(buf, 1, (size_t)len, fp); if (ferror(fp)) { n = -1; err = ERRNO; } else { err = 0; } } else { n = (int)send(sock, buf, (len_t)len, MSG_NOSIGNAL); err = (n < 0) ? ERRNO : 0; #if defined(_WIN32) if (err == WSAEWOULDBLOCK) { err = 0; n = 0; } #else if (err == EWOULDBLOCK) { err = 0; n = 0; } #endif if (n < 0) { /* shutdown of the socket at client side */ return -2; } } if (ctx->stop_flag) { return -2; } if ((n > 0) || ((n == 0) && (len == 0))) { /* some data has been read, or no data was requested */ return n; } if (n < 0) { /* socket error - check errno */ DEBUG_TRACE("send() failed, error %d", err); /* TODO (mid): error handling depending on the error code. * These codes are different between Windows and Linux. * Currently there is no problem with failing send calls, * if there is a reproducible situation, it should be * investigated in detail. */ return -2; } /* Only in case n=0 (timeout), repeat calling the write function */ /* If send failed, wait before retry */ if (fp != NULL) { /* For files, just wait a fixed time. * Maybe it helps, maybe not. */ mg_sleep(5); } else { /* For sockets, wait for the socket using poll */ struct pollfd pfd[1]; int pollres; pfd[0].fd = sock; pfd[0].events = POLLOUT; pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag)); if (ctx->stop_flag) { return -2; } if (pollres > 0) { continue; } } if (timeout > 0) { now = mg_get_current_time_ns(); if ((now - start) > timeout_ns) { /* Timeout */ break; } } } (void)err; /* Avoid unused warning if NO_SSL is set and DEBUG_TRACE is not used */ return -1; } static int64_t push_all(struct mg_context *ctx, FILE *fp, SOCKET sock, SSL *ssl, const char *buf, int64_t len) { double timeout = -1.0; int64_t n, nwritten = 0; if (ctx == NULL) { return -1; } if (ctx->dd.config[REQUEST_TIMEOUT]) { timeout = atoi(ctx->dd.config[REQUEST_TIMEOUT]) / 1000.0; } while ((len > 0) && (ctx->stop_flag == 0)) { n = push_inner(ctx, fp, sock, ssl, buf + nwritten, (int)len, timeout); if (n < 0) { if (nwritten == 0) { nwritten = n; /* Propagate the error */ } break; } else if (n == 0) { break; /* No more data to write */ } else { nwritten += n; len -= n; } } return nwritten; } /* Read from IO channel - opened file descriptor, socket, or SSL descriptor. * Return value: * >=0 .. number of bytes successfully read * -1 .. timeout * -2 .. error */ static int pull_inner(FILE *fp, struct mg_connection *conn, char *buf, int len, double timeout) { int nread, err = 0; #if defined(_WIN32) typedef int len_t; #else typedef size_t len_t; #endif #if !defined(NO_SSL) int ssl_pending; #endif /* We need an additional wait loop around this, because in some cases * with TLSwe may get data from the socket but not from SSL_read. * In this case we need to repeat at least once. */ if (fp != NULL) { #if !defined(_WIN32_WCE) /* Use read() instead of fread(), because if we're reading from the * CGI pipe, fread() may block until IO buffer is filled up. We * cannot afford to block and must pass all read bytes immediately * to the client. */ nread = (int)read(fileno(fp), buf, (size_t)len); #else /* WinCE does not support CGI pipes */ nread = (int)fread(buf, 1, (size_t)len, fp); #endif err = (nread < 0) ? ERRNO : 0; if ((nread == 0) && (len > 0)) { /* Should get data, but got EOL */ return -2; } #if !defined(NO_SSL) } else if ((conn->ssl != NULL) && ((ssl_pending = SSL_pending(conn->ssl)) > 0)) { /* We already know there is no more data buffered in conn->buf * but there is more available in the SSL layer. So don't poll * conn->client.sock yet. */ if (ssl_pending > len) { ssl_pending = len; } nread = SSL_read(conn->ssl, buf, ssl_pending); if (nread <= 0) { err = SSL_get_error(conn->ssl, nread); if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) { err = ERRNO; } else if ((err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)) { nread = 0; } else { DEBUG_TRACE("SSL_read() failed, error %d", err); return -1; } } else { err = 0; } } else if (conn->ssl != NULL) { struct pollfd pfd[1]; int pollres; pfd[0].fd = conn->client.sock; pfd[0].events = POLLIN; pollres = mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->phys_ctx->stop_flag)); if (conn->phys_ctx->stop_flag) { return -2; } if (pollres > 0) { nread = SSL_read(conn->ssl, buf, len); if (nread <= 0) { err = SSL_get_error(conn->ssl, nread); if ((err == SSL_ERROR_SYSCALL) && (nread == -1)) { err = ERRNO; } else if ((err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE)) { nread = 0; } else { DEBUG_TRACE("SSL_read() failed, error %d", err); return -2; } } else { err = 0; } } else if (pollres < 0) { /* Error */ return -2; } else { /* pollres = 0 means timeout */ nread = 0; } #endif } else { struct pollfd pfd[1]; int pollres; pfd[0].fd = conn->client.sock; pfd[0].events = POLLIN; pollres = mg_poll(pfd, 1, (int)(timeout * 1000.0), &(conn->phys_ctx->stop_flag)); if (conn->phys_ctx->stop_flag) { return -2; } if (pollres > 0) { nread = (int)recv(conn->client.sock, buf, (len_t)len, 0); err = (nread < 0) ? ERRNO : 0; if (nread <= 0) { /* shutdown of the socket at client side */ return -2; } } else if (pollres < 0) { /* error callint poll */ return -2; } else { /* pollres = 0 means timeout */ nread = 0; } } if (conn->phys_ctx->stop_flag) { return -2; } if ((nread > 0) || ((nread == 0) && (len == 0))) { /* some data has been read, or no data was requested */ return nread; } if (nread < 0) { /* socket error - check errno */ #if defined(_WIN32) if (err == WSAEWOULDBLOCK) { /* TODO (low): check if this is still required */ /* standard case if called from close_socket_gracefully */ return -2; } else if (err == WSAETIMEDOUT) { /* TODO (low): check if this is still required */ /* timeout is handled by the while loop */ return 0; } else if (err == WSAECONNABORTED) { /* See https://www.chilkatsoft.com/p/p_299.asp */ return -2; } else { DEBUG_TRACE("recv() failed, error %d", err); return -2; } #else /* TODO: POSIX returns either EAGAIN or EWOULDBLOCK in both cases, * if the timeout is reached and if the socket was set to non- * blocking in close_socket_gracefully, so we can not distinguish * here. We have to wait for the timeout in both cases for now. */ if ((err == EAGAIN) || (err == EWOULDBLOCK) || (err == EINTR)) { /* TODO (low): check if this is still required */ /* EAGAIN/EWOULDBLOCK: * standard case if called from close_socket_gracefully * => should return -1 */ /* or timeout occurred * => the code must stay in the while loop */ /* EINTR can be generated on a socket with a timeout set even * when SA_RESTART is effective for all relevant signals * (see signal(7)). * => stay in the while loop */ } else { DEBUG_TRACE("recv() failed, error %d", err); return -2; } #endif } /* Timeout occurred, but no data available. */ return -1; } static int pull_all(FILE *fp, struct mg_connection *conn, char *buf, int len) { int n, nread = 0; double timeout = -1.0; uint64_t start_time = 0, now = 0, timeout_ns = 0; if (conn->dom_ctx->config[REQUEST_TIMEOUT]) { timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0; } if (timeout >= 0.0) { start_time = mg_get_current_time_ns(); timeout_ns = (uint64_t)(timeout * 1.0E9); } while ((len > 0) && (conn->phys_ctx->stop_flag == 0)) { n = pull_inner(fp, conn, buf + nread, len, timeout); if (n == -2) { if (nread == 0) { nread = -1; /* Propagate the error */ } break; } else if (n == -1) { /* timeout */ if (timeout >= 0.0) { now = mg_get_current_time_ns(); if ((now - start_time) <= timeout_ns) { continue; } } break; } else if (n == 0) { break; /* No more data to read */ } else { conn->consumed_content += n; nread += n; len -= n; } } return nread; } static void discard_unread_request_data(struct mg_connection *conn) { char buf[MG_BUF_LEN]; size_t to_read; int nread; if (conn == NULL) { return; } to_read = sizeof(buf); if (conn->is_chunked) { /* Chunked encoding: 3=chunk read completely * completely */ while (conn->is_chunked != 3) { nread = mg_read(conn, buf, to_read); if (nread <= 0) { break; } } } else { /* Not chunked: content length is known */ while (conn->consumed_content < conn->content_len) { if (to_read > (size_t)(conn->content_len - conn->consumed_content)) { to_read = (size_t)(conn->content_len - conn->consumed_content); } nread = mg_read(conn, buf, to_read); if (nread <= 0) { break; } } } } static int mg_read_inner(struct mg_connection *conn, void *buf, size_t len) { int64_t n, buffered_len, nread; int64_t len64 = (int64_t)((len > INT_MAX) ? INT_MAX : len); /* since the return value is * int, we may not read more * bytes */ const char *body; if (conn == NULL) { return 0; } /* If Content-Length is not set for a request with body data * (e.g., a PUT or POST request), we do not know in advance * how much data should be read. */ if (conn->consumed_content == 0) { if (conn->is_chunked == 1) { conn->content_len = len64; conn->is_chunked = 2; } else if (conn->content_len == -1) { /* The body data is completed when the connection * is closed. */ conn->content_len = INT64_MAX; conn->must_close = 1; } } nread = 0; if (conn->consumed_content < conn->content_len) { /* Adjust number of bytes to read. */ int64_t left_to_read = conn->content_len - conn->consumed_content; if (left_to_read < len64) { /* Do not read more than the total content length of the * request. */ len64 = left_to_read; } /* Return buffered data */ buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len - conn->consumed_content; if (buffered_len > 0) { if (len64 < buffered_len) { buffered_len = len64; } body = conn->buf + conn->request_len + conn->consumed_content; memcpy(buf, body, (size_t)buffered_len); len64 -= buffered_len; conn->consumed_content += buffered_len; nread += buffered_len; buf = (char *)buf + buffered_len; } /* We have returned all buffered data. Read new data from the remote * socket. */ if ((n = pull_all(NULL, conn, (char *)buf, (int)len64)) >= 0) { nread += n; } else { nread = ((nread > 0) ? nread : n); } } return (int)nread; } static char mg_getc(struct mg_connection *conn) { char c; if (conn == NULL) { return 0; } if (mg_read_inner(conn, &c, 1) <= 0) { return (char)0; } return c; } int mg_read(struct mg_connection *conn, void *buf, size_t len) { if (len > INT_MAX) { len = INT_MAX; } if (conn == NULL) { return 0; } if (conn->is_chunked) { size_t all_read = 0; while (len > 0) { if (conn->is_chunked == 3) { /* No more data left to read */ return 0; } if (conn->chunk_remainder) { /* copy from the remainder of the last received chunk */ long read_ret; size_t read_now = ((conn->chunk_remainder > len) ? (len) : (conn->chunk_remainder)); conn->content_len += (int)read_now; read_ret = mg_read_inner(conn, (char *)buf + all_read, read_now); if (read_ret < 1) { /* read error */ return -1; } all_read += (size_t)read_ret; conn->chunk_remainder -= (size_t)read_ret; len -= (size_t)read_ret; if (conn->chunk_remainder == 0) { /* Add data bytes in the current chunk have been read, * so we are expecting \r\n now. */ char x1, x2; conn->content_len += 2; x1 = mg_getc(conn); x2 = mg_getc(conn); if ((x1 != '\r') || (x2 != '\n')) { /* Protocol violation */ return -1; } } } else { /* fetch a new chunk */ int i = 0; char lenbuf[64]; char *end = 0; unsigned long chunkSize = 0; for (i = 0; i < ((int)sizeof(lenbuf) - 1); i++) { conn->content_len++; lenbuf[i] = mg_getc(conn); if ((i > 0) && (lenbuf[i] == '\r') && (lenbuf[i - 1] != '\r')) { continue; } if ((i > 1) && (lenbuf[i] == '\n') && (lenbuf[i - 1] == '\r')) { lenbuf[i + 1] = 0; chunkSize = strtoul(lenbuf, &end, 16); if (chunkSize == 0) { /* regular end of content */ conn->is_chunked = 3; } break; } if (!isxdigit(lenbuf[i])) { /* illegal character for chunk length */ return -1; } } if ((end == NULL) || (*end != '\r')) { /* chunksize not set correctly */ return -1; } if (chunkSize == 0) { break; } conn->chunk_remainder = chunkSize; } } return (int)all_read; } return mg_read_inner(conn, buf, len); } int mg_write(struct mg_connection *conn, const void *buf, size_t len) { time_t now; int64_t n, total, allowed; if (conn == NULL) { return 0; } if (conn->throttle > 0) { if ((now = time(NULL)) != conn->last_throttle_time) { conn->last_throttle_time = now; conn->last_throttle_bytes = 0; } allowed = conn->throttle - conn->last_throttle_bytes; if (allowed > (int64_t)len) { allowed = (int64_t)len; } if ((total = push_all(conn->phys_ctx, NULL, conn->client.sock, conn->ssl, (const char *)buf, (int64_t)allowed)) == allowed) { buf = (const char *)buf + total; conn->last_throttle_bytes += total; while ((total < (int64_t)len) && (conn->phys_ctx->stop_flag == 0)) { allowed = (conn->throttle > ((int64_t)len - total)) ? (int64_t)len - total : conn->throttle; if ((n = push_all(conn->phys_ctx, NULL, conn->client.sock, conn->ssl, (const char *)buf, (int64_t)allowed)) != allowed) { break; } sleep(1); conn->last_throttle_bytes = allowed; conn->last_throttle_time = time(NULL); buf = (const char *)buf + n; total += n; } } } else { total = push_all(conn->phys_ctx, NULL, conn->client.sock, conn->ssl, (const char *)buf, (int64_t)len); } if (total > 0) { conn->num_bytes_sent += total; } return (int)total; } /* Send a chunk, if "Transfer-Encoding: chunked" is used */ int mg_send_chunk(struct mg_connection *conn, const char *chunk, unsigned int chunk_len) { char lenbuf[16]; size_t lenbuf_len; int ret; int t; /* First store the length information in a text buffer. */ sprintf(lenbuf, "%x\r\n", chunk_len); lenbuf_len = strlen(lenbuf); /* Then send length information, chunk and terminating \r\n. */ ret = mg_write(conn, lenbuf, lenbuf_len); if (ret != (int)lenbuf_len) { return -1; } t = ret; ret = mg_write(conn, chunk, chunk_len); if (ret != (int)chunk_len) { return -1; } t += ret; ret = mg_write(conn, "\r\n", 2); if (ret != 2) { return -1; } t += ret; return t; } #if defined(__GNUC__) || defined(__MINGW32__) /* This block forwards format strings to printf implementations, * so we need to disable the format-nonliteral warning. */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wformat-nonliteral" #endif /* Alternative alloc_vprintf() for non-compliant C runtimes */ static int alloc_vprintf2(char **buf, const char *fmt, va_list ap) { va_list ap_copy; size_t size = MG_BUF_LEN / 4; int len = -1; *buf = NULL; while (len < 0) { if (*buf) { mg_free(*buf); } size *= 4; *buf = (char *)mg_malloc(size); if (!*buf) { break; } va_copy(ap_copy, ap); len = vsnprintf_impl(*buf, size - 1, fmt, ap_copy); va_end(ap_copy); (*buf)[size - 1] = 0; } return len; } /* Print message to buffer. If buffer is large enough to hold the message, * return buffer. If buffer is to small, allocate large enough buffer on * heap, * and return allocated buffer. */ static int alloc_vprintf(char **out_buf, char *prealloc_buf, size_t prealloc_size, const char *fmt, va_list ap) { va_list ap_copy; int len; /* Windows is not standard-compliant, and vsnprintf() returns -1 if * buffer is too small. Also, older versions of msvcrt.dll do not have * _vscprintf(). However, if size is 0, vsnprintf() behaves correctly. * Therefore, we make two passes: on first pass, get required message * length. * On second pass, actually print the message. */ va_copy(ap_copy, ap); len = vsnprintf_impl(NULL, 0, fmt, ap_copy); va_end(ap_copy); if (len < 0) { /* C runtime is not standard compliant, vsnprintf() returned -1. * Switch to alternative code path that uses incremental * allocations. */ va_copy(ap_copy, ap); len = alloc_vprintf2(out_buf, fmt, ap_copy); va_end(ap_copy); } else if ((size_t)(len) >= prealloc_size) { /* The pre-allocated buffer not large enough. */ /* Allocate a new buffer. */ *out_buf = (char *)mg_malloc((size_t)(len) + 1); if (!*out_buf) { /* Allocation failed. Return -1 as "out of memory" error. */ return -1; } /* Buffer allocation successful. Store the string there. */ va_copy(ap_copy, ap); IGNORE_UNUSED_RESULT( vsnprintf_impl(*out_buf, (size_t)(len) + 1, fmt, ap_copy)); va_end(ap_copy); } else { /* The pre-allocated buffer is large enough. * Use it to store the string and return the address. */ va_copy(ap_copy, ap); IGNORE_UNUSED_RESULT( vsnprintf_impl(prealloc_buf, prealloc_size, fmt, ap_copy)); va_end(ap_copy); *out_buf = prealloc_buf; } return len; } #if defined(__GNUC__) || defined(__MINGW32__) /* Enable format-nonliteral warning again. */ #pragma GCC diagnostic pop #endif static int mg_vprintf(struct mg_connection *conn, const char *fmt, va_list ap) { char mem[MG_BUF_LEN]; char *buf = NULL; int len; if ((len = alloc_vprintf(&buf, mem, sizeof(mem), fmt, ap)) > 0) { len = mg_write(conn, buf, (size_t)len); } if ((buf != mem) && (buf != NULL)) { mg_free(buf); } return len; } int mg_printf(struct mg_connection *conn, const char *fmt, ...) { va_list ap; int result; va_start(ap, fmt); result = mg_vprintf(conn, fmt, ap); va_end(ap); return result; } int mg_url_decode(const char *src, int src_len, char *dst, int dst_len, int is_form_url_encoded) { int i, j, a, b; #define HEXTOI(x) (isdigit(x) ? (x - '0') : (x - 'W')) for (i = j = 0; (i < src_len) && (j < (dst_len - 1)); i++, j++) { if ((i < src_len - 2) && (src[i] == '%') && isxdigit(*(const unsigned char *)(src + i + 1)) && isxdigit(*(const unsigned char *)(src + i + 2))) { a = tolower(*(const unsigned char *)(src + i + 1)); b = tolower(*(const unsigned char *)(src + i + 2)); dst[j] = (char)((HEXTOI(a) << 4) | HEXTOI(b)); i += 2; } else if (is_form_url_encoded && (src[i] == '+')) { dst[j] = ' '; } else { dst[j] = src[i]; } } dst[j] = '\0'; /* Null-terminate the destination */ return (i >= src_len) ? j : -1; } int mg_get_var(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len) { return mg_get_var2(data, data_len, name, dst, dst_len, 0); } int mg_get_var2(const char *data, size_t data_len, const char *name, char *dst, size_t dst_len, size_t occurrence) { const char *p, *e, *s; size_t name_len; int len; if ((dst == NULL) || (dst_len == 0)) { len = -2; } else if ((data == NULL) || (name == NULL) || (data_len == 0)) { len = -1; dst[0] = '\0'; } else { name_len = strlen(name); e = data + data_len; len = -1; dst[0] = '\0'; /* data is "var1=val1&var2=val2...". Find variable first */ for (p = data; p + name_len < e; p++) { if (((p == data) || (p[-1] == '&')) && (p[name_len] == '=') && !mg_strncasecmp(name, p, name_len) && 0 == occurrence--) { /* Point p to variable value */ p += name_len + 1; /* Point s to the end of the value */ s = (const char *)memchr(p, '&', (size_t)(e - p)); if (s == NULL) { s = e; } DEBUG_ASSERT(s >= p); if (s < p) { return -3; } /* Decode variable into destination buffer */ len = mg_url_decode(p, (int)(s - p), dst, (int)dst_len, 1); /* Redirect error code from -1 to -2 (destination buffer too * small). */ if (len == -1) { len = -2; } break; } } } return len; } /* HCP24: some changes to compare hole var_name */ int mg_get_cookie(const char *cookie_header, const char *var_name, char *dst, size_t dst_size) { const char *s, *p, *end; int name_len, len = -1; if ((dst == NULL) || (dst_size == 0)) { return -2; } dst[0] = '\0'; if ((var_name == NULL) || ((s = cookie_header) == NULL)) { return -1; } name_len = (int)strlen(var_name); end = s + strlen(s); for (; (s = mg_strcasestr(s, var_name)) != NULL; s += name_len) { if (s[name_len] == '=') { /* HCP24: now check is it a substring or a full cookie name */ if ((s == cookie_header) || (s[-1] == ' ')) { s += name_len + 1; if ((p = strchr(s, ' ')) == NULL) { p = end; } if (p[-1] == ';') { p--; } if ((*s == '"') && (p[-1] == '"') && (p > s + 1)) { s++; p--; } if ((size_t)(p - s) < dst_size) { len = (int)(p - s); mg_strlcpy(dst, s, (size_t)len + 1); } else { len = -3; } break; } } } return len; } #if defined(USE_WEBSOCKET) || defined(USE_LUA) static void base64_encode(const unsigned char *src, int src_len, char *dst) { static const char *b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; int i, j, a, b, c; for (i = j = 0; i < src_len; i += 3) { a = src[i]; b = ((i + 1) >= src_len) ? 0 : src[i + 1]; c = ((i + 2) >= src_len) ? 0 : src[i + 2]; dst[j++] = b64[a >> 2]; dst[j++] = b64[((a & 3) << 4) | (b >> 4)]; if (i + 1 < src_len) { dst[j++] = b64[(b & 15) << 2 | (c >> 6)]; } if (i + 2 < src_len) { dst[j++] = b64[c & 63]; } } while (j % 4 != 0) { dst[j++] = '='; } dst[j++] = '\0'; } #endif #if defined(USE_LUA) static unsigned char b64reverse(char letter) { if ((letter >= 'A') && (letter <= 'Z')) { return letter - 'A'; } if ((letter >= 'a') && (letter <= 'z')) { return letter - 'a' + 26; } if ((letter >= '0') && (letter <= '9')) { return letter - '0' + 52; } if (letter == '+') { return 62; } if (letter == '/') { return 63; } if (letter == '=') { return 255; /* normal end */ } return 254; /* error */ } static int base64_decode(const unsigned char *src, int src_len, char *dst, size_t *dst_len) { int i; unsigned char a, b, c, d; *dst_len = 0; for (i = 0; i < src_len; i += 4) { a = b64reverse(src[i]); if (a >= 254) { return i; } b = b64reverse(((i + 1) >= src_len) ? 0 : src[i + 1]); if (b >= 254) { return i + 1; } c = b64reverse(((i + 2) >= src_len) ? 0 : src[i + 2]); if (c == 254) { return i + 2; } d = b64reverse(((i + 3) >= src_len) ? 0 : src[i + 3]); if (d == 254) { return i + 3; } dst[(*dst_len)++] = (a << 2) + (b >> 4); if (c != 255) { dst[(*dst_len)++] = (b << 4) + (c >> 2); if (d != 255) { dst[(*dst_len)++] = (c << 6) + d; } } } return -1; } #endif static int is_put_or_delete_method(const struct mg_connection *conn) { if (conn) { const char *s = conn->request_info.request_method; return (s != NULL) && (!strcmp(s, "PUT") || !strcmp(s, "DELETE") || !strcmp(s, "MKCOL") || !strcmp(s, "PATCH")); } return 0; } #if !defined(NO_FILES) static int extention_matches_script( struct mg_connection *conn, /* in: request (must be valid) */ const char *filename /* in: filename (must be valid) */ ) { #if !defined(NO_CGI) if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS], strlen(conn->dom_ctx->config[CGI_EXTENSIONS]), filename) > 0) { return 1; } #endif #if defined(USE_LUA) if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], strlen(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]), filename) > 0) { return 1; } #endif #if defined(USE_DUKTAPE) if (match_prefix(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]), filename) > 0) { return 1; } #endif /* filename and conn could be unused, if all preocessor conditions * are false (no script language supported). */ (void)filename; (void)conn; return 0; } /* For given directory path, substitute it to valid index file. * Return 1 if index file has been found, 0 if not found. * If the file is found, it's stats is returned in stp. */ static int substitute_index_file(struct mg_connection *conn, char *path, size_t path_len, struct mg_file_stat *filestat) { const char *list = conn->dom_ctx->config[INDEX_FILES]; struct vec filename_vec; size_t n = strlen(path); int found = 0; /* The 'path' given to us points to the directory. Remove all trailing * directory separator characters from the end of the path, and * then append single directory separator character. */ while ((n > 0) && (path[n - 1] == '/')) { n--; } path[n] = '/'; /* Traverse index files list. For each entry, append it to the given * path and see if the file exists. If it exists, break the loop */ while ((list = next_option(list, &filename_vec, NULL)) != NULL) { /* Ignore too long entries that may overflow path buffer */ if ((filename_vec.len + 1) > (path_len - (n + 1))) { continue; } /* Prepare full path to the index file */ mg_strlcpy(path + n + 1, filename_vec.ptr, filename_vec.len + 1); /* Does it exist? */ if (mg_stat(conn, path, filestat)) { /* Yes it does, break the loop */ found = 1; break; } } /* If no index file exists, restore directory path */ if (!found) { path[n] = '\0'; } return found; } #endif static void interpret_uri(struct mg_connection *conn, /* in/out: request (must be valid) */ char *filename, /* out: filename */ size_t filename_buf_len, /* in: size of filename buffer */ struct mg_file_stat *filestat, /* out: file status structure */ int *is_found, /* out: file found (directly) */ int *is_script_resource, /* out: handled by a script? */ int *is_websocket_request, /* out: websocket connetion? */ int *is_put_or_delete_request /* out: put/delete a file? */ ) { char const *accept_encoding; #if !defined(NO_FILES) const char *uri = conn->request_info.local_uri; const char *root = conn->dom_ctx->config[DOCUMENT_ROOT]; const char *rewrite; struct vec a, b; ptrdiff_t match_len; char gz_path[PATH_MAX]; int truncated; #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) char *tmp_str; size_t tmp_str_len, sep_pos; int allow_substitute_script_subresources; #endif #else (void)filename_buf_len; /* unused if NO_FILES is defined */ #endif /* Step 1: Set all initially unknown outputs to zero */ memset(filestat, 0, sizeof(*filestat)); *filename = 0; *is_found = 0; *is_script_resource = 0; /* Step 2: Check if the request attempts to modify the file system */ *is_put_or_delete_request = is_put_or_delete_method(conn); /* Step 3: Check if it is a websocket request, and modify the document * root if required */ #if defined(USE_WEBSOCKET) *is_websocket_request = is_websocket_protocol(conn); #if !defined(NO_FILES) if (*is_websocket_request && conn->dom_ctx->config[WEBSOCKET_ROOT]) { root = conn->dom_ctx->config[WEBSOCKET_ROOT]; } #endif /* !NO_FILES */ #else /* USE_WEBSOCKET */ *is_websocket_request = 0; #endif /* USE_WEBSOCKET */ /* Step 4: Check if gzip encoded response is allowed */ conn->accept_gzip = 0; if ((accept_encoding = mg_get_header(conn, "Accept-Encoding")) != NULL) { if (strstr(accept_encoding, "gzip") != NULL) { conn->accept_gzip = 1; } } #if !defined(NO_FILES) /* Step 5: If there is no root directory, don't look for files. */ /* Note that root == NULL is a regular use case here. This occurs, * if all requests are handled by callbacks, so the WEBSOCKET_ROOT * config is not required. */ if (root == NULL) { /* all file related outputs have already been set to 0, just return */ return; } /* Step 6: Determine the local file path from the root path and the * request uri. */ /* Using filename_buf_len - 1 because memmove() for PATH_INFO may shift * part of the path one byte on the right. */ mg_snprintf( conn, &truncated, filename, filename_buf_len - 1, "%s%s", root, uri); if (truncated) { goto interpret_cleanup; } /* Step 7: URI rewriting */ rewrite = conn->dom_ctx->config[URL_REWRITE_PATTERN]; while ((rewrite = next_option(rewrite, &a, &b)) != NULL) { if ((match_len = match_prefix(a.ptr, a.len, uri)) > 0) { mg_snprintf(conn, &truncated, filename, filename_buf_len - 1, "%.*s%s", (int)b.len, b.ptr, uri + match_len); break; } } if (truncated) { goto interpret_cleanup; } /* Step 8: Check if the file exists at the server */ /* Local file path and name, corresponding to requested URI * is now stored in "filename" variable. */ if (mg_stat(conn, filename, filestat)) { int uri_len = (int)strlen(uri); int is_uri_end_slash = (uri_len > 0) && (uri[uri_len - 1] == '/'); /* 8.1: File exists. */ *is_found = 1; /* 8.2: Check if it is a script type. */ if (extention_matches_script(conn, filename)) { /* The request addresses a CGI resource, Lua script or * server-side javascript. * The URI corresponds to the script itself (like * /path/script.cgi), and there is no additional resource * path (like /path/script.cgi/something). * Requests that modify (replace or delete) a resource, like * PUT and DELETE requests, should replace/delete the script * file. * Requests that read or write from/to a resource, like GET and * POST requests, should call the script and return the * generated response. */ *is_script_resource = (!*is_put_or_delete_request); } /* 8.3: If the request target is a directory, there could be * a substitute file (index.html, index.cgi, ...). */ if (filestat->is_directory && is_uri_end_slash) { /* Use a local copy here, since substitute_index_file will * change the content of the file status */ struct mg_file_stat tmp_filestat; memset(&tmp_filestat, 0, sizeof(tmp_filestat)); if (substitute_index_file( conn, filename, filename_buf_len, &tmp_filestat)) { /* Substitute file found. Copy stat to the output, then * check if the file is a script file */ *filestat = tmp_filestat; if (extention_matches_script(conn, filename)) { /* Substitute file is a script file */ *is_script_resource = 1; } else { /* Substitute file is a regular file */ *is_script_resource = 0; *is_found = (mg_stat(conn, filename, filestat) ? 1 : 0); } } /* If there is no substitute file, the server could return * a directory listing in a later step */ } return; } /* Step 9: Check for zipped files: */ /* If we can't find the actual file, look for the file * with the same name but a .gz extension. If we find it, * use that and set the gzipped flag in the file struct * to indicate that the response need to have the content- * encoding: gzip header. * We can only do this if the browser declares support. */ if (conn->accept_gzip) { mg_snprintf( conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", filename); if (truncated) { goto interpret_cleanup; } if (mg_stat(conn, gz_path, filestat)) { if (filestat) { filestat->is_gzipped = 1; *is_found = 1; } /* Currently gz files can not be scripts. */ return; } } #if !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) /* Step 10: Script resources may handle sub-resources */ /* Support PATH_INFO for CGI scripts. */ tmp_str_len = strlen(filename); tmp_str = (char *)mg_malloc_ctx(tmp_str_len + PATH_MAX + 1, conn->phys_ctx); if (!tmp_str) { /* Out of memory */ goto interpret_cleanup; } memcpy(tmp_str, filename, tmp_str_len + 1); /* Check config, if index scripts may have sub-resources */ allow_substitute_script_subresources = !mg_strcasecmp(conn->dom_ctx->config[ALLOW_INDEX_SCRIPT_SUB_RES], "yes"); sep_pos = tmp_str_len; while (sep_pos > 0) { sep_pos--; if (tmp_str[sep_pos] == '/') { int is_script = 0, does_exist = 0; tmp_str[sep_pos] = 0; if (tmp_str[0]) { is_script = extention_matches_script(conn, tmp_str); does_exist = mg_stat(conn, tmp_str, filestat); } if (does_exist && is_script) { filename[sep_pos] = 0; memmove(filename + sep_pos + 2, filename + sep_pos + 1, strlen(filename + sep_pos + 1) + 1); conn->path_info = filename + sep_pos + 1; filename[sep_pos + 1] = '/'; *is_script_resource = 1; *is_found = 1; break; } if (allow_substitute_script_subresources) { if (substitute_index_file( conn, tmp_str, tmp_str_len + PATH_MAX, filestat)) { /* some intermediate directory has an index file */ if (extention_matches_script(conn, tmp_str)) { char *tmp_str2; DEBUG_TRACE("Substitute script %s serving path %s", tmp_str, filename); /* this index file is a script */ tmp_str2 = mg_strdup_ctx(filename + sep_pos + 1, conn->phys_ctx); mg_snprintf(conn, &truncated, filename, filename_buf_len, "%s//%s", tmp_str, tmp_str2); mg_free(tmp_str2); if (truncated) { mg_free(tmp_str); goto interpret_cleanup; } sep_pos = strlen(tmp_str); filename[sep_pos] = 0; conn->path_info = filename + sep_pos + 1; *is_script_resource = 1; *is_found = 1; break; } else { DEBUG_TRACE("Substitute file %s serving path %s", tmp_str, filename); /* non-script files will not have sub-resources */ filename[sep_pos] = 0; conn->path_info = 0; *is_script_resource = 0; *is_found = 0; break; } } } tmp_str[sep_pos] = '/'; } } mg_free(tmp_str); #endif /* !defined(NO_CGI) || defined(USE_LUA) || defined(USE_DUKTAPE) */ #endif /* !defined(NO_FILES) */ return; #if !defined(NO_FILES) /* Reset all outputs */ interpret_cleanup: memset(filestat, 0, sizeof(*filestat)); *filename = 0; *is_found = 0; *is_script_resource = 0; *is_websocket_request = 0; *is_put_or_delete_request = 0; #endif /* !defined(NO_FILES) */ } /* Check whether full request is buffered. Return: * -1 if request or response is malformed * 0 if request or response is not yet fully buffered * >0 actual request length, including last \r\n\r\n */ static int get_http_header_len(const char *buf, int buflen) { int i; for (i = 0; i < buflen; i++) { /* Do an unsigned comparison in some conditions below */ const unsigned char c = ((const unsigned char *)buf)[i]; if ((c < 128) && ((char)c != '\r') && ((char)c != '\n') && !isprint(c)) { /* abort scan as soon as one malformed character is found */ return -1; } if (i < buflen - 1) { if ((buf[i] == '\n') && (buf[i + 1] == '\n')) { /* Two newline, no carriage return - not standard compliant, * but * it * should be accepted */ return i + 2; } } if (i < buflen - 3) { if ((buf[i] == '\r') && (buf[i + 1] == '\n') && (buf[i + 2] == '\r') && (buf[i + 3] == '\n')) { /* Two \r\n - standard compliant */ return i + 4; } } } return 0; } #if !defined(NO_CACHING) /* Convert month to the month number. Return -1 on error, or month number */ static int get_month_index(const char *s) { size_t i; for (i = 0; i < ARRAY_SIZE(month_names); i++) { if (!strcmp(s, month_names[i])) { return (int)i; } } return -1; } /* Parse UTC date-time string, and return the corresponding time_t value. */ static time_t parse_date_string(const char *datetime) { char month_str[32] = {0}; int second, minute, hour, day, month, year; time_t result = (time_t)0; struct tm tm; if ((sscanf(datetime, "%d/%3s/%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%*3s, %d %3s %d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6) || (sscanf(datetime, "%d-%3s-%d %d:%d:%d", &day, month_str, &year, &hour, &minute, &second) == 6)) { month = get_month_index(month_str); if ((month >= 0) && (year >= 1970)) { memset(&tm, 0, sizeof(tm)); tm.tm_year = year - 1900; tm.tm_mon = month; tm.tm_mday = day; tm.tm_hour = hour; tm.tm_min = minute; tm.tm_sec = second; result = timegm(&tm); } } return result; } #endif /* !NO_CACHING */ /* Protect against directory disclosure attack by removing '..', * excessive '/' and '\' characters */ static void remove_double_dots_and_double_slashes(char *s) { char *p = s; while ((s[0] == '.') && (s[1] == '.')) { s++; } while (*s != '\0') { *p++ = *s++; if ((s[-1] == '/') || (s[-1] == '\\')) { /* Skip all following slashes, backslashes and double-dots */ while (s[0] != '\0') { if ((s[0] == '/') || (s[0] == '\\')) { s++; } else if ((s[0] == '.') && (s[1] == '.')) { s += 2; } else { break; } } } } *p = '\0'; } static const struct { const char *extension; size_t ext_len; const char *mime_type; } builtin_mime_types[] = { /* IANA registered MIME types * (http://www.iana.org/assignments/media-types) * application types */ {".doc", 4, "application/msword"}, {".eps", 4, "application/postscript"}, {".exe", 4, "application/octet-stream"}, {".js", 3, "application/javascript"}, {".json", 5, "application/json"}, {".pdf", 4, "application/pdf"}, {".ps", 3, "application/postscript"}, {".rtf", 4, "application/rtf"}, {".xhtml", 6, "application/xhtml+xml"}, {".xsl", 4, "application/xml"}, {".xslt", 5, "application/xml"}, /* fonts */ {".ttf", 4, "application/font-sfnt"}, {".cff", 4, "application/font-sfnt"}, {".otf", 4, "application/font-sfnt"}, {".aat", 4, "application/font-sfnt"}, {".sil", 4, "application/font-sfnt"}, {".pfr", 4, "application/font-tdpfr"}, {".woff", 5, "application/font-woff"}, /* audio */ {".mp3", 4, "audio/mpeg"}, {".oga", 4, "audio/ogg"}, {".ogg", 4, "audio/ogg"}, /* image */ {".gif", 4, "image/gif"}, {".ief", 4, "image/ief"}, {".jpeg", 5, "image/jpeg"}, {".jpg", 4, "image/jpeg"}, {".jpm", 4, "image/jpm"}, {".jpx", 4, "image/jpx"}, {".png", 4, "image/png"}, {".svg", 4, "image/svg+xml"}, {".tif", 4, "image/tiff"}, {".tiff", 5, "image/tiff"}, /* model */ {".wrl", 4, "model/vrml"}, /* text */ {".css", 4, "text/css"}, {".csv", 4, "text/csv"}, {".htm", 4, "text/html"}, {".html", 5, "text/html"}, {".sgm", 4, "text/sgml"}, {".shtm", 5, "text/html"}, {".shtml", 6, "text/html"}, {".txt", 4, "text/plain"}, {".xml", 4, "text/xml"}, /* video */ {".mov", 4, "video/quicktime"}, {".mp4", 4, "video/mp4"}, {".mpeg", 5, "video/mpeg"}, {".mpg", 4, "video/mpeg"}, {".ogv", 4, "video/ogg"}, {".qt", 3, "video/quicktime"}, /* not registered types * (http://reference.sitepoint.com/html/mime-types-full, * http://www.hansenb.pdx.edu/DMKB/dict/tutorials/mime_typ.php, ..) */ {".arj", 4, "application/x-arj-compressed"}, {".gz", 3, "application/x-gunzip"}, {".rar", 4, "application/x-arj-compressed"}, {".swf", 4, "application/x-shockwave-flash"}, {".tar", 4, "application/x-tar"}, {".tgz", 4, "application/x-tar-gz"}, {".torrent", 8, "application/x-bittorrent"}, {".ppt", 4, "application/x-mspowerpoint"}, {".xls", 4, "application/x-msexcel"}, {".zip", 4, "application/x-zip-compressed"}, {".aac", 4, "audio/aac"}, /* http://en.wikipedia.org/wiki/Advanced_Audio_Coding */ {".aif", 4, "audio/x-aif"}, {".m3u", 4, "audio/x-mpegurl"}, {".mid", 4, "audio/x-midi"}, {".ra", 3, "audio/x-pn-realaudio"}, {".ram", 4, "audio/x-pn-realaudio"}, {".wav", 4, "audio/x-wav"}, {".bmp", 4, "image/bmp"}, {".ico", 4, "image/x-icon"}, {".pct", 4, "image/x-pct"}, {".pict", 5, "image/pict"}, {".rgb", 4, "image/x-rgb"}, {".webm", 5, "video/webm"}, /* http://en.wikipedia.org/wiki/WebM */ {".asf", 4, "video/x-ms-asf"}, {".avi", 4, "video/x-msvideo"}, {".m4v", 4, "video/x-m4v"}, {NULL, 0, NULL}}; const char * mg_get_builtin_mime_type(const char *path) { const char *ext; size_t i, path_len; path_len = strlen(path); for (i = 0; builtin_mime_types[i].extension != NULL; i++) { ext = path + (path_len - builtin_mime_types[i].ext_len); if ((path_len > builtin_mime_types[i].ext_len) && (mg_strcasecmp(ext, builtin_mime_types[i].extension) == 0)) { return builtin_mime_types[i].mime_type; } } return "text/plain"; } /* Look at the "path" extension and figure what mime type it has. * Store mime type in the vector. */ static void get_mime_type(struct mg_connection *conn, const char *path, struct vec *vec) { struct vec ext_vec, mime_vec; const char *list, *ext; size_t path_len; path_len = strlen(path); if ((conn == NULL) || (vec == NULL)) { if (vec != NULL) { memset(vec, '\0', sizeof(struct vec)); } return; } /* Scan user-defined mime types first, in case user wants to * override default mime types. */ list = conn->dom_ctx->config[EXTRA_MIME_TYPES]; while ((list = next_option(list, &ext_vec, &mime_vec)) != NULL) { /* ext now points to the path suffix */ ext = path + path_len - ext_vec.len; if (mg_strncasecmp(ext, ext_vec.ptr, ext_vec.len) == 0) { *vec = mime_vec; return; } } vec->ptr = mg_get_builtin_mime_type(path); vec->len = strlen(vec->ptr); } /* Stringify binary data. Output buffer must be twice as big as input, * because each byte takes 2 bytes in string representation */ static void bin2str(char *to, const unsigned char *p, size_t len) { static const char *hex = "0123456789abcdef"; for (; len--; p++) { *to++ = hex[p[0] >> 4]; *to++ = hex[p[0] & 0x0f]; } *to = '\0'; } /* Return stringified MD5 hash for list of strings. Buffer must be 33 bytes. */ char * mg_md5(char buf[33], ...) { md5_byte_t hash[16]; const char *p; va_list ap; md5_state_t ctx; md5_init(&ctx); va_start(ap, buf); while ((p = va_arg(ap, const char *)) != NULL) { md5_append(&ctx, (const md5_byte_t *)p, strlen(p)); } va_end(ap); md5_finish(&ctx, hash); bin2str(buf, hash, sizeof(hash)); return buf; } /* Check the user's password, return 1 if OK */ static int check_password(const char *method, const char *ha1, const char *uri, const char *nonce, const char *nc, const char *cnonce, const char *qop, const char *response) { char ha2[32 + 1], expected_response[32 + 1]; /* Some of the parameters may be NULL */ if ((method == NULL) || (nonce == NULL) || (nc == NULL) || (cnonce == NULL) || (qop == NULL) || (response == NULL)) { return 0; } /* NOTE(lsm): due to a bug in MSIE, we do not compare the URI */ if (strlen(response) != 32) { return 0; } mg_md5(ha2, method, ":", uri, NULL); mg_md5(expected_response, ha1, ":", nonce, ":", nc, ":", cnonce, ":", qop, ":", ha2, NULL); return mg_strcasecmp(response, expected_response) == 0; } /* Use the global passwords file, if specified by auth_gpass option, * or search for .htpasswd in the requested directory. */ static void open_auth_file(struct mg_connection *conn, const char *path, struct mg_file *filep) { if ((conn != NULL) && (conn->dom_ctx != NULL)) { char name[PATH_MAX]; const char *p, *e, *gpass = conn->dom_ctx->config[GLOBAL_PASSWORDS_FILE]; int truncated; if (gpass != NULL) { /* Use global passwords file */ if (!mg_fopen(conn, gpass, MG_FOPEN_MODE_READ, filep)) { #if defined(DEBUG) /* Use mg_cry_internal here, since gpass has been configured. */ mg_cry_internal(conn, "fopen(%s): %s", gpass, strerror(ERRNO)); #endif } /* Important: using local struct mg_file to test path for * is_directory flag. If filep is used, mg_stat() makes it * appear as if auth file was opened. * TODO(mid): Check if this is still required after rewriting * mg_stat */ } else if (mg_stat(conn, path, &filep->stat) && filep->stat.is_directory) { mg_snprintf(conn, &truncated, name, sizeof(name), "%s/%s", path, PASSWORDS_FILE_NAME); if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) { #if defined(DEBUG) /* Don't use mg_cry_internal here, but only a trace, since this * is * a typical case. It will occur for every directory * without a password file. */ DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO)); #endif } } else { /* Try to find .htpasswd in requested directory. */ for (p = path, e = p + strlen(p) - 1; e > p; e--) { if (e[0] == '/') { break; } } mg_snprintf(conn, &truncated, name, sizeof(name), "%.*s/%s", (int)(e - p), p, PASSWORDS_FILE_NAME); if (truncated || !mg_fopen(conn, name, MG_FOPEN_MODE_READ, filep)) { #if defined(DEBUG) /* Don't use mg_cry_internal here, but only a trace, since this * is * a typical case. It will occur for every directory * without a password file. */ DEBUG_TRACE("fopen(%s): %s", name, strerror(ERRNO)); #endif } } } } /* Parsed Authorization header */ struct ah { char *user, *uri, *cnonce, *response, *qop, *nc, *nonce; }; /* Return 1 on success. Always initializes the ah structure. */ static int parse_auth_header(struct mg_connection *conn, char *buf, size_t buf_size, struct ah *ah) { char *name, *value, *s; const char *auth_header; uint64_t nonce; if (!ah || !conn) { return 0; } (void)memset(ah, 0, sizeof(*ah)); if (((auth_header = mg_get_header(conn, "Authorization")) == NULL) || mg_strncasecmp(auth_header, "Digest ", 7) != 0) { return 0; } /* Make modifiable copy of the auth header */ (void)mg_strlcpy(buf, auth_header + 7, buf_size); s = buf; /* Parse authorization header */ for (;;) { /* Gobble initial spaces */ while (isspace(*(unsigned char *)s)) { s++; } name = skip_quoted(&s, "=", " ", 0); /* Value is either quote-delimited, or ends at first comma or space. */ if (s[0] == '\"') { s++; value = skip_quoted(&s, "\"", " ", '\\'); if (s[0] == ',') { s++; } } else { value = skip_quoted(&s, ", ", " ", 0); /* IE uses commas, FF uses * spaces */ } if (*name == '\0') { break; } if (!strcmp(name, "username")) { ah->user = value; } else if (!strcmp(name, "cnonce")) { ah->cnonce = value; } else if (!strcmp(name, "response")) { ah->response = value; } else if (!strcmp(name, "uri")) { ah->uri = value; } else if (!strcmp(name, "qop")) { ah->qop = value; } else if (!strcmp(name, "nc")) { ah->nc = value; } else if (!strcmp(name, "nonce")) { ah->nonce = value; } } #if !defined(NO_NONCE_CHECK) /* Read the nonce from the response. */ if (ah->nonce == NULL) { return 0; } s = NULL; nonce = strtoull(ah->nonce, &s, 10); if ((s == NULL) || (*s != 0)) { return 0; } /* Convert the nonce from the client to a number. */ nonce ^= conn->dom_ctx->auth_nonce_mask; /* The converted number corresponds to the time the nounce has been * created. This should not be earlier than the server start. */ /* Server side nonce check is valuable in all situations but one: * if the server restarts frequently, but the client should not see * that, so the server should accept nonces from previous starts. */ /* However, the reasonable default is to not accept a nonce from a * previous start, so if anyone changed the access rights between * two restarts, a new login is required. */ if (nonce < (uint64_t)conn->phys_ctx->start_time) { /* nonce is from a previous start of the server and no longer valid * (replay attack?) */ return 0; } /* Check if the nonce is too high, so it has not (yet) been used by the * server. */ if (nonce >= ((uint64_t)conn->phys_ctx->start_time + conn->dom_ctx->nonce_count)) { return 0; } #else (void)nonce; #endif /* CGI needs it as REMOTE_USER */ if (ah->user != NULL) { conn->request_info.remote_user = mg_strdup_ctx(ah->user, conn->phys_ctx); } else { return 0; } return 1; } static const char * mg_fgets(char *buf, size_t size, struct mg_file *filep, char **p) { #if defined(MG_USE_OPEN_FILE) const char *eof; size_t len; const char *memend; #else (void)p; /* parameter is unused */ #endif if (!filep) { return NULL; } #if defined(MG_USE_OPEN_FILE) if ((filep->access.membuf != NULL) && (*p != NULL)) { memend = (const char *)&filep->access.membuf[filep->stat.size]; /* Search for \n from p till the end of stream */ eof = (char *)memchr(*p, '\n', (size_t)(memend - *p)); if (eof != NULL) { eof += 1; /* Include \n */ } else { eof = memend; /* Copy remaining data */ } len = ((size_t)(eof - *p) > (size - 1)) ? (size - 1) : (size_t)(eof - *p); memcpy(buf, *p, len); buf[len] = '\0'; *p += len; return len ? eof : NULL; } else /* filep->access.fp block below */ #endif if (filep->access.fp != NULL) { return fgets(buf, (int)size, filep->access.fp); } else { return NULL; } } /* Define the initial recursion depth for procesesing htpasswd files that * include other htpasswd * (or even the same) files. It is not difficult to provide a file or files * s.t. they force civetweb * to infinitely recurse and then crash. */ #define INITIAL_DEPTH 9 #if INITIAL_DEPTH <= 0 #error Bad INITIAL_DEPTH for recursion, set to at least 1 #endif struct read_auth_file_struct { struct mg_connection *conn; struct ah ah; const char *domain; char buf[256 + 256 + 40]; const char *f_user; const char *f_domain; const char *f_ha1; }; static int read_auth_file(struct mg_file *filep, struct read_auth_file_struct *workdata, int depth) { char *p = NULL /* init if MG_USE_OPEN_FILE is not set */; int is_authorized = 0; struct mg_file fp; size_t l; if (!filep || !workdata || (0 == depth)) { return 0; } /* Loop over passwords file */ #if defined(MG_USE_OPEN_FILE) p = (char *)filep->access.membuf; #endif while (mg_fgets(workdata->buf, sizeof(workdata->buf), filep, &p) != NULL) { l = strlen(workdata->buf); while (l > 0) { if (isspace(workdata->buf[l - 1]) || iscntrl(workdata->buf[l - 1])) { l--; workdata->buf[l] = 0; } else break; } if (l < 1) { continue; } workdata->f_user = workdata->buf; if (workdata->f_user[0] == ':') { /* user names may not contain a ':' and may not be empty, * so lines starting with ':' may be used for a special purpose */ if (workdata->f_user[1] == '#') { /* :# is a comment */ continue; } else if (!strncmp(workdata->f_user + 1, "include=", 8)) { if (mg_fopen(workdata->conn, workdata->f_user + 9, MG_FOPEN_MODE_READ, &fp)) { is_authorized = read_auth_file(&fp, workdata, depth - 1); (void)mg_fclose( &fp.access); /* ignore error on read only file */ /* No need to continue processing files once we have a * match, since nothing will reset it back * to 0. */ if (is_authorized) { return is_authorized; } } else { mg_cry_internal(workdata->conn, "%s: cannot open authorization file: %s", __func__, workdata->buf); } continue; } /* everything is invalid for the moment (might change in the * future) */ mg_cry_internal(workdata->conn, "%s: syntax error in authorization file: %s", __func__, workdata->buf); continue; } workdata->f_domain = strchr(workdata->f_user, ':'); if (workdata->f_domain == NULL) { mg_cry_internal(workdata->conn, "%s: syntax error in authorization file: %s", __func__, workdata->buf); continue; } *(char *)(workdata->f_domain) = 0; (workdata->f_domain)++; workdata->f_ha1 = strchr(workdata->f_domain, ':'); if (workdata->f_ha1 == NULL) { mg_cry_internal(workdata->conn, "%s: syntax error in authorization file: %s", __func__, workdata->buf); continue; } *(char *)(workdata->f_ha1) = 0; (workdata->f_ha1)++; if (!strcmp(workdata->ah.user, workdata->f_user) && !strcmp(workdata->domain, workdata->f_domain)) { return check_password(workdata->conn->request_info.request_method, workdata->f_ha1, workdata->ah.uri, workdata->ah.nonce, workdata->ah.nc, workdata->ah.cnonce, workdata->ah.qop, workdata->ah.response); } } return is_authorized; } /* Authorize against the opened passwords file. Return 1 if authorized. */ static int authorize(struct mg_connection *conn, struct mg_file *filep, const char *realm) { struct read_auth_file_struct workdata; char buf[MG_BUF_LEN]; if (!conn || !conn->dom_ctx) { return 0; } memset(&workdata, 0, sizeof(workdata)); workdata.conn = conn; if (!parse_auth_header(conn, buf, sizeof(buf), &workdata.ah)) { return 0; } if (realm) { workdata.domain = realm; } else { workdata.domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN]; } return read_auth_file(filep, &workdata, INITIAL_DEPTH); } /* Public function to check http digest authentication header */ int mg_check_digest_access_authentication(struct mg_connection *conn, const char *realm, const char *filename) { struct mg_file file = STRUCT_FILE_INITIALIZER; int auth; if (!conn || !filename) { return -1; } if (!mg_fopen(conn, filename, MG_FOPEN_MODE_READ, &file)) { return -2; } auth = authorize(conn, &file, realm); mg_fclose(&file.access); return auth; } /* Return 1 if request is authorised, 0 otherwise. */ static int check_authorization(struct mg_connection *conn, const char *path) { char fname[PATH_MAX]; struct vec uri_vec, filename_vec; const char *list; struct mg_file file = STRUCT_FILE_INITIALIZER; int authorized = 1, truncated; if (!conn || !conn->dom_ctx) { return 0; } list = conn->dom_ctx->config[PROTECT_URI]; while ((list = next_option(list, &uri_vec, &filename_vec)) != NULL) { if (!memcmp(conn->request_info.local_uri, uri_vec.ptr, uri_vec.len)) { mg_snprintf(conn, &truncated, fname, sizeof(fname), "%.*s", (int)filename_vec.len, filename_vec.ptr); if (truncated || !mg_fopen(conn, fname, MG_FOPEN_MODE_READ, &file)) { mg_cry_internal(conn, "%s: cannot open %s: %s", __func__, fname, strerror(errno)); } break; } } if (!is_file_opened(&file.access)) { open_auth_file(conn, path, &file); } if (is_file_opened(&file.access)) { authorized = authorize(conn, &file, NULL); (void)mg_fclose(&file.access); /* ignore error on read only file */ } return authorized; } /* Internal function. Assumes conn is valid */ static void send_authorization_request(struct mg_connection *conn, const char *realm) { char date[64]; time_t curtime = time(NULL); uint64_t nonce = (uint64_t)(conn->phys_ctx->start_time); if (!realm) { realm = conn->dom_ctx->config[AUTHENTICATION_DOMAIN]; } (void)pthread_mutex_lock(&conn->phys_ctx->nonce_mutex); nonce += conn->dom_ctx->nonce_count; ++conn->dom_ctx->nonce_count; (void)pthread_mutex_unlock(&conn->phys_ctx->nonce_mutex); nonce ^= conn->dom_ctx->auth_nonce_mask; conn->status_code = 401; conn->must_close = 1; gmt_time_string(date, sizeof(date), &curtime); mg_printf(conn, "HTTP/1.1 401 Unauthorized\r\n"); send_no_cache_header(conn); send_additional_header(conn); mg_printf(conn, "Date: %s\r\n" "Connection: %s\r\n" "Content-Length: 0\r\n" "WWW-Authenticate: Digest qop=\"auth\", realm=\"%s\", " "nonce=\"%" UINT64_FMT "\"\r\n\r\n", date, suggest_connection_header(conn), realm, nonce); } /* Interface function. Parameters are provided by the user, so do * at least some basic checks. */ int mg_send_digest_access_authentication_request(struct mg_connection *conn, const char *realm) { if (conn && conn->dom_ctx) { send_authorization_request(conn, realm); return 0; } return -1; } #if !defined(NO_FILES) static int is_authorized_for_put(struct mg_connection *conn) { if (conn) { struct mg_file file = STRUCT_FILE_INITIALIZER; const char *passfile = conn->dom_ctx->config[PUT_DELETE_PASSWORDS_FILE]; int ret = 0; if (passfile != NULL && mg_fopen(conn, passfile, MG_FOPEN_MODE_READ, &file)) { ret = authorize(conn, &file, NULL); (void)mg_fclose(&file.access); /* ignore error on read only file */ } return ret; } return 0; } #endif int mg_modify_passwords_file(const char *fname, const char *domain, const char *user, const char *pass) { int found, i; char line[512], u[512] = "", d[512] = "", ha1[33], tmp[PATH_MAX + 8]; FILE *fp, *fp2; found = 0; fp = fp2 = NULL; /* Regard empty password as no password - remove user record. */ if ((pass != NULL) && (pass[0] == '\0')) { pass = NULL; } /* Other arguments must not be empty */ if ((fname == NULL) || (domain == NULL) || (user == NULL)) { return 0; } /* Using the given file format, user name and domain must not contain * ':' */ if (strchr(user, ':') != NULL) { return 0; } if (strchr(domain, ':') != NULL) { return 0; } /* Do not allow control characters like newline in user name and domain. * Do not allow excessively long names either. */ for (i = 0; ((i < 255) && (user[i] != 0)); i++) { if (iscntrl(user[i])) { return 0; } } if (user[i]) { return 0; } for (i = 0; ((i < 255) && (domain[i] != 0)); i++) { if (iscntrl(domain[i])) { return 0; } } if (domain[i]) { return 0; } /* The maximum length of the path to the password file is limited */ if ((strlen(fname) + 4) >= PATH_MAX) { return 0; } /* Create a temporary file name. Length has been checked before. */ strcpy(tmp, fname); strcat(tmp, ".tmp"); /* Create the file if does not exist */ /* Use of fopen here is OK, since fname is only ASCII */ if ((fp = fopen(fname, "a+")) != NULL) { (void)fclose(fp); } /* Open the given file and temporary file */ if ((fp = fopen(fname, "r")) == NULL) { return 0; } else if ((fp2 = fopen(tmp, "w+")) == NULL) { fclose(fp); return 0; } /* Copy the stuff to temporary file */ while (fgets(line, sizeof(line), fp) != NULL) { if (sscanf(line, "%255[^:]:%255[^:]:%*s", u, d) != 2) { continue; } u[255] = 0; d[255] = 0; if (!strcmp(u, user) && !strcmp(d, domain)) { found++; if (pass != NULL) { mg_md5(ha1, user, ":", domain, ":", pass, NULL); fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); } } else { fprintf(fp2, "%s", line); } } /* If new user, just add it */ if (!found && (pass != NULL)) { mg_md5(ha1, user, ":", domain, ":", pass, NULL); fprintf(fp2, "%s:%s:%s\n", user, domain, ha1); } /* Close files */ fclose(fp); fclose(fp2); /* Put the temp file in place of real file */ IGNORE_UNUSED_RESULT(remove(fname)); IGNORE_UNUSED_RESULT(rename(tmp, fname)); return 1; } static int is_valid_port(unsigned long port) { return (port <= 0xffff); } static int mg_inet_pton(int af, const char *src, void *dst, size_t dstlen) { struct addrinfo hints, *res, *ressave; int func_ret = 0; int gai_ret; memset(&hints, 0, sizeof(struct addrinfo)); hints.ai_family = af; gai_ret = getaddrinfo(src, NULL, &hints, &res); if (gai_ret != 0) { /* gai_strerror could be used to convert gai_ret to a string */ /* POSIX return values: see * http://pubs.opengroup.org/onlinepubs/9699919799/functions/freeaddrinfo.html */ /* Windows return values: see * https://msdn.microsoft.com/en-us/library/windows/desktop/ms738520%28v=vs.85%29.aspx */ return 0; } ressave = res; while (res) { if (dstlen >= (size_t)res->ai_addrlen) { memcpy(dst, res->ai_addr, res->ai_addrlen); func_ret = 1; } res = res->ai_next; } freeaddrinfo(ressave); return func_ret; } static int connect_socket(struct mg_context *ctx /* may be NULL */, const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, SOCKET *sock /* output: socket, must not be NULL */, union usa *sa /* output: socket address, must not be NULL */ ) { int ip_ver = 0; int conn_ret = -1; *sock = INVALID_SOCKET; memset(sa, 0, sizeof(*sa)); if (ebuf_len > 0) { *ebuf = 0; } if (host == NULL) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "NULL host"); return 0; } if ((port <= 0) || !is_valid_port((unsigned)port)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "invalid port"); return 0; } #if !defined(NO_SSL) #if !defined(NO_SSL_DL) #if defined(OPENSSL_API_1_1) if (use_ssl && (TLS_client_method == NULL)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "SSL is not initialized"); return 0; } #else if (use_ssl && (SSLv23_client_method == NULL)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "SSL is not initialized"); return 0; } #endif /* OPENSSL_API_1_1 */ #else (void)use_ssl; #endif /* NO_SSL_DL */ #else (void)use_ssl; #endif /* !defined(NO_SSL) */ if (mg_inet_pton(AF_INET, host, &sa->sin, sizeof(sa->sin))) { sa->sin.sin_family = AF_INET; sa->sin.sin_port = htons((uint16_t)port); ip_ver = 4; #if defined(USE_IPV6) } else if (mg_inet_pton(AF_INET6, host, &sa->sin6, sizeof(sa->sin6))) { sa->sin6.sin6_family = AF_INET6; sa->sin6.sin6_port = htons((uint16_t)port); ip_ver = 6; } else if (host[0] == '[') { /* While getaddrinfo on Windows will work with [::1], * getaddrinfo on Linux only works with ::1 (without []). */ size_t l = strlen(host + 1); char *h = (l > 1) ? mg_strdup_ctx(host + 1, ctx) : NULL; if (h) { h[l - 1] = 0; if (mg_inet_pton(AF_INET6, h, &sa->sin6, sizeof(sa->sin6))) { sa->sin6.sin6_family = AF_INET6; sa->sin6.sin6_port = htons((uint16_t)port); ip_ver = 6; } mg_free(h); } #endif } if (ip_ver == 0) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "host not found"); return 0; } if (ip_ver == 4) { *sock = socket(PF_INET, SOCK_STREAM, 0); } #if defined(USE_IPV6) else if (ip_ver == 6) { *sock = socket(PF_INET6, SOCK_STREAM, 0); } #endif if (*sock == INVALID_SOCKET) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "socket(): %s", strerror(ERRNO)); return 0; } if (0 != set_non_blocking_mode(*sock)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "Cannot set socket to non-blocking: %s", strerror(ERRNO)); closesocket(*sock); *sock = INVALID_SOCKET; return 0; } set_close_on_exec(*sock, fc(ctx)); if (ip_ver == 4) { /* connected with IPv4 */ conn_ret = connect(*sock, (struct sockaddr *)((void *)&sa->sin), sizeof(sa->sin)); } #if defined(USE_IPV6) else if (ip_ver == 6) { /* connected with IPv6 */ conn_ret = connect(*sock, (struct sockaddr *)((void *)&sa->sin6), sizeof(sa->sin6)); } #endif #if defined(_WIN32) if (conn_ret != 0) { DWORD err = WSAGetLastError(); /* could return WSAEWOULDBLOCK */ conn_ret = (int)err; #if !defined(EINPROGRESS) #define EINPROGRESS (WSAEWOULDBLOCK) /* Winsock equivalent */ #endif /* if !defined(EINPROGRESS) */ } #endif if ((conn_ret != 0) && (conn_ret != EINPROGRESS)) { /* Data for getsockopt */ int sockerr = -1; void *psockerr = &sockerr; #if defined(_WIN32) int len = (int)sizeof(sockerr); #else socklen_t len = (socklen_t)sizeof(sockerr); #endif /* Data for poll */ struct pollfd pfd[1]; int pollres; int ms_wait = 10000; /* 10 second timeout */ /* For a non-blocking socket, the connect sequence is: * 1) call connect (will not block) * 2) wait until the socket is ready for writing (select or poll) * 3) check connection state with getsockopt */ pfd[0].fd = *sock; pfd[0].events = POLLOUT; pollres = mg_poll(pfd, 1, (int)(ms_wait), &(ctx->stop_flag)); if (pollres != 1) { /* Not connected */ mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "connect(%s:%d): timeout", host, port); closesocket(*sock); *sock = INVALID_SOCKET; return 0; } #if defined(_WIN32) getsockopt(*sock, SOL_SOCKET, SO_ERROR, (char *)psockerr, &len); #else getsockopt(*sock, SOL_SOCKET, SO_ERROR, psockerr, &len); #endif if (sockerr != 0) { /* Not connected */ mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "connect(%s:%d): error %s", host, port, strerror(sockerr)); closesocket(*sock); *sock = INVALID_SOCKET; return 0; } } return 1; } int mg_url_encode(const char *src, char *dst, size_t dst_len) { static const char *dont_escape = "._-$,;~()"; static const char *hex = "0123456789abcdef"; char *pos = dst; const char *end = dst + dst_len - 1; for (; ((*src != '\0') && (pos < end)); src++, pos++) { if (isalnum(*(const unsigned char *)src) || (strchr(dont_escape, *(const unsigned char *)src) != NULL)) { *pos = *src; } else if (pos + 2 < end) { pos[0] = '%'; pos[1] = hex[(*(const unsigned char *)src) >> 4]; pos[2] = hex[(*(const unsigned char *)src) & 0xf]; pos += 2; } else { break; } } *pos = '\0'; return (*src == '\0') ? (int)(pos - dst) : -1; } /* Return 0 on success, non-zero if an error occurs. */ static int print_dir_entry(struct de *de) { size_t hrefsize; char *href; char size[64], mod[64]; #if defined(REENTRANT_TIME) struct tm _tm; struct tm *tm = &_tm; #else struct tm *tm; #endif hrefsize = PATH_MAX * 3; /* worst case */ href = (char *)mg_malloc(hrefsize); if (href == NULL) { return -1; } if (de->file.is_directory) { mg_snprintf(de->conn, NULL, /* Buffer is big enough */ size, sizeof(size), "%s", "[DIRECTORY]"); } else { /* We use (signed) cast below because MSVC 6 compiler cannot * convert unsigned __int64 to double. Sigh. */ if (de->file.size < 1024) { mg_snprintf(de->conn, NULL, /* Buffer is big enough */ size, sizeof(size), "%d", (int)de->file.size); } else if (de->file.size < 0x100000) { mg_snprintf(de->conn, NULL, /* Buffer is big enough */ size, sizeof(size), "%.1fk", (double)de->file.size / 1024.0); } else if (de->file.size < 0x40000000) { mg_snprintf(de->conn, NULL, /* Buffer is big enough */ size, sizeof(size), "%.1fM", (double)de->file.size / 1048576); } else { mg_snprintf(de->conn, NULL, /* Buffer is big enough */ size, sizeof(size), "%.1fG", (double)de->file.size / 1073741824); } } /* Note: mg_snprintf will not cause a buffer overflow above. * So, string truncation checks are not required here. */ #if defined(REENTRANT_TIME) localtime_r(&de->file.last_modified, tm); #else tm = localtime(&de->file.last_modified); #endif if (tm != NULL) { strftime(mod, sizeof(mod), "%d-%b-%Y %H:%M", tm); } else { mg_strlcpy(mod, "01-Jan-1970 00:00", sizeof(mod)); mod[sizeof(mod) - 1] = '\0'; } mg_url_encode(de->file_name, href, hrefsize); mg_printf(de->conn, "<tr><td><a href=\"%s%s%s\">%s%s</a></td>" "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n", de->conn->request_info.local_uri, href, de->file.is_directory ? "/" : "", de->file_name, de->file.is_directory ? "/" : "", mod, size); mg_free(href); return 0; } /* This function is called from send_directory() and used for * sorting directory entries by size, or name, or modification time. * On windows, __cdecl specification is needed in case if project is built * with __stdcall convention. qsort always requires __cdels callback. */ static int WINCDECL compare_dir_entries(const void *p1, const void *p2) { if (p1 && p2) { const struct de *a = (const struct de *)p1, *b = (const struct de *)p2; const char *query_string = a->conn->request_info.query_string; int cmp_result = 0; if (query_string == NULL) { query_string = "na"; } if (a->file.is_directory && !b->file.is_directory) { return -1; /* Always put directories on top */ } else if (!a->file.is_directory && b->file.is_directory) { return 1; /* Always put directories on top */ } else if (*query_string == 'n') { cmp_result = strcmp(a->file_name, b->file_name); } else if (*query_string == 's') { cmp_result = (a->file.size == b->file.size) ? 0 : ((a->file.size > b->file.size) ? 1 : -1); } else if (*query_string == 'd') { cmp_result = (a->file.last_modified == b->file.last_modified) ? 0 : ((a->file.last_modified > b->file.last_modified) ? 1 : -1); } return (query_string[1] == 'd') ? -cmp_result : cmp_result; } return 0; } static int must_hide_file(struct mg_connection *conn, const char *path) { if (conn && conn->dom_ctx) { const char *pw_pattern = "**" PASSWORDS_FILE_NAME "$"; const char *pattern = conn->dom_ctx->config[HIDE_FILES]; return (match_prefix(pw_pattern, strlen(pw_pattern), path) > 0) || ((pattern != NULL) && (match_prefix(pattern, strlen(pattern), path) > 0)); } return 0; } static int scan_directory(struct mg_connection *conn, const char *dir, void *data, int (*cb)(struct de *, void *)) { char path[PATH_MAX]; struct dirent *dp; DIR *dirp; struct de de; int truncated; if ((dirp = mg_opendir(conn, dir)) == NULL) { return 0; } else { de.conn = conn; while ((dp = mg_readdir(dirp)) != NULL) { /* Do not show current dir and hidden files */ if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..") || must_hide_file(conn, dp->d_name)) { continue; } mg_snprintf( conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name); /* If we don't memset stat structure to zero, mtime will have * garbage and strftime() will segfault later on in * print_dir_entry(). memset is required only if mg_stat() * fails. For more details, see * http://code.google.com/p/mongoose/issues/detail?id=79 */ memset(&de.file, 0, sizeof(de.file)); if (truncated) { /* If the path is not complete, skip processing. */ continue; } if (!mg_stat(conn, path, &de.file)) { mg_cry_internal(conn, "%s: mg_stat(%s) failed: %s", __func__, path, strerror(ERRNO)); } de.file_name = dp->d_name; cb(&de, data); } (void)mg_closedir(dirp); } return 1; } #if !defined(NO_FILES) static int remove_directory(struct mg_connection *conn, const char *dir) { char path[PATH_MAX]; struct dirent *dp; DIR *dirp; struct de de; int truncated; int ok = 1; if ((dirp = mg_opendir(conn, dir)) == NULL) { return 0; } else { de.conn = conn; while ((dp = mg_readdir(dirp)) != NULL) { /* Do not show current dir (but show hidden files as they will * also be removed) */ if (!strcmp(dp->d_name, ".") || !strcmp(dp->d_name, "..")) { continue; } mg_snprintf( conn, &truncated, path, sizeof(path), "%s/%s", dir, dp->d_name); /* If we don't memset stat structure to zero, mtime will have * garbage and strftime() will segfault later on in * print_dir_entry(). memset is required only if mg_stat() * fails. For more details, see * http://code.google.com/p/mongoose/issues/detail?id=79 */ memset(&de.file, 0, sizeof(de.file)); if (truncated) { /* Do not delete anything shorter */ ok = 0; continue; } if (!mg_stat(conn, path, &de.file)) { mg_cry_internal(conn, "%s: mg_stat(%s) failed: %s", __func__, path, strerror(ERRNO)); ok = 0; } if (de.file.is_directory) { if (remove_directory(conn, path) == 0) { ok = 0; } } else { /* This will fail file is the file is in memory */ if (mg_remove(conn, path) == 0) { ok = 0; } } } (void)mg_closedir(dirp); IGNORE_UNUSED_RESULT(rmdir(dir)); } return ok; } #endif struct dir_scan_data { struct de *entries; unsigned int num_entries; unsigned int arr_size; }; /* Behaves like realloc(), but frees original pointer on failure */ static void * realloc2(void *ptr, size_t size) { void *new_ptr = mg_realloc(ptr, size); if (new_ptr == NULL) { mg_free(ptr); } return new_ptr; } static int dir_scan_callback(struct de *de, void *data) { struct dir_scan_data *dsd = (struct dir_scan_data *)data; if ((dsd->entries == NULL) || (dsd->num_entries >= dsd->arr_size)) { dsd->arr_size *= 2; dsd->entries = (struct de *)realloc2(dsd->entries, dsd->arr_size * sizeof(dsd->entries[0])); } if (dsd->entries == NULL) { /* TODO(lsm, low): propagate an error to the caller */ dsd->num_entries = 0; } else { dsd->entries[dsd->num_entries].file_name = mg_strdup(de->file_name); dsd->entries[dsd->num_entries].file = de->file; dsd->entries[dsd->num_entries].conn = de->conn; dsd->num_entries++; } return 0; } static void handle_directory_request(struct mg_connection *conn, const char *dir) { unsigned int i; int sort_direction; struct dir_scan_data data = {NULL, 0, 128}; char date[64]; time_t curtime = time(NULL); if (!scan_directory(conn, dir, &data, dir_scan_callback)) { mg_send_http_error(conn, 500, "Error: Cannot open directory\nopendir(%s): %s", dir, strerror(ERRNO)); return; } gmt_time_string(date, sizeof(date), &curtime); if (!conn) { return; } sort_direction = ((conn->request_info.query_string != NULL) && (conn->request_info.query_string[1] == 'd')) ? 'a' : 'd'; conn->must_close = 1; mg_printf(conn, "HTTP/1.1 200 OK\r\n"); send_static_cache_header(conn); send_additional_header(conn); mg_printf(conn, "Date: %s\r\n" "Connection: close\r\n" "Content-Type: text/html; charset=utf-8\r\n\r\n", date); mg_printf(conn, "<html><head><title>Index of %s</title>" "<style>th {text-align: left;}</style></head>" "<body><h1>Index of %s</h1><pre><table cellpadding=\"0\">" "<tr><th><a href=\"?n%c\">Name</a></th>" "<th><a href=\"?d%c\">Modified</a></th>" "<th><a href=\"?s%c\">Size</a></th></tr>" "<tr><td colspan=\"3\"><hr></td></tr>", conn->request_info.local_uri, conn->request_info.local_uri, sort_direction, sort_direction, sort_direction); /* Print first entry - link to a parent directory */ mg_printf(conn, "<tr><td><a href=\"%s%s\">%s</a></td>" "<td>&nbsp;%s</td><td>&nbsp;&nbsp;%s</td></tr>\n", conn->request_info.local_uri, "..", "Parent directory", "-", "-"); /* Sort and print directory entries */ if (data.entries != NULL) { qsort(data.entries, (size_t)data.num_entries, sizeof(data.entries[0]), compare_dir_entries); for (i = 0; i < data.num_entries; i++) { print_dir_entry(&data.entries[i]); mg_free(data.entries[i].file_name); } mg_free(data.entries); } mg_printf(conn, "%s", "</table></body></html>"); conn->status_code = 200; } /* Send len bytes from the opened file to the client. */ static void send_file_data(struct mg_connection *conn, struct mg_file *filep, int64_t offset, int64_t len) { char buf[MG_BUF_LEN]; int to_read, num_read, num_written; int64_t size; if (!filep || !conn) { return; } /* Sanity check the offset */ size = (filep->stat.size > INT64_MAX) ? INT64_MAX : (int64_t)(filep->stat.size); offset = (offset < 0) ? 0 : ((offset > size) ? size : offset); #if defined(MG_USE_OPEN_FILE) if ((len > 0) && (filep->access.membuf != NULL) && (size > 0)) { /* file stored in memory */ if (len > size - offset) { len = size - offset; } mg_write(conn, filep->access.membuf + offset, (size_t)len); } else /* else block below */ #endif if (len > 0 && filep->access.fp != NULL) { /* file stored on disk */ #if defined(__linux__) /* sendfile is only available for Linux */ if ((conn->ssl == 0) && (conn->throttle == 0) && (!mg_strcasecmp(conn->dom_ctx->config[ALLOW_SENDFILE_CALL], "yes"))) { off_t sf_offs = (off_t)offset; ssize_t sf_sent; int sf_file = fileno(filep->access.fp); int loop_cnt = 0; do { /* 2147479552 (0x7FFFF000) is a limit found by experiment on * 64 bit Linux (2^31 minus one memory page of 4k?). */ size_t sf_tosend = (size_t)((len < 0x7FFFF000) ? len : 0x7FFFF000); sf_sent = sendfile(conn->client.sock, sf_file, &sf_offs, sf_tosend); if (sf_sent > 0) { len -= sf_sent; offset += sf_sent; } else if (loop_cnt == 0) { /* This file can not be sent using sendfile. * This might be the case for pseudo-files in the * /sys/ and /proc/ file system. * Use the regular user mode copy code instead. */ break; } else if (sf_sent == 0) { /* No error, but 0 bytes sent. May be EOF? */ return; } loop_cnt++; } while ((len > 0) && (sf_sent >= 0)); if (sf_sent > 0) { return; /* OK */ } /* sf_sent<0 means error, thus fall back to the classic way */ /* This is always the case, if sf_file is not a "normal" file, * e.g., for sending data from the output of a CGI process. */ offset = (int64_t)sf_offs; } #endif if ((offset > 0) && (fseeko(filep->access.fp, offset, SEEK_SET) != 0)) { mg_cry_internal(conn, "%s: fseeko() failed: %s", __func__, strerror(ERRNO)); mg_send_http_error( conn, 500, "%s", "Error: Unable to access file at requested position."); } else { while (len > 0) { /* Calculate how much to read from the file in the buffer */ to_read = sizeof(buf); if ((int64_t)to_read > len) { to_read = (int)len; } /* Read from file, exit the loop on error */ if ((num_read = (int)fread(buf, 1, (size_t)to_read, filep->access.fp)) <= 0) { break; } /* Send read bytes to the client, exit the loop on error */ if ((num_written = mg_write(conn, buf, (size_t)num_read)) != num_read) { break; } /* Both read and were successful, adjust counters */ len -= num_written; } } } } static int parse_range_header(const char *header, int64_t *a, int64_t *b) { return sscanf(header, "bytes=%" INT64_FMT "-%" INT64_FMT, a, b); } static void construct_etag(char *buf, size_t buf_len, const struct mg_file_stat *filestat) { if ((filestat != NULL) && (buf != NULL)) { mg_snprintf(NULL, NULL, /* All calls to construct_etag use 64 byte buffer */ buf, buf_len, "\"%lx.%" INT64_FMT "\"", (unsigned long)filestat->last_modified, filestat->size); } } static void fclose_on_exec(struct mg_file_access *filep, struct mg_connection *conn) { if (filep != NULL && filep->fp != NULL) { #if defined(_WIN32) (void)conn; /* Unused. */ #else if (fcntl(fileno(filep->fp), F_SETFD, FD_CLOEXEC) != 0) { mg_cry_internal(conn, "%s: fcntl(F_SETFD FD_CLOEXEC) failed: %s", __func__, strerror(ERRNO)); } #endif } } #if defined(USE_ZLIB) #include "mod_zlib.inl" #endif static void handle_static_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep, const char *mime_type, const char *additional_headers) { char date[64], lm[64], etag[64]; char range[128]; /* large enough, so there will be no overflow */ const char *msg = "OK", *hdr; time_t curtime = time(NULL); int64_t cl, r1, r2; struct vec mime_vec; int n, truncated; char gz_path[PATH_MAX]; const char *encoding = ""; const char *cors1, *cors2, *cors3; int is_head_request; #if defined(USE_ZLIB) /* Compression is allowed, unless there is a reason not to use compression. * If the file is already compressed, too small or a "range" request was * made, on the fly compression is not possible. */ int allow_on_the_fly_compression = 1; #endif if ((conn == NULL) || (conn->dom_ctx == NULL) || (filep == NULL)) { return; } is_head_request = !strcmp(conn->request_info.request_method, "HEAD"); if (mime_type == NULL) { get_mime_type(conn, path, &mime_vec); } else { mime_vec.ptr = mime_type; mime_vec.len = strlen(mime_type); } if (filep->stat.size > INT64_MAX) { mg_send_http_error(conn, 500, "Error: File size is too large to send\n%" INT64_FMT, filep->stat.size); return; } cl = (int64_t)filep->stat.size; conn->status_code = 200; range[0] = '\0'; #if defined(USE_ZLIB) /* if this file is in fact a pre-gzipped file, rewrite its filename * it's important to rewrite the filename after resolving * the mime type from it, to preserve the actual file's type */ if (!conn->accept_gzip) { allow_on_the_fly_compression = 0; } #endif if (filep->stat.is_gzipped) { mg_snprintf(conn, &truncated, gz_path, sizeof(gz_path), "%s.gz", path); if (truncated) { mg_send_http_error(conn, 500, "Error: Path of zipped file too long (%s)", path); return; } path = gz_path; encoding = "Content-Encoding: gzip\r\n"; #if defined(USE_ZLIB) /* File is already compressed. No "on the fly" compression. */ allow_on_the_fly_compression = 0; #endif } if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) { mg_send_http_error(conn, 500, "Error: Cannot open file\nfopen(%s): %s", path, strerror(ERRNO)); return; } fclose_on_exec(&filep->access, conn); /* If "Range" request was made: parse header, send only selected part * of the file. */ r1 = r2 = 0; hdr = mg_get_header(conn, "Range"); if ((hdr != NULL) && ((n = parse_range_header(hdr, &r1, &r2)) > 0) && (r1 >= 0) && (r2 >= 0)) { /* actually, range requests don't play well with a pre-gzipped * file (since the range is specified in the uncompressed space) */ if (filep->stat.is_gzipped) { mg_send_http_error( conn, 416, /* 416 = Range Not Satisfiable */ "%s", "Error: Range requests in gzipped files are not supported"); (void)mg_fclose( &filep->access); /* ignore error on read only file */ return; } conn->status_code = 206; cl = (n == 2) ? (((r2 > cl) ? cl : r2) - r1 + 1) : (cl - r1); mg_snprintf(conn, NULL, /* range buffer is big enough */ range, sizeof(range), "Content-Range: bytes " "%" INT64_FMT "-%" INT64_FMT "/%" INT64_FMT "\r\n", r1, r1 + cl - 1, filep->stat.size); msg = "Partial Content"; #if defined(USE_ZLIB) /* Do not compress ranges. */ allow_on_the_fly_compression = 0; #endif } /* Do not compress small files. Small files do not benefit from file * compression, but there is still some overhead. */ #if defined(USE_ZLIB) if (filep->stat.size < MG_FILE_COMPRESSION_SIZE_LIMIT) { /* File is below the size limit. */ allow_on_the_fly_compression = 0; } #endif /* Standard CORS header */ hdr = mg_get_header(conn, "Origin"); if (hdr) { /* Cross-origin resource sharing (CORS), see * http://www.html5rocks.com/en/tutorials/cors/, * http://www.html5rocks.com/static/images/cors_server_flowchart.png * - * preflight is not supported for files. */ cors1 = "Access-Control-Allow-Origin: "; cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN]; cors3 = "\r\n"; } else { cors1 = cors2 = cors3 = ""; } /* Prepare Etag, Date, Last-Modified headers. Must be in UTC, * according to * http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3 */ gmt_time_string(date, sizeof(date), &curtime); gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified); construct_etag(etag, sizeof(etag), &filep->stat); /* Send header */ (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n" "%s%s%s" /* CORS */ "Date: %s\r\n" "Last-Modified: %s\r\n" "Etag: %s\r\n" "Content-Type: %.*s\r\n" "Connection: %s\r\n", conn->status_code, msg, cors1, cors2, cors3, date, lm, etag, (int)mime_vec.len, mime_vec.ptr, suggest_connection_header(conn)); send_static_cache_header(conn); send_additional_header(conn); #if defined(USE_ZLIB) /* On the fly compression allowed */ if (allow_on_the_fly_compression) { /* For on the fly compression, we don't know the content size in * advance, so we have to use chunked encoding */ (void)mg_printf(conn, "Content-Encoding: gzip\r\n" "Transfer-Encoding: chunked\r\n"); } else #endif { /* Without on-the-fly compression, we know the content-length * and we can use ranges (with on-the-fly compression we cannot). * So we send these response headers only in this case. */ (void)mg_printf(conn, "Content-Length: %" INT64_FMT "\r\n" "Accept-Ranges: bytes\r\n" "%s" /* range */ "%s" /* encoding */, cl, range, encoding); } /* The previous code must not add any header starting with X- to make * sure no one of the additional_headers is included twice */ if (additional_headers != NULL) { (void)mg_printf(conn, "%.*s\r\n\r\n", (int)strlen(additional_headers), additional_headers); } else { (void)mg_printf(conn, "\r\n"); } if (!is_head_request) { #if defined(USE_ZLIB) if (allow_on_the_fly_compression) { /* Compress and send */ send_compressed_data(conn, filep); } else #endif { /* Send file directly */ send_file_data(conn, filep, r1, cl); } } (void)mg_fclose(&filep->access); /* ignore error on read only file */ } #if !defined(NO_CACHING) /* Return True if we should reply 304 Not Modified. */ static int is_not_modified(const struct mg_connection *conn, const struct mg_file_stat *filestat) { char etag[64]; const char *ims = mg_get_header(conn, "If-Modified-Since"); const char *inm = mg_get_header(conn, "If-None-Match"); construct_etag(etag, sizeof(etag), filestat); return ((inm != NULL) && !mg_strcasecmp(etag, inm)) || ((ims != NULL) && (filestat->last_modified <= parse_date_string(ims))); } static void handle_not_modified_static_file_request(struct mg_connection *conn, struct mg_file *filep) { char date[64], lm[64], etag[64]; time_t curtime = time(NULL); if ((conn == NULL) || (filep == NULL)) { return; } conn->status_code = 304; gmt_time_string(date, sizeof(date), &curtime); gmt_time_string(lm, sizeof(lm), &filep->stat.last_modified); construct_etag(etag, sizeof(etag), &filep->stat); (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n" "Date: %s\r\n", conn->status_code, mg_get_response_code_text(conn, conn->status_code), date); send_static_cache_header(conn); send_additional_header(conn); (void)mg_printf(conn, "Last-Modified: %s\r\n" "Etag: %s\r\n" "Connection: %s\r\n" "\r\n", lm, etag, suggest_connection_header(conn)); } #endif void mg_send_file(struct mg_connection *conn, const char *path) { mg_send_mime_file(conn, path, NULL); } void mg_send_mime_file(struct mg_connection *conn, const char *path, const char *mime_type) { mg_send_mime_file2(conn, path, mime_type, NULL); } void mg_send_mime_file2(struct mg_connection *conn, const char *path, const char *mime_type, const char *additional_headers) { struct mg_file file = STRUCT_FILE_INITIALIZER; if (!conn) { /* No conn */ return; } if (mg_stat(conn, path, &file.stat)) { #if !defined(NO_CACHING) if (is_not_modified(conn, &file.stat)) { /* Send 304 "Not Modified" - this must not send any body data */ handle_not_modified_static_file_request(conn, &file); } else #endif /* NO_CACHING */ if (file.stat.is_directory) { if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) { handle_directory_request(conn, path); } else { mg_send_http_error(conn, 403, "%s", "Error: Directory listing denied"); } } else { handle_static_file_request( conn, path, &file, mime_type, additional_headers); } } else { mg_send_http_error(conn, 404, "%s", "Error: File not found"); } } /* For a given PUT path, create all intermediate subdirectories. * Return 0 if the path itself is a directory. * Return 1 if the path leads to a file. * Return -1 for if the path is too long. * Return -2 if path can not be created. */ static int put_dir(struct mg_connection *conn, const char *path) { char buf[PATH_MAX]; const char *s, *p; struct mg_file file = STRUCT_FILE_INITIALIZER; size_t len; int res = 1; for (s = p = path + 2; (p = strchr(s, '/')) != NULL; s = ++p) { len = (size_t)(p - path); if (len >= sizeof(buf)) { /* path too long */ res = -1; break; } memcpy(buf, path, len); buf[len] = '\0'; /* Try to create intermediate directory */ DEBUG_TRACE("mkdir(%s)", buf); if (!mg_stat(conn, buf, &file.stat) && mg_mkdir(conn, buf, 0755) != 0) { /* path does not exixt and can not be created */ res = -2; break; } /* Is path itself a directory? */ if (p[1] == '\0') { res = 0; } } return res; } static void remove_bad_file(const struct mg_connection *conn, const char *path) { int r = mg_remove(conn, path); if (r != 0) { mg_cry_internal(conn, "%s: Cannot remove invalid file %s", __func__, path); } } long long mg_store_body(struct mg_connection *conn, const char *path) { char buf[MG_BUF_LEN]; long long len = 0; int ret, n; struct mg_file fi; if (conn->consumed_content != 0) { mg_cry_internal(conn, "%s: Contents already consumed", __func__); return -11; } ret = put_dir(conn, path); if (ret < 0) { /* -1 for path too long, * -2 for path can not be created. */ return ret; } if (ret != 1) { /* Return 0 means, path itself is a directory. */ return 0; } if (mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &fi) == 0) { return -12; } ret = mg_read(conn, buf, sizeof(buf)); while (ret > 0) { n = (int)fwrite(buf, 1, (size_t)ret, fi.access.fp); if (n != ret) { (void)mg_fclose( &fi.access); /* File is bad and will be removed anyway. */ remove_bad_file(conn, path); return -13; } len += ret; ret = mg_read(conn, buf, sizeof(buf)); } /* File is open for writing. If fclose fails, there was probably an * error flushing the buffer to disk, so the file on disk might be * broken. Delete it and return an error to the caller. */ if (mg_fclose(&fi.access) != 0) { remove_bad_file(conn, path); return -14; } return len; } /* Parse a buffer: * Forward the string pointer till the end of a word, then * terminate it and forward till the begin of the next word. */ static int skip_to_end_of_word_and_terminate(char **ppw, int eol) { /* Forward until a space is found - use isgraph here */ /* See http://www.cplusplus.com/reference/cctype/ */ while (isgraph(**ppw)) { (*ppw)++; } /* Check end of word */ if (eol) { /* must be a end of line */ if ((**ppw != '\r') && (**ppw != '\n')) { return -1; } } else { /* must be a end of a word, but not a line */ if (**ppw != ' ') { return -1; } } /* Terminate and forward to the next word */ do { **ppw = 0; (*ppw)++; } while ((**ppw) && isspace(**ppw)); /* Check after term */ if (!eol) { /* if it's not the end of line, there must be a next word */ if (!isgraph(**ppw)) { return -1; } } /* ok */ return 1; } /* Parse HTTP headers from the given buffer, advance buf pointer * to the point where parsing stopped. * All parameters must be valid pointers (not NULL). * Return <0 on error. */ static int parse_http_headers(char **buf, struct mg_header hdr[MG_MAX_HEADERS]) { int i; int num_headers = 0; for (i = 0; i < (int)MG_MAX_HEADERS; i++) { char *dp = *buf; while ((*dp != ':') && (*dp >= 33) && (*dp <= 126)) { dp++; } if (dp == *buf) { /* End of headers reached. */ break; } if (*dp != ':') { /* This is not a valid field. */ return -1; } /* End of header key (*dp == ':') */ /* Truncate here and set the key name */ *dp = 0; hdr[i].name = *buf; do { dp++; } while (*dp == ' '); /* The rest of the line is the value */ hdr[i].value = dp; *buf = dp + strcspn(dp, "\r\n"); if (((*buf)[0] != '\r') || ((*buf)[1] != '\n')) { *buf = NULL; } num_headers = i + 1; if (*buf) { (*buf)[0] = 0; (*buf)[1] = 0; *buf += 2; } else { *buf = dp; break; } if ((*buf)[0] == '\r') { /* This is the end of the header */ break; } } return num_headers; } struct mg_http_method_info { const char *name; int request_has_body; int response_has_body; int is_safe; int is_idempotent; int is_cacheable; }; /* https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods */ static struct mg_http_method_info http_methods[] = { /* HTTP (RFC 2616) */ {"GET", 0, 1, 1, 1, 1}, {"POST", 1, 1, 0, 0, 0}, {"PUT", 1, 0, 0, 1, 0}, {"DELETE", 0, 0, 0, 1, 0}, {"HEAD", 0, 0, 1, 1, 1}, {"OPTIONS", 0, 0, 1, 1, 0}, {"CONNECT", 1, 1, 0, 0, 0}, /* TRACE method (RFC 2616) is not supported for security reasons */ /* PATCH method (RFC 5789) */ {"PATCH", 1, 0, 0, 0, 0}, /* PATCH method only allowed for CGI/Lua/LSP and callbacks. */ /* WEBDAV (RFC 2518) */ {"PROPFIND", 0, 1, 1, 1, 0}, /* http://www.webdav.org/specs/rfc4918.html, 9.1: * Some PROPFIND results MAY be cached, with care, * as there is no cache validation mechanism for * most properties. This method is both safe and * idempotent (see Section 9.1 of [RFC2616]). */ {"MKCOL", 0, 0, 0, 1, 0}, /* http://www.webdav.org/specs/rfc4918.html, 9.1: * When MKCOL is invoked without a request body, * the newly created collection SHOULD have no * members. A MKCOL request message may contain * a message body. The precise behavior of a MKCOL * request when the body is present is undefined, * ... ==> We do not support MKCOL with body data. * This method is idempotent, but not safe (see * Section 9.1 of [RFC2616]). Responses to this * method MUST NOT be cached. */ /* Unsupported WEBDAV Methods: */ /* PROPPATCH, COPY, MOVE, LOCK, UNLOCK (RFC 2518) */ /* + 11 methods from RFC 3253 */ /* ORDERPATCH (RFC 3648) */ /* ACL (RFC 3744) */ /* SEARCH (RFC 5323) */ /* + MicroSoft extensions * https://msdn.microsoft.com/en-us/library/aa142917.aspx */ /* REPORT method (RFC 3253) */ {"REPORT", 1, 1, 1, 1, 1}, /* REPORT method only allowed for CGI/Lua/LSP and callbacks. */ /* It was defined for WEBDAV in RFC 3253, Sec. 3.6 * (https://tools.ietf.org/html/rfc3253#section-3.6), but seems * to be useful for REST in case a "GET request with body" is * required. */ {NULL, 0, 0, 0, 0, 0} /* end of list */ }; static const struct mg_http_method_info * get_http_method_info(const char *method) { /* Check if the method is known to the server. The list of all known * HTTP methods can be found here at * http://www.iana.org/assignments/http-methods/http-methods.xhtml */ const struct mg_http_method_info *m = http_methods; while (m->name) { if (!strcmp(m->name, method)) { return m; } m++; } return NULL; } static int is_valid_http_method(const char *method) { return (get_http_method_info(method) != NULL); } /* Parse HTTP request, fill in mg_request_info structure. * This function modifies the buffer by NUL-terminating * HTTP request components, header names and header values. * Parameters: * buf (in/out): pointer to the HTTP header to parse and split * len (in): length of HTTP header buffer * re (out): parsed header as mg_request_info * buf and ri must be valid pointers (not NULL), len>0. * Returns <0 on error. */ static int parse_http_request(char *buf, int len, struct mg_request_info *ri) { int request_length; int init_skip = 0; /* Reset attributes. DO NOT TOUCH is_ssl, remote_addr, * remote_port */ ri->remote_user = ri->request_method = ri->request_uri = ri->http_version = NULL; ri->num_headers = 0; /* RFC says that all initial whitespaces should be ingored */ /* This included all leading \r and \n (isspace) */ /* See table: http://www.cplusplus.com/reference/cctype/ */ while ((len > 0) && isspace(*(unsigned char *)buf)) { buf++; len--; init_skip++; } if (len == 0) { /* Incomplete request */ return 0; } /* Control characters are not allowed, including zero */ if (iscntrl(*(unsigned char *)buf)) { return -1; } /* Find end of HTTP header */ request_length = get_http_header_len(buf, len); if (request_length <= 0) { return request_length; } buf[request_length - 1] = '\0'; if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) { return -1; } /* The first word has to be the HTTP method */ ri->request_method = buf; if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) { return -1; } /* Check for a valid http method */ if (!is_valid_http_method(ri->request_method)) { return -1; } /* The second word is the URI */ ri->request_uri = buf; if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) { return -1; } /* Next would be the HTTP version */ ri->http_version = buf; if (skip_to_end_of_word_and_terminate(&buf, 1) <= 0) { return -1; } /* Check for a valid HTTP version key */ if (strncmp(ri->http_version, "HTTP/", 5) != 0) { /* Invalid request */ return -1; } ri->http_version += 5; /* Parse all HTTP headers */ ri->num_headers = parse_http_headers(&buf, ri->http_headers); if (ri->num_headers < 0) { /* Error while parsing headers */ return -1; } return request_length + init_skip; } static int parse_http_response(char *buf, int len, struct mg_response_info *ri) { int response_length; int init_skip = 0; char *tmp, *tmp2; long l; /* Initialize elements. */ ri->http_version = ri->status_text = NULL; ri->num_headers = ri->status_code = 0; /* RFC says that all initial whitespaces should be ingored */ /* This included all leading \r and \n (isspace) */ /* See table: http://www.cplusplus.com/reference/cctype/ */ while ((len > 0) && isspace(*(unsigned char *)buf)) { buf++; len--; init_skip++; } if (len == 0) { /* Incomplete request */ return 0; } /* Control characters are not allowed, including zero */ if (iscntrl(*(unsigned char *)buf)) { return -1; } /* Find end of HTTP header */ response_length = get_http_header_len(buf, len); if (response_length <= 0) { return response_length; } buf[response_length - 1] = '\0'; if ((*buf == 0) || (*buf == '\r') || (*buf == '\n')) { return -1; } /* The first word is the HTTP version */ /* Check for a valid HTTP version key */ if (strncmp(buf, "HTTP/", 5) != 0) { /* Invalid request */ return -1; } buf += 5; if (!isgraph(buf[0])) { /* Invalid request */ return -1; } ri->http_version = buf; if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) { return -1; } /* The second word is the status as a number */ tmp = buf; if (skip_to_end_of_word_and_terminate(&buf, 0) <= 0) { return -1; } l = strtol(tmp, &tmp2, 10); if ((l < 100) || (l >= 1000) || ((tmp2 - tmp) != 3) || (*tmp2 != 0)) { /* Everything else but a 3 digit code is invalid */ return -1; } ri->status_code = (int)l; /* The rest of the line is the status text */ ri->status_text = buf; /* Find end of status text */ /* isgraph or isspace = isprint */ while (isprint(*buf)) { buf++; } if ((*buf != '\r') && (*buf != '\n')) { return -1; } /* Terminate string and forward buf to next line */ do { *buf = 0; buf++; } while ((*buf) && isspace(*buf)); /* Parse all HTTP headers */ ri->num_headers = parse_http_headers(&buf, ri->http_headers); if (ri->num_headers < 0) { /* Error while parsing headers */ return -1; } return response_length + init_skip; } /* Keep reading the input (either opened file descriptor fd, or socket sock, * or SSL descriptor ssl) into buffer buf, until \r\n\r\n appears in the * buffer (which marks the end of HTTP request). Buffer buf may already * have some data. The length of the data is stored in nread. * Upon every read operation, increase nread by the number of bytes read. */ static int read_message(FILE *fp, struct mg_connection *conn, char *buf, int bufsiz, int *nread) { int request_len, n = 0; struct timespec last_action_time; double request_timeout; if (!conn) { return 0; } memset(&last_action_time, 0, sizeof(last_action_time)); if (conn->dom_ctx->config[REQUEST_TIMEOUT]) { /* value of request_timeout is in seconds, config in milliseconds */ request_timeout = atof(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0; } else { request_timeout = -1.0; } if (conn->handled_requests > 0) { if (conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) { request_timeout = atof(conn->dom_ctx->config[KEEP_ALIVE_TIMEOUT]) / 1000.0; } } request_len = get_http_header_len(buf, *nread); /* first time reading from this connection */ clock_gettime(CLOCK_MONOTONIC, &last_action_time); while (request_len == 0) { /* Full request not yet received */ if (conn->phys_ctx->stop_flag != 0) { /* Server is to be stopped. */ return -1; } if (*nread >= bufsiz) { /* Request too long */ return -2; } n = pull_inner( fp, conn, buf + *nread, bufsiz - *nread, request_timeout); if (n == -2) { /* Receive error */ return -1; } if (n > 0) { *nread += n; request_len = get_http_header_len(buf, *nread); } else { request_len = 0; } if ((request_len == 0) && (request_timeout >= 0)) { if (mg_difftimespec(&last_action_time, &(conn->req_time)) > request_timeout) { /* Timeout */ return -1; } clock_gettime(CLOCK_MONOTONIC, &last_action_time); } } return request_len; } #if !defined(NO_CGI) || !defined(NO_FILES) static int forward_body_data(struct mg_connection *conn, FILE *fp, SOCKET sock, SSL *ssl) { const char *expect, *body; char buf[MG_BUF_LEN]; int to_read, nread, success = 0; int64_t buffered_len; double timeout = -1.0; if (!conn) { return 0; } if (conn->dom_ctx->config[REQUEST_TIMEOUT]) { timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0; } expect = mg_get_header(conn, "Expect"); DEBUG_ASSERT(fp != NULL); if (!fp) { mg_send_http_error(conn, 500, "%s", "Error: NULL File"); return 0; } if ((conn->content_len == -1) && (!conn->is_chunked)) { /* Content length is not specified by the client. */ mg_send_http_error(conn, 411, "%s", "Error: Client did not specify content length"); } else if ((expect != NULL) && (mg_strcasecmp(expect, "100-continue") != 0)) { /* Client sent an "Expect: xyz" header and xyz is not 100-continue. */ mg_send_http_error(conn, 417, "Error: Can not fulfill expectation %s", expect); } else { if (expect != NULL) { (void)mg_printf(conn, "%s", "HTTP/1.1 100 Continue\r\n\r\n"); conn->status_code = 100; } else { conn->status_code = 200; } buffered_len = (int64_t)(conn->data_len) - (int64_t)conn->request_len - conn->consumed_content; DEBUG_ASSERT(buffered_len >= 0); DEBUG_ASSERT(conn->consumed_content == 0); if ((buffered_len < 0) || (conn->consumed_content != 0)) { mg_send_http_error(conn, 500, "%s", "Error: Size mismatch"); return 0; } if (buffered_len > 0) { if ((int64_t)buffered_len > conn->content_len) { buffered_len = (int)conn->content_len; } body = conn->buf + conn->request_len + conn->consumed_content; push_all( conn->phys_ctx, fp, sock, ssl, body, (int64_t)buffered_len); conn->consumed_content += buffered_len; } nread = 0; while (conn->consumed_content < conn->content_len) { to_read = sizeof(buf); if ((int64_t)to_read > conn->content_len - conn->consumed_content) { to_read = (int)(conn->content_len - conn->consumed_content); } nread = pull_inner(NULL, conn, buf, to_read, timeout); if (nread == -2) { /* error */ break; } if (nread > 0) { if (push_all(conn->phys_ctx, fp, sock, ssl, buf, nread) != nread) { break; } } conn->consumed_content += nread; } if (conn->consumed_content == conn->content_len) { success = (nread >= 0); } /* Each error code path in this function must send an error */ if (!success) { /* NOTE: Maybe some data has already been sent. */ /* TODO (low): If some data has been sent, a correct error * reply can no longer be sent, so just close the connection */ mg_send_http_error(conn, 500, "%s", ""); } } return success; } #endif #if defined(USE_TIMERS) #define TIMER_API static #include "timer.inl" #endif /* USE_TIMERS */ #if !defined(NO_CGI) /* This structure helps to create an environment for the spawned CGI * program. * Environment is an array of "VARIABLE=VALUE\0" ASCIIZ strings, * last element must be NULL. * However, on Windows there is a requirement that all these * VARIABLE=VALUE\0 * strings must reside in a contiguous buffer. The end of the buffer is * marked by two '\0' characters. * We satisfy both worlds: we create an envp array (which is vars), all * entries are actually pointers inside buf. */ struct cgi_environment { struct mg_connection *conn; /* Data block */ char *buf; /* Environment buffer */ size_t buflen; /* Space available in buf */ size_t bufused; /* Space taken in buf */ /* Index block */ char **var; /* char **envp */ size_t varlen; /* Number of variables available in var */ size_t varused; /* Number of variables stored in var */ }; static void addenv(struct cgi_environment *env, PRINTF_FORMAT_STRING(const char *fmt), ...) PRINTF_ARGS(2, 3); /* Append VARIABLE=VALUE\0 string to the buffer, and add a respective * pointer into the vars array. Assumes env != NULL and fmt != NULL. */ static void addenv(struct cgi_environment *env, const char *fmt, ...) { size_t n, space; int truncated = 0; char *added; va_list ap; /* Calculate how much space is left in the buffer */ space = (env->buflen - env->bufused); /* Calculate an estimate for the required space */ n = strlen(fmt) + 2 + 128; do { if (space <= n) { /* Allocate new buffer */ n = env->buflen + CGI_ENVIRONMENT_SIZE; added = (char *)mg_realloc_ctx(env->buf, n, env->conn->phys_ctx); if (!added) { /* Out of memory */ mg_cry_internal( env->conn, "%s: Cannot allocate memory for CGI variable [%s]", __func__, fmt); return; } env->buf = added; env->buflen = n; space = (env->buflen - env->bufused); } /* Make a pointer to the free space int the buffer */ added = env->buf + env->bufused; /* Copy VARIABLE=VALUE\0 string into the free space */ va_start(ap, fmt); mg_vsnprintf(env->conn, &truncated, added, (size_t)space, fmt, ap); va_end(ap); /* Do not add truncated strings to the environment */ if (truncated) { /* Reallocate the buffer */ space = 0; n = 1; } } while (truncated); /* Calculate number of bytes added to the environment */ n = strlen(added) + 1; env->bufused += n; /* Now update the variable index */ space = (env->varlen - env->varused); if (space < 2) { mg_cry_internal(env->conn, "%s: Cannot register CGI variable [%s]", __func__, fmt); return; } /* Append a pointer to the added string into the envp array */ env->var[env->varused] = added; env->varused++; } /* Return 0 on success, non-zero if an error occurs. */ static int prepare_cgi_environment(struct mg_connection *conn, const char *prog, struct cgi_environment *env) { const char *s; struct vec var_vec; char *p, src_addr[IP_ADDR_STR_LEN], http_var_name[128]; int i, truncated, uri_len; if ((conn == NULL) || (prog == NULL) || (env == NULL)) { return -1; } env->conn = conn; env->buflen = CGI_ENVIRONMENT_SIZE; env->bufused = 0; env->buf = (char *)mg_malloc_ctx(env->buflen, conn->phys_ctx); if (env->buf == NULL) { mg_cry_internal(conn, "%s: Not enough memory for environmental buffer", __func__); return -1; } env->varlen = MAX_CGI_ENVIR_VARS; env->varused = 0; env->var = (char **)mg_malloc_ctx(env->buflen * sizeof(char *), conn->phys_ctx); if (env->var == NULL) { mg_cry_internal(conn, "%s: Not enough memory for environmental variables", __func__); mg_free(env->buf); return -1; } addenv(env, "SERVER_NAME=%s", conn->dom_ctx->config[AUTHENTICATION_DOMAIN]); addenv(env, "SERVER_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]); addenv(env, "DOCUMENT_ROOT=%s", conn->dom_ctx->config[DOCUMENT_ROOT]); addenv(env, "SERVER_SOFTWARE=CivetWeb/%s", mg_version()); /* Prepare the environment block */ addenv(env, "%s", "GATEWAY_INTERFACE=CGI/1.1"); addenv(env, "%s", "SERVER_PROTOCOL=HTTP/1.1"); addenv(env, "%s", "REDIRECT_STATUS=200"); /* For PHP */ #if defined(USE_IPV6) if (conn->client.lsa.sa.sa_family == AF_INET6) { addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin6.sin6_port)); } else #endif { addenv(env, "SERVER_PORT=%d", ntohs(conn->client.lsa.sin.sin_port)); } sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); addenv(env, "REMOTE_ADDR=%s", src_addr); addenv(env, "REQUEST_METHOD=%s", conn->request_info.request_method); addenv(env, "REMOTE_PORT=%d", conn->request_info.remote_port); addenv(env, "REQUEST_URI=%s", conn->request_info.request_uri); addenv(env, "LOCAL_URI=%s", conn->request_info.local_uri); /* SCRIPT_NAME */ uri_len = (int)strlen(conn->request_info.local_uri); if (conn->path_info == NULL) { if (conn->request_info.local_uri[uri_len - 1] != '/') { /* URI: /path_to_script/script.cgi */ addenv(env, "SCRIPT_NAME=%s", conn->request_info.local_uri); } else { /* URI: /path_to_script/ ... using index.cgi */ const char *index_file = strrchr(prog, '/'); if (index_file) { addenv(env, "SCRIPT_NAME=%s%s", conn->request_info.local_uri, index_file + 1); } } } else { /* URI: /path_to_script/script.cgi/path_info */ addenv(env, "SCRIPT_NAME=%.*s", uri_len - (int)strlen(conn->path_info), conn->request_info.local_uri); } addenv(env, "SCRIPT_FILENAME=%s", prog); if (conn->path_info == NULL) { addenv(env, "PATH_TRANSLATED=%s", conn->dom_ctx->config[DOCUMENT_ROOT]); } else { addenv(env, "PATH_TRANSLATED=%s%s", conn->dom_ctx->config[DOCUMENT_ROOT], conn->path_info); } addenv(env, "HTTPS=%s", (conn->ssl == NULL) ? "off" : "on"); if ((s = mg_get_header(conn, "Content-Type")) != NULL) { addenv(env, "CONTENT_TYPE=%s", s); } if (conn->request_info.query_string != NULL) { addenv(env, "QUERY_STRING=%s", conn->request_info.query_string); } if ((s = mg_get_header(conn, "Content-Length")) != NULL) { addenv(env, "CONTENT_LENGTH=%s", s); } if ((s = getenv("PATH")) != NULL) { addenv(env, "PATH=%s", s); } if (conn->path_info != NULL) { addenv(env, "PATH_INFO=%s", conn->path_info); } if (conn->status_code > 0) { /* CGI error handler should show the status code */ addenv(env, "STATUS=%d", conn->status_code); } #if defined(_WIN32) if ((s = getenv("COMSPEC")) != NULL) { addenv(env, "COMSPEC=%s", s); } if ((s = getenv("SYSTEMROOT")) != NULL) { addenv(env, "SYSTEMROOT=%s", s); } if ((s = getenv("SystemDrive")) != NULL) { addenv(env, "SystemDrive=%s", s); } if ((s = getenv("ProgramFiles")) != NULL) { addenv(env, "ProgramFiles=%s", s); } if ((s = getenv("ProgramFiles(x86)")) != NULL) { addenv(env, "ProgramFiles(x86)=%s", s); } #else if ((s = getenv("LD_LIBRARY_PATH")) != NULL) { addenv(env, "LD_LIBRARY_PATH=%s", s); } #endif /* _WIN32 */ if ((s = getenv("PERLLIB")) != NULL) { addenv(env, "PERLLIB=%s", s); } if (conn->request_info.remote_user != NULL) { addenv(env, "REMOTE_USER=%s", conn->request_info.remote_user); addenv(env, "%s", "AUTH_TYPE=Digest"); } /* Add all headers as HTTP_* variables */ for (i = 0; i < conn->request_info.num_headers; i++) { (void)mg_snprintf(conn, &truncated, http_var_name, sizeof(http_var_name), "HTTP_%s", conn->request_info.http_headers[i].name); if (truncated) { mg_cry_internal(conn, "%s: HTTP header variable too long [%s]", __func__, conn->request_info.http_headers[i].name); continue; } /* Convert variable name into uppercase, and change - to _ */ for (p = http_var_name; *p != '\0'; p++) { if (*p == '-') { *p = '_'; } *p = (char)toupper(*(unsigned char *)p); } addenv(env, "%s=%s", http_var_name, conn->request_info.http_headers[i].value); } /* Add user-specified variables */ s = conn->dom_ctx->config[CGI_ENVIRONMENT]; while ((s = next_option(s, &var_vec, NULL)) != NULL) { addenv(env, "%.*s", (int)var_vec.len, var_vec.ptr); } env->var[env->varused] = NULL; env->buf[env->bufused] = '\0'; return 0; } static int abort_process(void *data) { /* Waitpid checks for child status and won't work for a pid that does not * identify a child of the current process. Thus, if the pid is reused, * we will not affect a different process. */ pid_t pid = (pid_t)data; int status = 0; pid_t rpid = waitpid(pid, &status, WNOHANG); if ((rpid != (pid_t)-1) && (status == 0)) { /* Stop child process */ DEBUG_TRACE("CGI timer: Stop child process %p\n", pid); kill(pid, SIGABRT); /* Wait until process is terminated (don't leave zombies) */ while (waitpid(pid, &status, 0) != (pid_t)-1) /* nop */ ; } else { DEBUG_TRACE("CGI timer: Child process %p already stopped in time\n", pid); } return 0; } static void handle_cgi_request(struct mg_connection *conn, const char *prog) { char *buf; size_t buflen; int headers_len, data_len, i, truncated; int fdin[2] = {-1, -1}, fdout[2] = {-1, -1}, fderr[2] = {-1, -1}; const char *status, *status_text, *connection_state; char *pbuf, dir[PATH_MAX], *p; struct mg_request_info ri; struct cgi_environment blk; FILE *in = NULL, *out = NULL, *err = NULL; struct mg_file fout = STRUCT_FILE_INITIALIZER; pid_t pid = (pid_t)-1; if (conn == NULL) { return; } buf = NULL; buflen = conn->phys_ctx->max_request_size; i = prepare_cgi_environment(conn, prog, &blk); if (i != 0) { blk.buf = NULL; blk.var = NULL; goto done; } /* CGI must be executed in its own directory. 'dir' must point to the * directory containing executable program, 'p' must point to the * executable program name relative to 'dir'. */ (void)mg_snprintf(conn, &truncated, dir, sizeof(dir), "%s", prog); if (truncated) { mg_cry_internal(conn, "Error: CGI program \"%s\": Path too long", prog); mg_send_http_error(conn, 500, "Error: %s", "CGI path too long"); goto done; } if ((p = strrchr(dir, '/')) != NULL) { *p++ = '\0'; } else { dir[0] = '.'; dir[1] = '\0'; p = (char *)prog; } if ((pipe(fdin) != 0) || (pipe(fdout) != 0) || (pipe(fderr) != 0)) { status = strerror(ERRNO); mg_cry_internal( conn, "Error: CGI program \"%s\": Can not create CGI pipes: %s", prog, status); mg_send_http_error(conn, 500, "Error: Cannot create CGI pipe: %s", status); goto done; } DEBUG_TRACE("CGI: spawn %s %s\n", dir, p); pid = spawn_process(conn, p, blk.buf, blk.var, fdin, fdout, fderr, dir); if (pid == (pid_t)-1) { status = strerror(ERRNO); mg_cry_internal( conn, "Error: CGI program \"%s\": Can not spawn CGI process: %s", prog, status); mg_send_http_error(conn, 500, "Error: Cannot spawn CGI process [%s]: %s", prog, status); goto done; } #if defined(USE_TIMERS) // TODO (#618): set a timeout timer_add(conn->phys_ctx, /* one minute */ 60.0, 0.0, 1, abort_process, (void *)pid); #endif /* Make sure child closes all pipe descriptors. It must dup them to 0,1 */ set_close_on_exec((SOCKET)fdin[0], conn); /* stdin read */ set_close_on_exec((SOCKET)fdin[1], conn); /* stdin write */ set_close_on_exec((SOCKET)fdout[0], conn); /* stdout read */ set_close_on_exec((SOCKET)fdout[1], conn); /* stdout write */ set_close_on_exec((SOCKET)fderr[0], conn); /* stderr read */ set_close_on_exec((SOCKET)fderr[1], conn); /* stderr write */ /* Parent closes only one side of the pipes. * If we don't mark them as closed, close() attempt before * return from this function throws an exception on Windows. * Windows does not like when closed descriptor is closed again. */ (void)close(fdin[0]); (void)close(fdout[1]); (void)close(fderr[1]); fdin[0] = fdout[1] = fderr[1] = -1; if ((in = fdopen(fdin[1], "wb")) == NULL) { status = strerror(ERRNO); mg_cry_internal(conn, "Error: CGI program \"%s\": Can not open stdin: %s", prog, status); mg_send_http_error(conn, 500, "Error: CGI can not open fdin\nfopen: %s", status); goto done; } if ((out = fdopen(fdout[0], "rb")) == NULL) { status = strerror(ERRNO); mg_cry_internal(conn, "Error: CGI program \"%s\": Can not open stdout: %s", prog, status); mg_send_http_error(conn, 500, "Error: CGI can not open fdout\nfopen: %s", status); goto done; } if ((err = fdopen(fderr[0], "rb")) == NULL) { status = strerror(ERRNO); mg_cry_internal(conn, "Error: CGI program \"%s\": Can not open stderr: %s", prog, status); mg_send_http_error(conn, 500, "Error: CGI can not open fderr\nfopen: %s", status); goto done; } setbuf(in, NULL); setbuf(out, NULL); setbuf(err, NULL); fout.access.fp = out; if ((conn->request_info.content_length != 0) || (conn->is_chunked)) { DEBUG_TRACE("CGI: send body data (%lli)\n", (signed long long)conn->request_info.content_length); /* This is a POST/PUT request, or another request with body data. */ if (!forward_body_data(conn, in, INVALID_SOCKET, NULL)) { /* Error sending the body data */ mg_cry_internal( conn, "Error: CGI program \"%s\": Forward body data failed", prog); goto done; } } /* Close so child gets an EOF. */ fclose(in); in = NULL; fdin[1] = -1; /* Now read CGI reply into a buffer. We need to set correct * status code, thus we need to see all HTTP headers first. * Do not send anything back to client, until we buffer in all * HTTP headers. */ data_len = 0; buf = (char *)mg_malloc_ctx(buflen, conn->phys_ctx); if (buf == NULL) { mg_send_http_error(conn, 500, "Error: Not enough memory for CGI buffer (%u bytes)", (unsigned int)buflen); mg_cry_internal( conn, "Error: CGI program \"%s\": Not enough memory for buffer (%u " "bytes)", prog, (unsigned int)buflen); goto done; } DEBUG_TRACE("CGI: %s", "wait for response"); headers_len = read_message(out, conn, buf, (int)buflen, &data_len); DEBUG_TRACE("CGI: response: %li", (signed long)headers_len); if (headers_len <= 0) { /* Could not parse the CGI response. Check if some error message on * stderr. */ i = pull_all(err, conn, buf, (int)buflen); if (i > 0) { /* CGI program explicitly sent an error */ /* Write the error message to the internal log */ mg_cry_internal(conn, "Error: CGI program \"%s\" sent error " "message: [%.*s]", prog, i, buf); /* Don't send the error message back to the client */ mg_send_http_error(conn, 500, "Error: CGI program \"%s\" failed.", prog); } else { /* CGI program did not explicitly send an error, but a broken * respon header */ mg_cry_internal(conn, "Error: CGI program sent malformed or too big " "(>%u bytes) HTTP headers: [%.*s]", (unsigned)buflen, data_len, buf); mg_send_http_error(conn, 500, "Error: CGI program sent malformed or too big " "(>%u bytes) HTTP headers: [%.*s]", (unsigned)buflen, data_len, buf); } /* in both cases, abort processing CGI */ goto done; } pbuf = buf; buf[headers_len - 1] = '\0'; ri.num_headers = parse_http_headers(&pbuf, ri.http_headers); /* Make up and send the status line */ status_text = "OK"; if ((status = get_header(ri.http_headers, ri.num_headers, "Status")) != NULL) { conn->status_code = atoi(status); status_text = status; while (isdigit(*(const unsigned char *)status_text) || *status_text == ' ') { status_text++; } } else if (get_header(ri.http_headers, ri.num_headers, "Location") != NULL) { conn->status_code = 307; } else { conn->status_code = 200; } connection_state = get_header(ri.http_headers, ri.num_headers, "Connection"); if (!header_has_option(connection_state, "keep-alive")) { conn->must_close = 1; } DEBUG_TRACE("CGI: response %u %s", conn->status_code, status_text); (void)mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, status_text); /* Send headers */ for (i = 0; i < ri.num_headers; i++) { mg_printf(conn, "%s: %s\r\n", ri.http_headers[i].name, ri.http_headers[i].value); } mg_write(conn, "\r\n", 2); /* Send chunk of data that may have been read after the headers */ mg_write(conn, buf + headers_len, (size_t)(data_len - headers_len)); /* Read the rest of CGI output and send to the client */ DEBUG_TRACE("CGI: %s", "forward all data"); send_file_data(conn, &fout, 0, INT64_MAX); DEBUG_TRACE("CGI: %s", "all data sent"); done: mg_free(blk.var); mg_free(blk.buf); if (pid != (pid_t)-1) { abort_process((void *)pid); } if (fdin[0] != -1) { close(fdin[0]); } if (fdout[1] != -1) { close(fdout[1]); } if (in != NULL) { fclose(in); } else if (fdin[1] != -1) { close(fdin[1]); } if (out != NULL) { fclose(out); } else if (fdout[0] != -1) { close(fdout[0]); } if (err != NULL) { fclose(err); } else if (fderr[0] != -1) { close(fderr[0]); } if (buf != NULL) { mg_free(buf); } } #endif /* !NO_CGI */ #if !defined(NO_FILES) static void mkcol(struct mg_connection *conn, const char *path) { int rc, body_len; struct de de; char date[64]; time_t curtime = time(NULL); if (conn == NULL) { return; } /* TODO (mid): Check the mg_send_http_error situations in this function */ memset(&de.file, 0, sizeof(de.file)); if (!mg_stat(conn, path, &de.file)) { mg_cry_internal(conn, "%s: mg_stat(%s) failed: %s", __func__, path, strerror(ERRNO)); } if (de.file.last_modified) { /* TODO (mid): This check does not seem to make any sense ! */ /* TODO (mid): Add a webdav unit test first, before changing * anything here. */ mg_send_http_error( conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO)); return; } body_len = conn->data_len - conn->request_len; if (body_len > 0) { mg_send_http_error( conn, 415, "Error: mkcol(%s): %s", path, strerror(ERRNO)); return; } rc = mg_mkdir(conn, path, 0755); if (rc == 0) { conn->status_code = 201; gmt_time_string(date, sizeof(date), &curtime); mg_printf(conn, "HTTP/1.1 %d Created\r\n" "Date: %s\r\n", conn->status_code, date); send_static_cache_header(conn); send_additional_header(conn); mg_printf(conn, "Content-Length: 0\r\n" "Connection: %s\r\n\r\n", suggest_connection_header(conn)); } else { if (errno == EEXIST) { mg_send_http_error( conn, 405, "Error: mkcol(%s): %s", path, strerror(ERRNO)); } else if (errno == EACCES) { mg_send_http_error( conn, 403, "Error: mkcol(%s): %s", path, strerror(ERRNO)); } else if (errno == ENOENT) { mg_send_http_error( conn, 409, "Error: mkcol(%s): %s", path, strerror(ERRNO)); } else { mg_send_http_error( conn, 500, "fopen(%s): %s", path, strerror(ERRNO)); } } } static void put_file(struct mg_connection *conn, const char *path) { struct mg_file file = STRUCT_FILE_INITIALIZER; const char *range; int64_t r1, r2; int rc; char date[64]; time_t curtime = time(NULL); if (conn == NULL) { return; } if (mg_stat(conn, path, &file.stat)) { /* File already exists */ conn->status_code = 200; if (file.stat.is_directory) { /* This is an already existing directory, * so there is nothing to do for the server. */ rc = 0; } else { /* File exists and is not a directory. */ /* Can it be replaced? */ #if defined(MG_USE_OPEN_FILE) if (file.access.membuf != NULL) { /* This is an "in-memory" file, that can not be replaced */ mg_send_http_error(conn, 405, "Error: Put not possible\nReplacing %s " "is not supported", path); return; } #endif /* Check if the server may write this file */ if (access(path, W_OK) == 0) { /* Access granted */ conn->status_code = 200; rc = 1; } else { mg_send_http_error( conn, 403, "Error: Put not possible\nReplacing %s is not allowed", path); return; } } } else { /* File should be created */ conn->status_code = 201; rc = put_dir(conn, path); } if (rc == 0) { /* put_dir returns 0 if path is a directory */ gmt_time_string(date, sizeof(date), &curtime); mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, mg_get_response_code_text(NULL, conn->status_code)); send_no_cache_header(conn); send_additional_header(conn); mg_printf(conn, "Date: %s\r\n" "Content-Length: 0\r\n" "Connection: %s\r\n\r\n", date, suggest_connection_header(conn)); /* Request to create a directory has been fulfilled successfully. * No need to put a file. */ return; } if (rc == -1) { /* put_dir returns -1 if the path is too long */ mg_send_http_error(conn, 414, "Error: Path too long\nput_dir(%s): %s", path, strerror(ERRNO)); return; } if (rc == -2) { /* put_dir returns -2 if the directory can not be created */ mg_send_http_error(conn, 500, "Error: Can not create directory\nput_dir(%s): %s", path, strerror(ERRNO)); return; } /* A file should be created or overwritten. */ /* Currently CivetWeb does not nead read+write access. */ if (!mg_fopen(conn, path, MG_FOPEN_MODE_WRITE, &file) || file.access.fp == NULL) { (void)mg_fclose(&file.access); mg_send_http_error(conn, 500, "Error: Can not create file\nfopen(%s): %s", path, strerror(ERRNO)); return; } fclose_on_exec(&file.access, conn); range = mg_get_header(conn, "Content-Range"); r1 = r2 = 0; if ((range != NULL) && parse_range_header(range, &r1, &r2) > 0) { conn->status_code = 206; /* Partial content */ fseeko(file.access.fp, r1, SEEK_SET); } if (!forward_body_data(conn, file.access.fp, INVALID_SOCKET, NULL)) { /* forward_body_data failed. * The error code has already been sent to the client, * and conn->status_code is already set. */ (void)mg_fclose(&file.access); return; } if (mg_fclose(&file.access) != 0) { /* fclose failed. This might have different reasons, but a likely * one is "no space on disk", http 507. */ conn->status_code = 507; } gmt_time_string(date, sizeof(date), &curtime); mg_printf(conn, "HTTP/1.1 %d %s\r\n", conn->status_code, mg_get_response_code_text(NULL, conn->status_code)); send_no_cache_header(conn); send_additional_header(conn); mg_printf(conn, "Date: %s\r\n" "Content-Length: 0\r\n" "Connection: %s\r\n\r\n", date, suggest_connection_header(conn)); } static void delete_file(struct mg_connection *conn, const char *path) { struct de de; memset(&de.file, 0, sizeof(de.file)); if (!mg_stat(conn, path, &de.file)) { /* mg_stat returns 0 if the file does not exist */ mg_send_http_error(conn, 404, "Error: Cannot delete file\nFile %s not found", path); return; } #if 0 /* Ignore if a file in memory is inside a folder */ if (de.access.membuf != NULL) { /* the file is cached in memory */ mg_send_http_error( conn, 405, "Error: Delete not possible\nDeleting %s is not supported", path); return; } #endif if (de.file.is_directory) { if (remove_directory(conn, path)) { /* Delete is successful: Return 204 without content. */ mg_send_http_error(conn, 204, "%s", ""); } else { /* Delete is not successful: Return 500 (Server error). */ mg_send_http_error(conn, 500, "Error: Could not delete %s", path); } return; } /* This is an existing file (not a directory). * Check if write permission is granted. */ if (access(path, W_OK) != 0) { /* File is read only */ mg_send_http_error( conn, 403, "Error: Delete not possible\nDeleting %s is not allowed", path); return; } /* Try to delete it. */ if (mg_remove(conn, path) == 0) { /* Delete was successful: Return 204 without content. */ mg_send_http_error(conn, 204, "%s", ""); } else { /* Delete not successful (file locked). */ mg_send_http_error(conn, 423, "Error: Cannot delete file\nremove(%s): %s", path, strerror(ERRNO)); } } #endif /* !NO_FILES */ static void send_ssi_file(struct mg_connection *, const char *, struct mg_file *, int); static void do_ssi_include(struct mg_connection *conn, const char *ssi, char *tag, int include_level) { char file_name[MG_BUF_LEN], path[512], *p; struct mg_file file = STRUCT_FILE_INITIALIZER; size_t len; int truncated = 0; if (conn == NULL) { return; } /* sscanf() is safe here, since send_ssi_file() also uses buffer * of size MG_BUF_LEN to get the tag. So strlen(tag) is * always < MG_BUF_LEN. */ if (sscanf(tag, " virtual=\"%511[^\"]\"", file_name) == 1) { /* File name is relative to the webserver root */ file_name[511] = 0; (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s/%s", conn->dom_ctx->config[DOCUMENT_ROOT], file_name); } else if (sscanf(tag, " abspath=\"%511[^\"]\"", file_name) == 1) { /* File name is relative to the webserver working directory * or it is absolute system path */ file_name[511] = 0; (void) mg_snprintf(conn, &truncated, path, sizeof(path), "%s", file_name); } else if ((sscanf(tag, " file=\"%511[^\"]\"", file_name) == 1) || (sscanf(tag, " \"%511[^\"]\"", file_name) == 1)) { /* File name is relative to the currect document */ file_name[511] = 0; (void)mg_snprintf(conn, &truncated, path, sizeof(path), "%s", ssi); if (!truncated) { if ((p = strrchr(path, '/')) != NULL) { p[1] = '\0'; } len = strlen(path); (void)mg_snprintf(conn, &truncated, path + len, sizeof(path) - len, "%s", file_name); } } else { mg_cry_internal(conn, "Bad SSI #include: [%s]", tag); return; } if (truncated) { mg_cry_internal(conn, "SSI #include path length overflow: [%s]", tag); return; } if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, &file)) { mg_cry_internal(conn, "Cannot open SSI #include: [%s]: fopen(%s): %s", tag, path, strerror(ERRNO)); } else { fclose_on_exec(&file.access, conn); if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS], strlen(conn->dom_ctx->config[SSI_EXTENSIONS]), path) > 0) { send_ssi_file(conn, path, &file, include_level + 1); } else { send_file_data(conn, &file, 0, INT64_MAX); } (void)mg_fclose(&file.access); /* Ignore errors for readonly files */ } } #if !defined(NO_POPEN) static void do_ssi_exec(struct mg_connection *conn, char *tag) { char cmd[1024] = ""; struct mg_file file = STRUCT_FILE_INITIALIZER; if (sscanf(tag, " \"%1023[^\"]\"", cmd) != 1) { mg_cry_internal(conn, "Bad SSI #exec: [%s]", tag); } else { cmd[1023] = 0; if ((file.access.fp = popen(cmd, "r")) == NULL) { mg_cry_internal(conn, "Cannot SSI #exec: [%s]: %s", cmd, strerror(ERRNO)); } else { send_file_data(conn, &file, 0, INT64_MAX); pclose(file.access.fp); } } } #endif /* !NO_POPEN */ static int mg_fgetc(struct mg_file *filep, int offset) { (void)offset; /* unused in case MG_USE_OPEN_FILE is set */ if (filep == NULL) { return EOF; } #if defined(MG_USE_OPEN_FILE) if ((filep->access.membuf != NULL) && (offset >= 0) && (((unsigned int)(offset)) < filep->stat.size)) { return ((const unsigned char *)filep->access.membuf)[offset]; } else /* else block below */ #endif if (filep->access.fp != NULL) { return fgetc(filep->access.fp); } else { return EOF; } } static void send_ssi_file(struct mg_connection *conn, const char *path, struct mg_file *filep, int include_level) { char buf[MG_BUF_LEN]; int ch, offset, len, in_tag, in_ssi_tag; if (include_level > 10) { mg_cry_internal(conn, "SSI #include level is too deep (%s)", path); return; } in_tag = in_ssi_tag = len = offset = 0; /* Read file, byte by byte, and look for SSI include tags */ while ((ch = mg_fgetc(filep, offset++)) != EOF) { if (in_tag) { /* We are in a tag, either SSI tag or html tag */ if (ch == '>') { /* Tag is closing */ buf[len++] = '>'; if (in_ssi_tag) { /* Handle SSI tag */ buf[len] = 0; if ((len > 12) && !memcmp(buf + 5, "include", 7)) { do_ssi_include(conn, path, buf + 12, include_level + 1); #if !defined(NO_POPEN) } else if ((len > 9) && !memcmp(buf + 5, "exec", 4)) { do_ssi_exec(conn, buf + 9); #endif /* !NO_POPEN */ } else { mg_cry_internal(conn, "%s: unknown SSI " "command: \"%s\"", path, buf); } len = 0; in_ssi_tag = in_tag = 0; } else { /* Not an SSI tag */ /* Flush buffer */ (void)mg_write(conn, buf, (size_t)len); len = 0; in_tag = 0; } } else { /* Tag is still open */ buf[len++] = (char)(ch & 0xff); if ((len == 5) && !memcmp(buf, "<!--#", 5)) { /* All SSI tags start with <!--# */ in_ssi_tag = 1; } if ((len + 2) > (int)sizeof(buf)) { /* Tag to long for buffer */ mg_cry_internal(conn, "%s: tag is too large", path); return; } } } else { /* We are not in a tag yet. */ if (ch == '<') { /* Tag is opening */ in_tag = 1; if (len > 0) { /* Flush current buffer. * Buffer is filled with "len" bytes. */ (void)mg_write(conn, buf, (size_t)len); } /* Store the < */ len = 1; buf[0] = '<'; } else { /* No Tag */ /* Add data to buffer */ buf[len++] = (char)(ch & 0xff); /* Flush if buffer is full */ if (len == (int)sizeof(buf)) { mg_write(conn, buf, (size_t)len); len = 0; } } } } /* Send the rest of buffered data */ if (len > 0) { mg_write(conn, buf, (size_t)len); } } static void handle_ssi_file_request(struct mg_connection *conn, const char *path, struct mg_file *filep) { char date[64]; time_t curtime = time(NULL); const char *cors1, *cors2, *cors3; if ((conn == NULL) || (path == NULL) || (filep == NULL)) { return; } if (mg_get_header(conn, "Origin")) { /* Cross-origin resource sharing (CORS). */ cors1 = "Access-Control-Allow-Origin: "; cors2 = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN]; cors3 = "\r\n"; } else { cors1 = cors2 = cors3 = ""; } if (!mg_fopen(conn, path, MG_FOPEN_MODE_READ, filep)) { /* File exists (precondition for calling this function), * but can not be opened by the server. */ mg_send_http_error(conn, 500, "Error: Cannot read file\nfopen(%s): %s", path, strerror(ERRNO)); } else { conn->must_close = 1; gmt_time_string(date, sizeof(date), &curtime); fclose_on_exec(&filep->access, conn); mg_printf(conn, "HTTP/1.1 200 OK\r\n"); send_no_cache_header(conn); send_additional_header(conn); mg_printf(conn, "%s%s%s" "Date: %s\r\n" "Content-Type: text/html\r\n" "Connection: %s\r\n\r\n", cors1, cors2, cors3, date, suggest_connection_header(conn)); send_ssi_file(conn, path, filep, 0); (void)mg_fclose(&filep->access); /* Ignore errors for readonly files */ } } #if !defined(NO_FILES) static void send_options(struct mg_connection *conn) { char date[64]; time_t curtime = time(NULL); if (!conn) { return; } conn->status_code = 200; conn->must_close = 1; gmt_time_string(date, sizeof(date), &curtime); /* We do not set a "Cache-Control" header here, but leave the default. * Since browsers do not send an OPTIONS request, we can not test the * effect anyway. */ mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Date: %s\r\n" "Connection: %s\r\n" "Allow: GET, POST, HEAD, CONNECT, PUT, DELETE, OPTIONS, " "PROPFIND, MKCOL\r\n" "DAV: 1\r\n", date, suggest_connection_header(conn)); send_additional_header(conn); mg_printf(conn, "\r\n"); } /* Writes PROPFIND properties for a collection element */ static void print_props(struct mg_connection *conn, const char *uri, struct mg_file_stat *filep) { char mtime[64]; if ((conn == NULL) || (uri == NULL) || (filep == NULL)) { return; } gmt_time_string(mtime, sizeof(mtime), &filep->last_modified); mg_printf(conn, "<d:response>" "<d:href>%s</d:href>" "<d:propstat>" "<d:prop>" "<d:resourcetype>%s</d:resourcetype>" "<d:getcontentlength>%" INT64_FMT "</d:getcontentlength>" "<d:getlastmodified>%s</d:getlastmodified>" "</d:prop>" "<d:status>HTTP/1.1 200 OK</d:status>" "</d:propstat>" "</d:response>\n", uri, filep->is_directory ? "<d:collection/>" : "", filep->size, mtime); } static int print_dav_dir_entry(struct de *de, void *data) { char href[PATH_MAX]; int truncated; struct mg_connection *conn = (struct mg_connection *)data; if (!de || !conn) { return -1; } mg_snprintf(conn, &truncated, href, sizeof(href), "%s%s", conn->request_info.local_uri, de->file_name); if (!truncated) { size_t href_encoded_size; char *href_encoded; href_encoded_size = PATH_MAX * 3; /* worst case */ href_encoded = (char *)mg_malloc(href_encoded_size); if (href_encoded == NULL) { return -1; } mg_url_encode(href, href_encoded, href_encoded_size); print_props(conn, href_encoded, &de->file); mg_free(href_encoded); } return 0; } static void handle_propfind(struct mg_connection *conn, const char *path, struct mg_file_stat *filep) { const char *depth = mg_get_header(conn, "Depth"); char date[64]; time_t curtime = time(NULL); gmt_time_string(date, sizeof(date), &curtime); if (!conn || !path || !filep || !conn->dom_ctx) { return; } conn->must_close = 1; conn->status_code = 207; mg_printf(conn, "HTTP/1.1 207 Multi-Status\r\n" "Date: %s\r\n", date); send_static_cache_header(conn); send_additional_header(conn); mg_printf(conn, "Connection: %s\r\n" "Content-Type: text/xml; charset=utf-8\r\n\r\n", suggest_connection_header(conn)); mg_printf(conn, "<?xml version=\"1.0\" encoding=\"utf-8\"?>" "<d:multistatus xmlns:d='DAV:'>\n"); /* Print properties for the requested resource itself */ print_props(conn, conn->request_info.local_uri, filep); /* If it is a directory, print directory entries too if Depth is not 0 */ if (filep->is_directory && !mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING], "yes") && ((depth == NULL) || (strcmp(depth, "0") != 0))) { scan_directory(conn, path, conn, &print_dav_dir_entry); } mg_printf(conn, "%s\n", "</d:multistatus>"); } #endif void mg_lock_connection(struct mg_connection *conn) { if (conn) { (void)pthread_mutex_lock(&conn->mutex); } } void mg_unlock_connection(struct mg_connection *conn) { if (conn) { (void)pthread_mutex_unlock(&conn->mutex); } } void mg_lock_context(struct mg_context *ctx) { if (ctx) { (void)pthread_mutex_lock(&ctx->nonce_mutex); } } void mg_unlock_context(struct mg_context *ctx) { if (ctx) { (void)pthread_mutex_unlock(&ctx->nonce_mutex); } } #if defined(USE_LUA) #include "mod_lua.inl" #endif /* USE_LUA */ #if defined(USE_DUKTAPE) #include "mod_duktape.inl" #endif /* USE_DUKTAPE */ #if defined(USE_WEBSOCKET) #if !defined(NO_SSL_DL) #define SHA_API static #include "sha1.inl" #endif static int send_websocket_handshake(struct mg_connection *conn, const char *websock_key) { static const char *magic = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"; char buf[100], sha[20], b64_sha[sizeof(sha) * 2]; SHA_CTX sha_ctx; int truncated; /* Calculate Sec-WebSocket-Accept reply from Sec-WebSocket-Key. */ mg_snprintf(conn, &truncated, buf, sizeof(buf), "%s%s", websock_key, magic); if (truncated) { conn->must_close = 1; return 0; } DEBUG_TRACE("%s", "Send websocket handshake"); SHA1_Init(&sha_ctx); SHA1_Update(&sha_ctx, (unsigned char *)buf, (uint32_t)strlen(buf)); SHA1_Final((unsigned char *)sha, &sha_ctx); base64_encode((unsigned char *)sha, sizeof(sha), b64_sha); mg_printf(conn, "HTTP/1.1 101 Switching Protocols\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Accept: %s\r\n", b64_sha); if (conn->request_info.acceptedWebSocketSubprotocol) { mg_printf(conn, "Sec-WebSocket-Protocol: %s\r\n\r\n", conn->request_info.acceptedWebSocketSubprotocol); } else { mg_printf(conn, "%s", "\r\n"); } return 1; } #if !defined(MG_MAX_UNANSWERED_PING) /* Configuration of the maximum number of websocket PINGs that might * stay unanswered before the connection is considered broken. * Note: The name of this define may still change (until it is * defined as a compile parameter in a documentation). */ #define MG_MAX_UNANSWERED_PING (5) #endif static void read_websocket(struct mg_connection *conn, mg_websocket_data_handler ws_data_handler, void *callback_data) { /* Pointer to the beginning of the portion of the incoming websocket * message queue. * The original websocket upgrade request is never removed, so the queue * begins after it. */ unsigned char *buf = (unsigned char *)conn->buf + conn->request_len; int n, error, exit_by_callback; int ret; /* body_len is the length of the entire queue in bytes * len is the length of the current message * data_len is the length of the current message's data payload * header_len is the length of the current message's header */ size_t i, len, mask_len = 0, header_len, body_len; uint64_t data_len = 0; /* "The masking key is a 32-bit value chosen at random by the client." * http://tools.ietf.org/html/draft-ietf-hybi-thewebsocketprotocol-17#section-5 */ unsigned char mask[4]; /* data points to the place where the message is stored when passed to * the websocket_data callback. This is either mem on the stack, or a * dynamically allocated buffer if it is too large. */ unsigned char mem[4096]; unsigned char mop; /* mask flag and opcode */ /* Variables used for connection monitoring */ double timeout = -1.0; int enable_ping_pong = 0; int ping_count = 0; if (conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG]) { enable_ping_pong = !mg_strcasecmp(conn->dom_ctx->config[ENABLE_WEBSOCKET_PING_PONG], "yes"); } if (conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) { timeout = atoi(conn->dom_ctx->config[WEBSOCKET_TIMEOUT]) / 1000.0; } if ((timeout <= 0.0) && (conn->dom_ctx->config[REQUEST_TIMEOUT])) { timeout = atoi(conn->dom_ctx->config[REQUEST_TIMEOUT]) / 1000.0; } /* Enter data processing loop */ DEBUG_TRACE("Websocket connection %s:%u start data processing loop", conn->request_info.remote_addr, conn->request_info.remote_port); conn->in_websocket_handling = 1; mg_set_thread_name("wsock"); /* Loop continuously, reading messages from the socket, invoking the * callback, and waiting repeatedly until an error occurs. */ while (!conn->phys_ctx->stop_flag && !conn->must_close) { header_len = 0; DEBUG_ASSERT(conn->data_len >= conn->request_len); if ((body_len = (size_t)(conn->data_len - conn->request_len)) >= 2) { len = buf[1] & 127; mask_len = (buf[1] & 128) ? 4 : 0; if ((len < 126) && (body_len >= mask_len)) { /* inline 7-bit length field */ data_len = len; header_len = 2 + mask_len; } else if ((len == 126) && (body_len >= (4 + mask_len))) { /* 16-bit length field */ header_len = 4 + mask_len; data_len = ((((size_t)buf[2]) << 8) + buf[3]); } else if (body_len >= (10 + mask_len)) { /* 64-bit length field */ uint32_t l1, l2; memcpy(&l1, &buf[2], 4); /* Use memcpy for alignment */ memcpy(&l2, &buf[6], 4); header_len = 10 + mask_len; data_len = (((uint64_t)ntohl(l1)) << 32) + ntohl(l2); if (data_len > (uint64_t)0x7FFF0000ul) { /* no can do */ mg_cry_internal( conn, "%s", "websocket out of memory; closing connection"); break; } } } if ((header_len > 0) && (body_len >= header_len)) { /* Allocate space to hold websocket payload */ unsigned char *data = mem; if ((size_t)data_len > (size_t)sizeof(mem)) { data = (unsigned char *)mg_malloc_ctx((size_t)data_len, conn->phys_ctx); if (data == NULL) { /* Allocation failed, exit the loop and then close the * connection */ mg_cry_internal( conn, "%s", "websocket out of memory; closing connection"); break; } } /* Copy the mask before we shift the queue and destroy it */ if (mask_len > 0) { memcpy(mask, buf + header_len - mask_len, sizeof(mask)); } else { memset(mask, 0, sizeof(mask)); } /* Read frame payload from the first message in the queue into * data and advance the queue by moving the memory in place. */ DEBUG_ASSERT(body_len >= header_len); if (data_len + (uint64_t)header_len > (uint64_t)body_len) { mop = buf[0]; /* current mask and opcode */ /* Overflow case */ len = body_len - header_len; memcpy(data, buf + header_len, len); error = 0; while ((uint64_t)len < data_len) { n = pull_inner(NULL, conn, (char *)(data + len), (int)(data_len - len), timeout); if (n <= -2) { error = 1; break; } else if (n > 0) { len += (size_t)n; } else { /* Timeout: should retry */ /* TODO: retry condition */ } } if (error) { mg_cry_internal( conn, "%s", "Websocket pull failed; closing connection"); if (data != mem) { mg_free(data); } break; } conn->data_len = conn->request_len; } else { mop = buf[0]; /* current mask and opcode, overwritten by * memmove() */ /* Length of the message being read at the front of the * queue. Cast to 31 bit is OK, since we limited * data_len before. */ len = (size_t)data_len + header_len; /* Copy the data payload into the data pointer for the * callback. Cast to 31 bit is OK, since we * limited data_len */ memcpy(data, buf + header_len, (size_t)data_len); /* Move the queue forward len bytes */ memmove(buf, buf + len, body_len - len); /* Mark the queue as advanced */ conn->data_len -= (int)len; } /* Apply mask if necessary */ if (mask_len > 0) { for (i = 0; i < (size_t)data_len; i++) { data[i] ^= mask[i & 3]; } } exit_by_callback = 0; if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PONG)) { /* filter PONG messages */ DEBUG_TRACE("PONG from %s:%u", conn->request_info.remote_addr, conn->request_info.remote_port); /* No unanwered PINGs left */ ping_count = 0; } else if (enable_ping_pong && ((mop & 0xF) == MG_WEBSOCKET_OPCODE_PING)) { /* reply PING messages */ DEBUG_TRACE("Reply PING from %s:%u", conn->request_info.remote_addr, conn->request_info.remote_port); ret = mg_websocket_write(conn, MG_WEBSOCKET_OPCODE_PONG, (char *)data, (size_t)data_len); if (ret <= 0) { /* Error: send failed */ DEBUG_TRACE("Reply PONG failed (%i)", ret); break; } } else { /* Exit the loop if callback signals to exit (server side), * or "connection close" opcode received (client side). */ if ((ws_data_handler != NULL) && !ws_data_handler(conn, mop, (char *)data, (size_t)data_len, callback_data)) { exit_by_callback = 1; } } /* It a buffer has been allocated, free it again */ if (data != mem) { mg_free(data); } if (exit_by_callback) { DEBUG_TRACE("Callback requests to close connection from %s:%u", conn->request_info.remote_addr, conn->request_info.remote_port); break; } if ((mop & 0xf) == MG_WEBSOCKET_OPCODE_CONNECTION_CLOSE) { /* Opcode == 8, connection close */ DEBUG_TRACE("Message requests to close connection from %s:%u", conn->request_info.remote_addr, conn->request_info.remote_port); break; } /* Not breaking the loop, process next websocket frame. */ } else { /* Read from the socket into the next available location in the * message queue. */ n = pull_inner(NULL, conn, conn->buf + conn->data_len, conn->buf_size - conn->data_len, timeout); if (n <= -2) { /* Error, no bytes read */ DEBUG_TRACE("PULL from %s:%u failed", conn->request_info.remote_addr, conn->request_info.remote_port); break; } if (n > 0) { conn->data_len += n; /* Reset open PING count */ ping_count = 0; } else { if (!conn->phys_ctx->stop_flag && !conn->must_close) { if (ping_count > MG_MAX_UNANSWERED_PING) { /* Stop sending PING */ DEBUG_TRACE("Too many (%i) unanswered ping from %s:%u " "- closing connection", ping_count, conn->request_info.remote_addr, conn->request_info.remote_port); break; } if (enable_ping_pong) { /* Send Websocket PING message */ DEBUG_TRACE("PING to %s:%u", conn->request_info.remote_addr, conn->request_info.remote_port); ret = mg_websocket_write(conn, MG_WEBSOCKET_OPCODE_PING, NULL, 0); if (ret <= 0) { /* Error: send failed */ DEBUG_TRACE("Send PING failed (%i)", ret); break; } ping_count++; } } /* Timeout: should retry */ /* TODO: get timeout def */ } } } /* Leave data processing loop */ mg_set_thread_name("worker"); conn->in_websocket_handling = 0; DEBUG_TRACE("Websocket connection %s:%u left data processing loop", conn->request_info.remote_addr, conn->request_info.remote_port); } static int mg_websocket_write_exec(struct mg_connection *conn, int opcode, const char *data, size_t dataLen, uint32_t masking_key) { unsigned char header[14]; size_t headerLen; int retval; #if defined(__GNUC__) || defined(__MINGW32__) /* Disable spurious conversion warning for GCC */ #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif header[0] = 0x80u | (unsigned char)((unsigned)opcode & 0xf); #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic pop #endif /* Frame format: http://tools.ietf.org/html/rfc6455#section-5.2 */ if (dataLen < 126) { /* inline 7-bit length field */ header[1] = (unsigned char)dataLen; headerLen = 2; } else if (dataLen <= 0xFFFF) { /* 16-bit length field */ uint16_t len = htons((uint16_t)dataLen); header[1] = 126; memcpy(header + 2, &len, 2); headerLen = 4; } else { /* 64-bit length field */ uint32_t len1 = htonl((uint32_t)((uint64_t)dataLen >> 32)); uint32_t len2 = htonl((uint32_t)(dataLen & 0xFFFFFFFFu)); header[1] = 127; memcpy(header + 2, &len1, 4); memcpy(header + 6, &len2, 4); headerLen = 10; } if (masking_key) { /* add mask */ header[1] |= 0x80; memcpy(header + headerLen, &masking_key, 4); headerLen += 4; } /* Note that POSIX/Winsock's send() is threadsafe * http://stackoverflow.com/questions/1981372/are-parallel-calls-to-send-recv-on-the-same-socket-valid * but mongoose's mg_printf/mg_write is not (because of the loop in * push(), although that is only a problem if the packet is large or * outgoing buffer is full). */ /* TODO: Check if this lock should be moved to user land. * Currently the server sets this lock for websockets, but * not for any other connection. It must be set for every * conn read/written by more than one thread, no matter if * it is a websocket or regular connection. */ (void)mg_lock_connection(conn); retval = mg_write(conn, header, headerLen); if (retval != (int)headerLen) { /* Did not send complete header */ retval = -1; } else { if (dataLen > 0) { retval = mg_write(conn, data, dataLen); } /* if dataLen == 0, the header length (2) is returned */ } /* TODO: Remove this unlock as well, when lock is removed. */ mg_unlock_connection(conn); return retval; } int mg_websocket_write(struct mg_connection *conn, int opcode, const char *data, size_t dataLen) { return mg_websocket_write_exec(conn, opcode, data, dataLen, 0); } static void mask_data(const char *in, size_t in_len, uint32_t masking_key, char *out) { size_t i = 0; i = 0; if ((in_len > 3) && ((ptrdiff_t)in % 4) == 0) { /* Convert in 32 bit words, if data is 4 byte aligned */ while (i < (in_len - 3)) { *(uint32_t *)(void *)(out + i) = *(uint32_t *)(void *)(in + i) ^ masking_key; i += 4; } } if (i != in_len) { /* convert 1-3 remaining bytes if ((dataLen % 4) != 0)*/ while (i < in_len) { *(uint8_t *)(void *)(out + i) = *(uint8_t *)(void *)(in + i) ^ *(((uint8_t *)&masking_key) + (i % 4)); i++; } } } int mg_websocket_client_write(struct mg_connection *conn, int opcode, const char *data, size_t dataLen) { int retval = -1; char *masked_data = (char *)mg_malloc_ctx(((dataLen + 7) / 4) * 4, conn->phys_ctx); uint32_t masking_key = 0; if (masked_data == NULL) { /* Return -1 in an error case */ mg_cry_internal(conn, "%s", "Cannot allocate buffer for masked websocket response: " "Out of memory"); return -1; } do { /* Get a masking key - but not 0 */ masking_key = (uint32_t)get_random(); } while (masking_key == 0); mask_data(data, dataLen, masking_key, masked_data); retval = mg_websocket_write_exec( conn, opcode, masked_data, dataLen, masking_key); mg_free(masked_data); return retval; } static void handle_websocket_request(struct mg_connection *conn, const char *path, int is_callback_resource, struct mg_websocket_subprotocols *subprotocols, mg_websocket_connect_handler ws_connect_handler, mg_websocket_ready_handler ws_ready_handler, mg_websocket_data_handler ws_data_handler, mg_websocket_close_handler ws_close_handler, void *cbData) { const char *websock_key = mg_get_header(conn, "Sec-WebSocket-Key"); const char *version = mg_get_header(conn, "Sec-WebSocket-Version"); ptrdiff_t lua_websock = 0; #if !defined(USE_LUA) (void)path; #endif /* Step 1: Check websocket protocol version. */ /* Step 1.1: Check Sec-WebSocket-Key. */ if (!websock_key) { /* The RFC standard version (https://tools.ietf.org/html/rfc6455) * requires a Sec-WebSocket-Key header. */ /* It could be the hixie draft version * (http://tools.ietf.org/html/draft-hixie-thewebsocketprotocol-76). */ const char *key1 = mg_get_header(conn, "Sec-WebSocket-Key1"); const char *key2 = mg_get_header(conn, "Sec-WebSocket-Key2"); char key3[8]; if ((key1 != NULL) && (key2 != NULL)) { /* This version uses 8 byte body data in a GET request */ conn->content_len = 8; if (8 == mg_read(conn, key3, 8)) { /* This is the hixie version */ mg_send_http_error(conn, 426, "%s", "Protocol upgrade to RFC 6455 required"); return; } } /* This is an unknown version */ mg_send_http_error(conn, 400, "%s", "Malformed websocket request"); return; } /* Step 1.2: Check websocket protocol version. */ /* The RFC version (https://tools.ietf.org/html/rfc6455) is 13. */ if ((version == NULL) || (strcmp(version, "13") != 0)) { /* Reject wrong versions */ mg_send_http_error(conn, 426, "%s", "Protocol upgrade required"); return; } /* Step 1.3: Could check for "Host", but we do not really nead this * value for anything, so just ignore it. */ /* Step 2: If a callback is responsible, call it. */ if (is_callback_resource) { /* Step 2.1 check and select subprotocol */ const char *protocols[64]; // max 64 headers int nbSubprotocolHeader = get_req_headers(&conn->request_info, "Sec-WebSocket-Protocol", protocols, 64); if ((nbSubprotocolHeader > 0) && subprotocols) { int cnt = 0; int idx; unsigned long len; const char *sep, *curSubProtocol, *acceptedWebSocketSubprotocol = NULL; /* look for matching subprotocol */ do { const char *protocol = protocols[cnt]; do { sep = strchr(protocol, ','); curSubProtocol = protocol; len = sep ? (unsigned long)(sep - protocol) : (unsigned long)strlen(protocol); while (sep && isspace(*++sep)) ; // ignore leading whitespaces protocol = sep; for (idx = 0; idx < subprotocols->nb_subprotocols; idx++) { if ((strlen(subprotocols->subprotocols[idx]) == len) && (strncmp(curSubProtocol, subprotocols->subprotocols[idx], len) == 0)) { acceptedWebSocketSubprotocol = subprotocols->subprotocols[idx]; break; } } } while (sep && !acceptedWebSocketSubprotocol); } while (++cnt < nbSubprotocolHeader && !acceptedWebSocketSubprotocol); conn->request_info.acceptedWebSocketSubprotocol = acceptedWebSocketSubprotocol; } else if (nbSubprotocolHeader > 0) { /* keep legacy behavior */ const char *protocol = protocols[0]; /* The protocol is a comma separated list of names. */ /* The server must only return one value from this list. */ /* First check if it is a list or just a single value. */ const char *sep = strrchr(protocol, ','); if (sep == NULL) { /* Just a single protocol -> accept it. */ conn->request_info.acceptedWebSocketSubprotocol = protocol; } else { /* Multiple protocols -> accept the last one. */ /* This is just a quick fix if the client offers multiple * protocols. The handler should have a list of accepted * protocols on his own * and use it to select one protocol among those the client * has * offered. */ while (isspace(*++sep)) { ; /* ignore leading whitespaces */ } conn->request_info.acceptedWebSocketSubprotocol = sep; } } if ((ws_connect_handler != NULL) && (ws_connect_handler(conn, cbData) != 0)) { /* C callback has returned non-zero, do not proceed with * handshake. */ /* Note that C callbacks are no longer called when Lua is * responsible, so C can no longer filter callbacks for Lua. */ return; } } #if defined(USE_LUA) /* Step 3: No callback. Check if Lua is responsible. */ else { /* Step 3.1: Check if Lua is responsible. */ if (conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]) { lua_websock = match_prefix( conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS], strlen(conn->dom_ctx->config[LUA_WEBSOCKET_EXTENSIONS]), path); } if (lua_websock) { /* Step 3.2: Lua is responsible: call it. */ conn->lua_websocket_state = lua_websocket_new(path, conn); if (!conn->lua_websocket_state) { /* Lua rejected the new client */ return; } } } #endif /* Step 4: Check if there is a responsible websocket handler. */ if (!is_callback_resource && !lua_websock) { /* There is no callback, and Lua is not responsible either. */ /* Reply with a 404 Not Found. We are still at a standard * HTTP request here, before the websocket handshake, so * we can still send standard HTTP error replies. */ mg_send_http_error(conn, 404, "%s", "Not found"); return; } /* Step 5: The websocket connection has been accepted */ if (!send_websocket_handshake(conn, websock_key)) { mg_send_http_error(conn, 500, "%s", "Websocket handshake failed"); return; } /* Step 6: Call the ready handler */ if (is_callback_resource) { if (ws_ready_handler != NULL) { ws_ready_handler(conn, cbData); } #if defined(USE_LUA) } else if (lua_websock) { if (!lua_websocket_ready(conn, conn->lua_websocket_state)) { /* the ready handler returned false */ return; } #endif } /* Step 7: Enter the read loop */ if (is_callback_resource) { read_websocket(conn, ws_data_handler, cbData); #if defined(USE_LUA) } else if (lua_websock) { read_websocket(conn, lua_websocket_data, conn->lua_websocket_state); #endif } /* Step 8: Call the close handler */ if (ws_close_handler) { ws_close_handler(conn, cbData); } } static int is_websocket_protocol(const struct mg_connection *conn) { const char *upgrade, *connection; /* A websocket protocoll has the following HTTP headers: * * Connection: Upgrade * Upgrade: Websocket */ upgrade = mg_get_header(conn, "Upgrade"); if (upgrade == NULL) { return 0; /* fail early, don't waste time checking other header * fields */ } if (!mg_strcasestr(upgrade, "websocket")) { return 0; } connection = mg_get_header(conn, "Connection"); if (connection == NULL) { return 0; } if (!mg_strcasestr(connection, "upgrade")) { return 0; } /* The headers "Host", "Sec-WebSocket-Key", "Sec-WebSocket-Protocol" and * "Sec-WebSocket-Version" are also required. * Don't check them here, since even an unsupported websocket protocol * request still IS a websocket request (in contrast to a standard HTTP * request). It will fail later in handle_websocket_request. */ return 1; } #endif /* !USE_WEBSOCKET */ static int isbyte(int n) { return (n >= 0) && (n <= 255); } static int parse_net(const char *spec, uint32_t *net, uint32_t *mask) { int n, a, b, c, d, slash = 32, len = 0; if (((sscanf(spec, "%d.%d.%d.%d/%d%n", &a, &b, &c, &d, &slash, &n) == 5) || (sscanf(spec, "%d.%d.%d.%d%n", &a, &b, &c, &d, &n) == 4)) && isbyte(a) && isbyte(b) && isbyte(c) && isbyte(d) && (slash >= 0) && (slash < 33)) { len = n; *net = ((uint32_t)a << 24) | ((uint32_t)b << 16) | ((uint32_t)c << 8) | (uint32_t)d; *mask = slash ? (0xffffffffU << (32 - slash)) : 0; } return len; } static int set_throttle(const char *spec, uint32_t remote_ip, const char *uri) { int throttle = 0; struct vec vec, val; uint32_t net, mask; char mult; double v; while ((spec = next_option(spec, &vec, &val)) != NULL) { mult = ','; if ((val.ptr == NULL) || (sscanf(val.ptr, "%lf%c", &v, &mult) < 1) || (v < 0) || ((lowercase(&mult) != 'k') && (lowercase(&mult) != 'm') && (mult != ','))) { continue; } v *= (lowercase(&mult) == 'k') ? 1024 : ((lowercase(&mult) == 'm') ? 1048576 : 1); if (vec.len == 1 && vec.ptr[0] == '*') { throttle = (int)v; } else if (parse_net(vec.ptr, &net, &mask) > 0) { if ((remote_ip & mask) == net) { throttle = (int)v; } } else if (match_prefix(vec.ptr, vec.len, uri) > 0) { throttle = (int)v; } } return throttle; } static uint32_t get_remote_ip(const struct mg_connection *conn) { if (!conn) { return 0; } return ntohl(*(const uint32_t *)&conn->client.rsa.sin.sin_addr); } /* The mg_upload function is superseeded by mg_handle_form_request. */ #include "handle_form.inl" #if defined(MG_LEGACY_INTERFACE) /* Implement the deprecated mg_upload function by calling the new * mg_handle_form_request function. While mg_upload could only handle * HTML forms sent as POST request in multipart/form-data format * containing only file input elements, mg_handle_form_request can * handle all form input elements and all standard request methods. */ struct mg_upload_user_data { struct mg_connection *conn; const char *destination_dir; int num_uploaded_files; }; /* Helper function for deprecated mg_upload. */ static int mg_upload_field_found(const char *key, const char *filename, char *path, size_t pathlen, void *user_data) { int truncated = 0; struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data; (void)key; if (!filename) { mg_cry_internal(fud->conn, "%s: No filename set", __func__); return FORM_FIELD_STORAGE_ABORT; } mg_snprintf(fud->conn, &truncated, path, pathlen - 1, "%s/%s", fud->destination_dir, filename); if (truncated) { mg_cry_internal(fud->conn, "%s: File path too long", __func__); return FORM_FIELD_STORAGE_ABORT; } return FORM_FIELD_STORAGE_STORE; } /* Helper function for deprecated mg_upload. */ static int mg_upload_field_get(const char *key, const char *value, size_t value_size, void *user_data) { /* Function should never be called */ (void)key; (void)value; (void)value_size; (void)user_data; return 0; } /* Helper function for deprecated mg_upload. */ static int mg_upload_field_stored(const char *path, long long file_size, void *user_data) { struct mg_upload_user_data *fud = (struct mg_upload_user_data *)user_data; (void)file_size; fud->num_uploaded_files++; fud->conn->phys_ctx->callbacks.upload(fud->conn, path); return 0; } /* Deprecated function mg_upload - use mg_handle_form_request instead. */ int mg_upload(struct mg_connection *conn, const char *destination_dir) { struct mg_upload_user_data fud = {conn, destination_dir, 0}; struct mg_form_data_handler fdh = {mg_upload_field_found, mg_upload_field_get, mg_upload_field_stored, 0}; int ret; fdh.user_data = (void *)&fud; ret = mg_handle_form_request(conn, &fdh); if (ret < 0) { mg_cry_internal(conn, "%s: Error while parsing the request", __func__); } return fud.num_uploaded_files; } #endif static int get_first_ssl_listener_index(const struct mg_context *ctx) { unsigned int i; int idx = -1; if (ctx) { for (i = 0; ((idx == -1) && (i < ctx->num_listening_sockets)); i++) { idx = ctx->listening_sockets[i].is_ssl ? ((int)(i)) : -1; } } return idx; } /* Return host (without port) */ /* Use mg_free to free the result */ static const char * alloc_get_host(struct mg_connection *conn) { char buf[1025]; size_t buflen = sizeof(buf); const char *host_header = get_header(conn->request_info.http_headers, conn->request_info.num_headers, "Host"); char *host; if (host_header != NULL) { char *pos; /* Create a local copy of the "Host" header, since it might be * modified here. */ mg_strlcpy(buf, host_header, buflen); buf[buflen - 1] = '\0'; host = buf; while (isspace(*host)) { host++; } /* If the "Host" is an IPv6 address, like [::1], parse until ] * is found. */ if (*host == '[') { pos = strchr(host, ']'); if (!pos) { /* Malformed hostname starts with '[', but no ']' found */ DEBUG_TRACE("%s", "Host name format error '[' without ']'"); return NULL; } /* terminate after ']' */ pos[1] = 0; } else { /* Otherwise, a ':' separates hostname and port number */ pos = strchr(host, ':'); if (pos != NULL) { *pos = '\0'; } } if (conn->ssl) { /* This is a HTTPS connection, maybe we have a hostname * from SNI (set in ssl_servername_callback). */ const char *sslhost = conn->dom_ctx->config[AUTHENTICATION_DOMAIN]; if (sslhost && (conn->dom_ctx != &(conn->phys_ctx->dd))) { /* We are not using the default domain */ if (mg_strcasecmp(host, sslhost)) { /* Mismatch between SNI domain and HTTP domain */ DEBUG_TRACE("Host mismatch: SNI: %s, HTTPS: %s", sslhost, host); return NULL; } } DEBUG_TRACE("HTTPS Host: %s", host); } else { struct mg_domain_context *dom = &(conn->phys_ctx->dd); while (dom) { if (!mg_strcasecmp(host, dom->config[AUTHENTICATION_DOMAIN])) { /* Found matching domain */ DEBUG_TRACE("HTTP domain %s found", dom->config[AUTHENTICATION_DOMAIN]); /* TODO: Check if this is a HTTP or HTTPS domain */ conn->dom_ctx = dom; break; } dom = dom->next; } DEBUG_TRACE("HTTP Host: %s", host); } } else { sockaddr_to_string(buf, buflen, &conn->client.lsa); host = buf; DEBUG_TRACE("IP: %s", host); } return mg_strdup_ctx(host, conn->phys_ctx); } static void redirect_to_https_port(struct mg_connection *conn, int ssl_index) { char target_url[MG_BUF_LEN]; int truncated = 0; conn->must_close = 1; /* Send host, port, uri and (if it exists) ?query_string */ if (conn->host) { /* Use "308 Permanent Redirect" */ int redirect_code = 308; /* Create target URL */ mg_snprintf( conn, &truncated, target_url, sizeof(target_url), "Location: https://%s:%d%s%s%s", conn->host, #if defined(USE_IPV6) (conn->phys_ctx->listening_sockets[ssl_index].lsa.sa.sa_family == AF_INET6) ? (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index] .lsa.sin6.sin6_port) : #endif (int)ntohs(conn->phys_ctx->listening_sockets[ssl_index] .lsa.sin.sin_port), conn->request_info.local_uri, (conn->request_info.query_string == NULL) ? "" : "?", (conn->request_info.query_string == NULL) ? "" : conn->request_info.query_string); /* Check overflow in location buffer (will not occur if MG_BUF_LEN * is used as buffer size) */ if (truncated) { mg_send_http_error(conn, 500, "%s", "Redirect URL too long"); return; } /* Use redirect helper function */ mg_send_http_redirect(conn, target_url, redirect_code); } } static void handler_info_acquire(struct mg_handler_info *handler_info) { pthread_mutex_lock(&handler_info->refcount_mutex); handler_info->refcount++; pthread_mutex_unlock(&handler_info->refcount_mutex); } static void handler_info_release(struct mg_handler_info *handler_info) { pthread_mutex_lock(&handler_info->refcount_mutex); handler_info->refcount--; pthread_cond_signal(&handler_info->refcount_cond); pthread_mutex_unlock(&handler_info->refcount_mutex); } static void handler_info_wait_unused(struct mg_handler_info *handler_info) { pthread_mutex_lock(&handler_info->refcount_mutex); while (handler_info->refcount) { pthread_cond_wait(&handler_info->refcount_cond, &handler_info->refcount_mutex); } pthread_mutex_unlock(&handler_info->refcount_mutex); } static void mg_set_handler_type(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *uri, int handler_type, int is_delete_request, mg_request_handler handler, struct mg_websocket_subprotocols *subprotocols, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, mg_authorization_handler auth_handler, void *cbdata) { struct mg_handler_info *tmp_rh, **lastref; size_t urilen = strlen(uri); if (handler_type == WEBSOCKET_HANDLER) { DEBUG_ASSERT(handler == NULL); DEBUG_ASSERT(is_delete_request || connect_handler != NULL || ready_handler != NULL || data_handler != NULL || close_handler != NULL); DEBUG_ASSERT(auth_handler == NULL); if (handler != NULL) { return; } if (!is_delete_request && (connect_handler == NULL) && (ready_handler == NULL) && (data_handler == NULL) && (close_handler == NULL)) { return; } if (auth_handler != NULL) { return; } } else if (handler_type == REQUEST_HANDLER) { DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL && data_handler == NULL && close_handler == NULL); DEBUG_ASSERT(is_delete_request || (handler != NULL)); DEBUG_ASSERT(auth_handler == NULL); if ((connect_handler != NULL) || (ready_handler != NULL) || (data_handler != NULL) || (close_handler != NULL)) { return; } if (!is_delete_request && (handler == NULL)) { return; } if (auth_handler != NULL) { return; } } else { /* AUTH_HANDLER */ DEBUG_ASSERT(handler == NULL); DEBUG_ASSERT(connect_handler == NULL && ready_handler == NULL && data_handler == NULL && close_handler == NULL); DEBUG_ASSERT(auth_handler != NULL); if (handler != NULL) { return; } if ((connect_handler != NULL) || (ready_handler != NULL) || (data_handler != NULL) || (close_handler != NULL)) { return; } if (!is_delete_request && (auth_handler == NULL)) { return; } } if (!phys_ctx || !dom_ctx) { return; } mg_lock_context(phys_ctx); /* first try to find an existing handler */ lastref = &(dom_ctx->handlers); for (tmp_rh = dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) { if (tmp_rh->handler_type == handler_type) { if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) { if (!is_delete_request) { /* update existing handler */ if (handler_type == REQUEST_HANDLER) { /* Wait for end of use before updating */ handler_info_wait_unused(tmp_rh); /* Ok, the handler is no more use -> Update it */ tmp_rh->handler = handler; } else if (handler_type == WEBSOCKET_HANDLER) { tmp_rh->subprotocols = subprotocols; tmp_rh->connect_handler = connect_handler; tmp_rh->ready_handler = ready_handler; tmp_rh->data_handler = data_handler; tmp_rh->close_handler = close_handler; } else { /* AUTH_HANDLER */ tmp_rh->auth_handler = auth_handler; } tmp_rh->cbdata = cbdata; } else { /* remove existing handler */ if (handler_type == REQUEST_HANDLER) { /* Wait for end of use before removing */ handler_info_wait_unused(tmp_rh); /* Ok, the handler is no more used -> Destroy resources */ pthread_cond_destroy(&tmp_rh->refcount_cond); pthread_mutex_destroy(&tmp_rh->refcount_mutex); } *lastref = tmp_rh->next; mg_free(tmp_rh->uri); mg_free(tmp_rh); } mg_unlock_context(phys_ctx); return; } } lastref = &(tmp_rh->next); } if (is_delete_request) { /* no handler to set, this was a remove request to a non-existing * handler */ mg_unlock_context(phys_ctx); return; } tmp_rh = (struct mg_handler_info *)mg_calloc_ctx(sizeof(struct mg_handler_info), 1, phys_ctx); if (tmp_rh == NULL) { mg_unlock_context(phys_ctx); mg_cry_internal(fc(phys_ctx), "%s", "Cannot create new request handler struct, OOM"); return; } tmp_rh->uri = mg_strdup_ctx(uri, phys_ctx); if (!tmp_rh->uri) { mg_unlock_context(phys_ctx); mg_free(tmp_rh); mg_cry_internal(fc(phys_ctx), "%s", "Cannot create new request handler struct, OOM"); return; } tmp_rh->uri_len = urilen; if (handler_type == REQUEST_HANDLER) { /* Init refcount mutex and condition */ if (0 != pthread_mutex_init(&tmp_rh->refcount_mutex, NULL)) { mg_unlock_context(phys_ctx); mg_free(tmp_rh); mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount mutex"); return; } if (0 != pthread_cond_init(&tmp_rh->refcount_cond, NULL)) { mg_unlock_context(phys_ctx); pthread_mutex_destroy(&tmp_rh->refcount_mutex); mg_free(tmp_rh); mg_cry_internal(fc(phys_ctx), "%s", "Cannot init refcount cond"); return; } tmp_rh->refcount = 0; tmp_rh->handler = handler; } else if (handler_type == WEBSOCKET_HANDLER) { tmp_rh->subprotocols = subprotocols; tmp_rh->connect_handler = connect_handler; tmp_rh->ready_handler = ready_handler; tmp_rh->data_handler = data_handler; tmp_rh->close_handler = close_handler; } else { /* AUTH_HANDLER */ tmp_rh->auth_handler = auth_handler; } tmp_rh->cbdata = cbdata; tmp_rh->handler_type = handler_type; tmp_rh->next = NULL; *lastref = tmp_rh; mg_unlock_context(phys_ctx); } void mg_set_request_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata) { mg_set_handler_type(ctx, &(ctx->dd), uri, REQUEST_HANDLER, handler == NULL, handler, NULL, NULL, NULL, NULL, NULL, NULL, cbdata); } void mg_set_websocket_handler(struct mg_context *ctx, const char *uri, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, void *cbdata) { mg_set_websocket_handler_with_subprotocols(ctx, uri, NULL, connect_handler, ready_handler, data_handler, close_handler, cbdata); } void mg_set_websocket_handler_with_subprotocols( struct mg_context *ctx, const char *uri, struct mg_websocket_subprotocols *subprotocols, mg_websocket_connect_handler connect_handler, mg_websocket_ready_handler ready_handler, mg_websocket_data_handler data_handler, mg_websocket_close_handler close_handler, void *cbdata) { int is_delete_request = (connect_handler == NULL) && (ready_handler == NULL) && (data_handler == NULL) && (close_handler == NULL); mg_set_handler_type(ctx, &(ctx->dd), uri, WEBSOCKET_HANDLER, is_delete_request, NULL, subprotocols, connect_handler, ready_handler, data_handler, close_handler, NULL, cbdata); } void mg_set_auth_handler(struct mg_context *ctx, const char *uri, mg_request_handler handler, void *cbdata) { mg_set_handler_type(ctx, &(ctx->dd), uri, AUTH_HANDLER, handler == NULL, NULL, NULL, NULL, NULL, NULL, NULL, handler, cbdata); } static int get_request_handler(struct mg_connection *conn, int handler_type, mg_request_handler *handler, struct mg_websocket_subprotocols **subprotocols, mg_websocket_connect_handler *connect_handler, mg_websocket_ready_handler *ready_handler, mg_websocket_data_handler *data_handler, mg_websocket_close_handler *close_handler, mg_authorization_handler *auth_handler, void **cbdata, struct mg_handler_info **handler_info) { const struct mg_request_info *request_info = mg_get_request_info(conn); if (request_info) { const char *uri = request_info->local_uri; size_t urilen = strlen(uri); struct mg_handler_info *tmp_rh; if (!conn || !conn->phys_ctx || !conn->dom_ctx) { return 0; } mg_lock_context(conn->phys_ctx); /* first try for an exact match */ for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) { if (tmp_rh->handler_type == handler_type) { if ((urilen == tmp_rh->uri_len) && !strcmp(tmp_rh->uri, uri)) { if (handler_type == WEBSOCKET_HANDLER) { *subprotocols = tmp_rh->subprotocols; *connect_handler = tmp_rh->connect_handler; *ready_handler = tmp_rh->ready_handler; *data_handler = tmp_rh->data_handler; *close_handler = tmp_rh->close_handler; } else if (handler_type == REQUEST_HANDLER) { *handler = tmp_rh->handler; /* Acquire handler and give it back */ handler_info_acquire(tmp_rh); *handler_info = tmp_rh; } else { /* AUTH_HANDLER */ *auth_handler = tmp_rh->auth_handler; } *cbdata = tmp_rh->cbdata; mg_unlock_context(conn->phys_ctx); return 1; } } } /* next try for a partial match, we will accept uri/something */ for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) { if (tmp_rh->handler_type == handler_type) { if ((tmp_rh->uri_len < urilen) && (uri[tmp_rh->uri_len] == '/') && (memcmp(tmp_rh->uri, uri, tmp_rh->uri_len) == 0)) { if (handler_type == WEBSOCKET_HANDLER) { *subprotocols = tmp_rh->subprotocols; *connect_handler = tmp_rh->connect_handler; *ready_handler = tmp_rh->ready_handler; *data_handler = tmp_rh->data_handler; *close_handler = tmp_rh->close_handler; } else if (handler_type == REQUEST_HANDLER) { *handler = tmp_rh->handler; /* Acquire handler and give it back */ handler_info_acquire(tmp_rh); *handler_info = tmp_rh; } else { /* AUTH_HANDLER */ *auth_handler = tmp_rh->auth_handler; } *cbdata = tmp_rh->cbdata; mg_unlock_context(conn->phys_ctx); return 1; } } } /* finally try for pattern match */ for (tmp_rh = conn->dom_ctx->handlers; tmp_rh != NULL; tmp_rh = tmp_rh->next) { if (tmp_rh->handler_type == handler_type) { if (match_prefix(tmp_rh->uri, tmp_rh->uri_len, uri) > 0) { if (handler_type == WEBSOCKET_HANDLER) { *subprotocols = tmp_rh->subprotocols; *connect_handler = tmp_rh->connect_handler; *ready_handler = tmp_rh->ready_handler; *data_handler = tmp_rh->data_handler; *close_handler = tmp_rh->close_handler; } else if (handler_type == REQUEST_HANDLER) { *handler = tmp_rh->handler; /* Acquire handler and give it back */ handler_info_acquire(tmp_rh); *handler_info = tmp_rh; } else { /* AUTH_HANDLER */ *auth_handler = tmp_rh->auth_handler; } *cbdata = tmp_rh->cbdata; mg_unlock_context(conn->phys_ctx); return 1; } } } mg_unlock_context(conn->phys_ctx); } return 0; /* none found */ } /* Check if the script file is in a path, allowed for script files. * This can be used if uploading files is possible not only for the server * admin, and the upload mechanism does not check the file extension. */ static int is_in_script_path(const struct mg_connection *conn, const char *path) { /* TODO (Feature): Add config value for allowed script path. * Default: All allowed. */ (void)conn; (void)path; return 1; } #if defined(USE_WEBSOCKET) && defined(MG_LEGACY_INTERFACE) static int deprecated_websocket_connect_wrapper(const struct mg_connection *conn, void *cbdata) { struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata; if (pcallbacks->websocket_connect) { return pcallbacks->websocket_connect(conn); } /* No handler set - assume "OK" */ return 0; } static void deprecated_websocket_ready_wrapper(struct mg_connection *conn, void *cbdata) { struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata; if (pcallbacks->websocket_ready) { pcallbacks->websocket_ready(conn); } } static int deprecated_websocket_data_wrapper(struct mg_connection *conn, int bits, char *data, size_t len, void *cbdata) { struct mg_callbacks *pcallbacks = (struct mg_callbacks *)cbdata; if (pcallbacks->websocket_data) { return pcallbacks->websocket_data(conn, bits, data, len); } /* No handler set - assume "OK" */ return 1; } #endif /* This is the heart of the Civetweb's logic. * This function is called when the request is read, parsed and validated, * and Civetweb must decide what action to take: serve a file, or * a directory, or call embedded function, etcetera. */ static void handle_request(struct mg_connection *conn) { struct mg_request_info *ri = &conn->request_info; char path[PATH_MAX]; int uri_len, ssl_index; int is_found = 0, is_script_resource = 0, is_websocket_request = 0, is_put_or_delete_request = 0, is_callback_resource = 0; int i; struct mg_file file = STRUCT_FILE_INITIALIZER; mg_request_handler callback_handler = NULL; struct mg_handler_info *handler_info = NULL; struct mg_websocket_subprotocols *subprotocols; mg_websocket_connect_handler ws_connect_handler = NULL; mg_websocket_ready_handler ws_ready_handler = NULL; mg_websocket_data_handler ws_data_handler = NULL; mg_websocket_close_handler ws_close_handler = NULL; void *callback_data = NULL; mg_authorization_handler auth_handler = NULL; void *auth_callback_data = NULL; int handler_type; time_t curtime = time(NULL); char date[64]; path[0] = 0; /* 1. get the request url */ /* 1.1. split into url and query string */ if ((conn->request_info.query_string = strchr(ri->request_uri, '?')) != NULL) { *((char *)conn->request_info.query_string++) = '\0'; } /* 1.2. do a https redirect, if required. Do not decode URIs yet. */ if (!conn->client.is_ssl && conn->client.ssl_redir) { ssl_index = get_first_ssl_listener_index(conn->phys_ctx); if (ssl_index >= 0) { redirect_to_https_port(conn, ssl_index); } else { /* A http to https forward port has been specified, * but no https port to forward to. */ mg_send_http_error(conn, 503, "%s", "Error: SSL forward not configured properly"); mg_cry_internal(conn, "%s", "Can not redirect to SSL, no SSL port available"); } return; } uri_len = (int)strlen(ri->local_uri); /* 1.3. decode url (if config says so) */ if (should_decode_url(conn)) { mg_url_decode( ri->local_uri, uri_len, (char *)ri->local_uri, uri_len + 1, 0); } /* 1.4. clean URIs, so a path like allowed_dir/../forbidden_file is * not possible */ remove_double_dots_and_double_slashes((char *)ri->local_uri); /* step 1. completed, the url is known now */ uri_len = (int)strlen(ri->local_uri); DEBUG_TRACE("URL: %s", ri->local_uri); /* 2. if this ip has limited speed, set it for this connection */ conn->throttle = set_throttle(conn->dom_ctx->config[THROTTLE], get_remote_ip(conn), ri->local_uri); /* 3. call a "handle everything" callback, if registered */ if (conn->phys_ctx->callbacks.begin_request != NULL) { /* Note that since V1.7 the "begin_request" function is called * before an authorization check. If an authorization check is * required, use a request_handler instead. */ i = conn->phys_ctx->callbacks.begin_request(conn); if (i > 0) { /* callback already processed the request. Store the return value as a status code for the access log. */ conn->status_code = i; discard_unread_request_data(conn); return; } else if (i == 0) { /* civetweb should process the request */ } else { /* unspecified - may change with the next version */ return; } } /* request not yet handled by a handler or redirect, so the request * is processed here */ /* 4. Check for CORS preflight requests and handle them (if configured). * https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS */ if (!strcmp(ri->request_method, "OPTIONS")) { /* Send a response to CORS preflights only if * access_control_allow_methods is not NULL and not an empty string. * In this case, scripts can still handle CORS. */ const char *cors_meth_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_METHODS]; const char *cors_orig_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_ORIGIN]; const char *cors_origin = get_header(ri->http_headers, ri->num_headers, "Origin"); const char *cors_acrm = get_header(ri->http_headers, ri->num_headers, "Access-Control-Request-Method"); /* Todo: check if cors_origin is in cors_orig_cfg. * Or, let the client check this. */ if ((cors_meth_cfg != NULL) && (*cors_meth_cfg != 0) && (cors_orig_cfg != NULL) && (*cors_orig_cfg != 0) && (cors_origin != NULL) && (cors_acrm != NULL)) { /* This is a valid CORS preflight, and the server is configured * to * handle it automatically. */ const char *cors_acrh = get_header(ri->http_headers, ri->num_headers, "Access-Control-Request-Headers"); gmt_time_string(date, sizeof(date), &curtime); mg_printf(conn, "HTTP/1.1 200 OK\r\n" "Date: %s\r\n" "Access-Control-Allow-Origin: %s\r\n" "Access-Control-Allow-Methods: %s\r\n" "Content-Length: 0\r\n" "Connection: %s\r\n", date, cors_orig_cfg, ((cors_meth_cfg[0] == '*') ? cors_acrm : cors_meth_cfg), suggest_connection_header(conn)); if (cors_acrh != NULL) { /* CORS request is asking for additional headers */ const char *cors_hdr_cfg = conn->dom_ctx->config[ACCESS_CONTROL_ALLOW_HEADERS]; if ((cors_hdr_cfg != NULL) && (*cors_hdr_cfg != 0)) { /* Allow only if access_control_allow_headers is * not NULL and not an empty string. If this * configuration is set to *, allow everything. * Otherwise this configuration must be a list * of allowed HTTP header names. */ mg_printf(conn, "Access-Control-Allow-Headers: %s\r\n", ((cors_hdr_cfg[0] == '*') ? cors_acrh : cors_hdr_cfg)); } } mg_printf(conn, "Access-Control-Max-Age: 60\r\n"); mg_printf(conn, "\r\n"); return; } } /* 5. interpret the url to find out how the request must be handled */ /* 5.1. first test, if the request targets the regular http(s):// * protocol namespace or the websocket ws(s):// protocol namespace. */ is_websocket_request = is_websocket_protocol(conn); #if defined(USE_WEBSOCKET) handler_type = is_websocket_request ? WEBSOCKET_HANDLER : REQUEST_HANDLER; #else handler_type = REQUEST_HANDLER; #endif /* defined(USE_WEBSOCKET) */ /* 5.2. check if the request will be handled by a callback */ if (get_request_handler(conn, handler_type, &callback_handler, &subprotocols, &ws_connect_handler, &ws_ready_handler, &ws_data_handler, &ws_close_handler, NULL, &callback_data, &handler_info)) { /* 5.2.1. A callback will handle this request. All requests * handled * by a callback have to be considered as requests to a script * resource. */ is_callback_resource = 1; is_script_resource = 1; is_put_or_delete_request = is_put_or_delete_method(conn); } else { no_callback_resource: /* 5.2.2. No callback is responsible for this request. The URI * addresses a file based resource (static content or Lua/cgi * scripts in the file system). */ is_callback_resource = 0; interpret_uri(conn, path, sizeof(path), &file.stat, &is_found, &is_script_resource, &is_websocket_request, &is_put_or_delete_request); } /* 6. authorization check */ /* 6.1. a custom authorization handler is installed */ if (get_request_handler(conn, AUTH_HANDLER, NULL, NULL, NULL, NULL, NULL, NULL, &auth_handler, &auth_callback_data, NULL)) { if (!auth_handler(conn, auth_callback_data)) { return; } } else if (is_put_or_delete_request && !is_script_resource && !is_callback_resource) { /* 6.2. this request is a PUT/DELETE to a real file */ /* 6.2.1. thus, the server must have real files */ #if defined(NO_FILES) if (1) { #else if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) { #endif /* This server does not have any real files, thus the * PUT/DELETE methods are not valid. */ mg_send_http_error(conn, 405, "%s method not allowed", conn->request_info.request_method); return; } #if !defined(NO_FILES) /* 6.2.2. Check if put authorization for static files is * available. */ if (!is_authorized_for_put(conn)) { send_authorization_request(conn, NULL); return; } #endif } else { /* 6.3. This is either a OPTIONS, GET, HEAD or POST request, * or it is a PUT or DELETE request to a resource that does not * correspond to a file. Check authorization. */ if (!check_authorization(conn, path)) { send_authorization_request(conn, NULL); return; } } /* request is authorized or does not need authorization */ /* 7. check if there are request handlers for this uri */ if (is_callback_resource) { if (!is_websocket_request) { i = callback_handler(conn, callback_data); /* Callback handler will not be used anymore. Release it */ handler_info_release(handler_info); if (i > 0) { /* Do nothing, callback has served the request. Store * then return value as status code for the log and discard * all data from the client not used by the callback. */ conn->status_code = i; discard_unread_request_data(conn); } else { /* The handler did NOT handle the request. */ /* Some proper reactions would be: * a) close the connections without sending anything * b) send a 404 not found * c) try if there is a file matching the URI * It would be possible to do a, b or c in the callback * implementation, and return 1 - we cannot do anything * here, that is not possible in the callback. * * TODO: What would be the best reaction here? * (Note: The reaction may change, if there is a better *idea.) */ /* For the moment, use option c: We look for a proper file, * but since a file request is not always a script resource, * the authorization check might be different. */ interpret_uri(conn, path, sizeof(path), &file.stat, &is_found, &is_script_resource, &is_websocket_request, &is_put_or_delete_request); callback_handler = NULL; /* Here we are at a dead end: * According to URI matching, a callback should be * responsible for handling the request, * we called it, but the callback declared itself * not responsible. * We use a goto here, to get out of this dead end, * and continue with the default handling. * A goto here is simpler and better to understand * than some curious loop. */ goto no_callback_resource; } } else { #if defined(USE_WEBSOCKET) handle_websocket_request(conn, path, is_callback_resource, subprotocols, ws_connect_handler, ws_ready_handler, ws_data_handler, ws_close_handler, callback_data); #endif } return; } /* 8. handle websocket requests */ #if defined(USE_WEBSOCKET) if (is_websocket_request) { if (is_script_resource) { if (is_in_script_path(conn, path)) { /* Websocket Lua script */ handle_websocket_request(conn, path, 0 /* Lua Script */, NULL, NULL, NULL, NULL, NULL, conn->phys_ctx->user_data); } else { /* Script was in an illegal path */ mg_send_http_error(conn, 403, "%s", "Forbidden"); } } else { #if defined(MG_LEGACY_INTERFACE) handle_websocket_request( conn, path, !is_script_resource /* could be deprecated global callback */, NULL, deprecated_websocket_connect_wrapper, deprecated_websocket_ready_wrapper, deprecated_websocket_data_wrapper, NULL, conn->phys_ctx->user_data); #else mg_send_http_error(conn, 404, "%s", "Not found"); #endif } return; } else #endif #if defined(NO_FILES) /* 9a. In case the server uses only callbacks, this uri is * unknown. * Then, all request handling ends here. */ mg_send_http_error(conn, 404, "%s", "Not Found"); #else /* 9b. This request is either for a static file or resource handled * by a script file. Thus, a DOCUMENT_ROOT must exist. */ if (conn->dom_ctx->config[DOCUMENT_ROOT] == NULL) { mg_send_http_error(conn, 404, "%s", "Not Found"); return; } /* 10. Request is handled by a script */ if (is_script_resource) { handle_file_based_request(conn, path, &file); return; } /* 11. Handle put/delete/mkcol requests */ if (is_put_or_delete_request) { /* 11.1. PUT method */ if (!strcmp(ri->request_method, "PUT")) { put_file(conn, path); return; } /* 11.2. DELETE method */ if (!strcmp(ri->request_method, "DELETE")) { delete_file(conn, path); return; } /* 11.3. MKCOL method */ if (!strcmp(ri->request_method, "MKCOL")) { mkcol(conn, path); return; } /* 11.4. PATCH method * This method is not supported for static resources, * only for scripts (Lua, CGI) and callbacks. */ mg_send_http_error(conn, 405, "%s method not allowed", conn->request_info.request_method); return; } /* 11. File does not exist, or it was configured that it should be * hidden */ if (!is_found || (must_hide_file(conn, path))) { mg_send_http_error(conn, 404, "%s", "Not found"); return; } /* 12. Directory uris should end with a slash */ if (file.stat.is_directory && (uri_len > 0) && (ri->local_uri[uri_len - 1] != '/')) { gmt_time_string(date, sizeof(date), &curtime); mg_printf(conn, "HTTP/1.1 301 Moved Permanently\r\n" "Location: %s/\r\n" "Date: %s\r\n" /* "Cache-Control: private\r\n" (= default) */ "Content-Length: 0\r\n" "Connection: %s\r\n", ri->request_uri, date, suggest_connection_header(conn)); send_additional_header(conn); mg_printf(conn, "\r\n"); return; } /* 13. Handle other methods than GET/HEAD */ /* 13.1. Handle PROPFIND */ if (!strcmp(ri->request_method, "PROPFIND")) { handle_propfind(conn, path, &file.stat); return; } /* 13.2. Handle OPTIONS for files */ if (!strcmp(ri->request_method, "OPTIONS")) { /* This standard handler is only used for real files. * Scripts should support the OPTIONS method themselves, to allow a * maximum flexibility. * Lua and CGI scripts may fully support CORS this way (including * preflights). */ send_options(conn); return; } /* 13.3. everything but GET and HEAD (e.g. POST) */ if ((0 != strcmp(ri->request_method, "GET")) && (0 != strcmp(ri->request_method, "HEAD"))) { mg_send_http_error(conn, 405, "%s method not allowed", conn->request_info.request_method); return; } /* 14. directories */ if (file.stat.is_directory) { /* Substitute files have already been handled above. */ /* Here we can either generate and send a directory listing, * or send an "access denied" error. */ if (!mg_strcasecmp(conn->dom_ctx->config[ENABLE_DIRECTORY_LISTING], "yes")) { handle_directory_request(conn, path); } else { mg_send_http_error(conn, 403, "%s", "Error: Directory listing denied"); } return; } /* 15. read a normal file with GET or HEAD */ handle_file_based_request(conn, path, &file); #endif /* !defined(NO_FILES) */ } static void handle_file_based_request(struct mg_connection *conn, const char *path, struct mg_file *file) { if (!conn || !conn->dom_ctx) { return; } if (0) { #if defined(USE_LUA) } else if (match_prefix( conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS], strlen(conn->dom_ctx->config[LUA_SERVER_PAGE_EXTENSIONS]), path) > 0) { if (is_in_script_path(conn, path)) { /* Lua server page: an SSI like page containing mostly plain * html * code * plus some tags with server generated contents. */ handle_lsp_request(conn, path, file, NULL); } else { /* Script was in an illegal path */ mg_send_http_error(conn, 403, "%s", "Forbidden"); } } else if (match_prefix(conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS], strlen( conn->dom_ctx->config[LUA_SCRIPT_EXTENSIONS]), path) > 0) { if (is_in_script_path(conn, path)) { /* Lua in-server module script: a CGI like script used to * generate * the * entire reply. */ mg_exec_lua_script(conn, path, NULL); } else { /* Script was in an illegal path */ mg_send_http_error(conn, 403, "%s", "Forbidden"); } #endif #if defined(USE_DUKTAPE) } else if (match_prefix( conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS], strlen(conn->dom_ctx->config[DUKTAPE_SCRIPT_EXTENSIONS]), path) > 0) { if (is_in_script_path(conn, path)) { /* Call duktape to generate the page */ mg_exec_duktape_script(conn, path); } else { /* Script was in an illegal path */ mg_send_http_error(conn, 403, "%s", "Forbidden"); } #endif #if !defined(NO_CGI) } else if (match_prefix(conn->dom_ctx->config[CGI_EXTENSIONS], strlen(conn->dom_ctx->config[CGI_EXTENSIONS]), path) > 0) { if (is_in_script_path(conn, path)) { /* CGI scripts may support all HTTP methods */ handle_cgi_request(conn, path); } else { /* Script was in an illegal path */ mg_send_http_error(conn, 403, "%s", "Forbidden"); } #endif /* !NO_CGI */ } else if (match_prefix(conn->dom_ctx->config[SSI_EXTENSIONS], strlen(conn->dom_ctx->config[SSI_EXTENSIONS]), path) > 0) { if (is_in_script_path(conn, path)) { handle_ssi_file_request(conn, path, file); } else { /* Script was in an illegal path */ mg_send_http_error(conn, 403, "%s", "Forbidden"); } #if !defined(NO_CACHING) } else if ((!conn->in_error_handler) && is_not_modified(conn, &file->stat)) { /* Send 304 "Not Modified" - this must not send any body data */ handle_not_modified_static_file_request(conn, file); #endif /* !NO_CACHING */ } else { handle_static_file_request(conn, path, file, NULL, NULL); } } static void close_all_listening_sockets(struct mg_context *ctx) { unsigned int i; if (!ctx) { return; } for (i = 0; i < ctx->num_listening_sockets; i++) { closesocket(ctx->listening_sockets[i].sock); ctx->listening_sockets[i].sock = INVALID_SOCKET; } mg_free(ctx->listening_sockets); ctx->listening_sockets = NULL; mg_free(ctx->listening_socket_fds); ctx->listening_socket_fds = NULL; } /* Valid listening port specification is: [ip_address:]port[s] * Examples for IPv4: 80, 443s, 127.0.0.1:3128, 192.0.2.3:8080s * Examples for IPv6: [::]:80, [::1]:80, * [2001:0db8:7654:3210:FEDC:BA98:7654:3210]:443s * see https://tools.ietf.org/html/rfc3513#section-2.2 * In order to bind to both, IPv4 and IPv6, you can either add * both ports using 8080,[::]:8080, or the short form +8080. * Both forms differ in detail: 8080,[::]:8080 create two sockets, * one only accepting IPv4 the other only IPv6. +8080 creates * one socket accepting IPv4 and IPv6. Depending on the IPv6 * environment, they might work differently, or might not work * at all - it must be tested what options work best in the * relevant network environment. */ static int parse_port_string(const struct vec *vec, struct socket *so, int *ip_version) { unsigned int a, b, c, d, port; int ch, len; const char *cb; #if defined(USE_IPV6) char buf[100] = {0}; #endif /* MacOS needs that. If we do not zero it, subsequent bind() will fail. * Also, all-zeroes in the socket address means binding to all addresses * for both IPv4 and IPv6 (INADDR_ANY and IN6ADDR_ANY_INIT). */ memset(so, 0, sizeof(*so)); so->lsa.sin.sin_family = AF_INET; *ip_version = 0; /* Initialize port and len as invalid. */ port = 0; len = 0; /* Test for different ways to format this string */ if (sscanf(vec->ptr, "%u.%u.%u.%u:%u%n", &a, &b, &c, &d, &port, &len) == 5) { /* Bind to a specific IPv4 address, e.g. 192.168.1.5:8080 */ so->lsa.sin.sin_addr.s_addr = htonl((a << 24) | (b << 16) | (c << 8) | d); so->lsa.sin.sin_port = htons((uint16_t)port); *ip_version = 4; #if defined(USE_IPV6) } else if (sscanf(vec->ptr, "[%49[^]]]:%u%n", buf, &port, &len) == 2 && mg_inet_pton( AF_INET6, buf, &so->lsa.sin6, sizeof(so->lsa.sin6))) { /* IPv6 address, examples: see above */ /* so->lsa.sin6.sin6_family = AF_INET6; already set by mg_inet_pton */ so->lsa.sin6.sin6_port = htons((uint16_t)port); *ip_version = 6; #endif } else if ((vec->ptr[0] == '+') && (sscanf(vec->ptr + 1, "%u%n", &port, &len) == 1)) { /* Port is specified with a +, bind to IPv6 and IPv4, INADDR_ANY */ /* Add 1 to len for the + character we skipped before */ len++; #if defined(USE_IPV6) /* Set socket family to IPv6, do not use IPV6_V6ONLY */ so->lsa.sin6.sin6_family = AF_INET6; so->lsa.sin6.sin6_port = htons((uint16_t)port); *ip_version = 4 + 6; #else /* Bind to IPv4 only, since IPv6 is not built in. */ so->lsa.sin.sin_port = htons((uint16_t)port); *ip_version = 4; #endif } else if (sscanf(vec->ptr, "%u%n", &port, &len) == 1) { /* If only port is specified, bind to IPv4, INADDR_ANY */ so->lsa.sin.sin_port = htons((uint16_t)port); *ip_version = 4; } else if ((cb = strchr(vec->ptr, ':')) != NULL) { /* String could be a hostname. This check algotithm * will only work for RFC 952 compliant hostnames, * starting with a letter, containing only letters, * digits and hyphen ('-'). Newer specs may allow * more, but this is not guaranteed here, since it * may interfere with rules for port option lists. */ /* According to RFC 1035, hostnames are restricted to 255 characters * in total (63 between two dots). */ char hostname[256]; size_t hostnlen = (size_t)(cb - vec->ptr); if (hostnlen >= sizeof(hostname)) { /* This would be invalid in any case */ *ip_version = 0; return 0; } memcpy(hostname, vec->ptr, hostnlen); hostname[hostnlen] = 0; if (mg_inet_pton( AF_INET, vec->ptr, &so->lsa.sin, sizeof(so->lsa.sin))) { if (sscanf(cb + 1, "%u%n", &port, &len) == 1) { *ip_version = 4; so->lsa.sin.sin_family = AF_INET; so->lsa.sin.sin_port = htons((uint16_t)port); len += (int)(hostnlen + 1); } else { port = 0; len = 0; } #if defined(USE_IPV6) } else if (mg_inet_pton(AF_INET6, vec->ptr, &so->lsa.sin6, sizeof(so->lsa.sin6))) { if (sscanf(cb + 1, "%u%n", &port, &len) == 1) { *ip_version = 6; so->lsa.sin6.sin6_family = AF_INET6; so->lsa.sin.sin_port = htons((uint16_t)port); len += (int)(hostnlen + 1); } else { port = 0; len = 0; } #endif } } else { /* Parsing failure. */ } /* sscanf and the option splitting code ensure the following condition */ if ((len < 0) && ((unsigned)len > (unsigned)vec->len)) { *ip_version = 0; return 0; } ch = vec->ptr[len]; /* Next character after the port number */ so->is_ssl = (ch == 's'); so->ssl_redir = (ch == 'r'); /* Make sure the port is valid and vector ends with 's', 'r' or ',' */ if (is_valid_port(port) && ((ch == '\0') || (ch == 's') || (ch == 'r') || (ch == ','))) { return 1; } /* Reset ip_version to 0 if there is an error */ *ip_version = 0; return 0; } /* Is there any SSL port in use? */ static int is_ssl_port_used(const char *ports) { if (ports) { /* There are several different allowed syntax variants: * - "80" for a single port using every network interface * - "localhost:80" for a single port using only localhost * - "80,localhost:8080" for two ports, one bound to localhost * - "80,127.0.0.1:8084,[::1]:8086" for three ports, one bound * to IPv4 localhost, one to IPv6 localhost * - "+80" use port 80 for IPv4 and IPv6 * - "+80r,+443s" port 80 (HTTP) is a redirect to port 443 (HTTPS), * for both: IPv4 and IPv4 * - "+443s,localhost:8080" port 443 (HTTPS) for every interface, * additionally port 8080 bound to localhost connections * * If we just look for 's' anywhere in the string, "localhost:80" * will be detected as SSL (false positive). * Looking for 's' after a digit may cause false positives in * "my24service:8080". * Looking from 's' backward if there are only ':' and numbers * before will not work for "24service:8080" (non SSL, port 8080) * or "24s" (SSL, port 24). * * Remark: Initially hostnames were not allowed to start with a * digit (according to RFC 952), this was allowed later (RFC 1123, * Section 2.1). * * To get this correct, the entire string must be parsed as a whole, * reading it as a list element for element and parsing with an * algorithm equivalent to parse_port_string. * * In fact, we use local interface names here, not arbitrary hostnames, * so in most cases the only name will be "localhost". * * So, for now, we use this simple algorithm, that may still return * a false positive in bizarre cases. */ int i; int portslen = (int)strlen(ports); char prevIsNumber = 0; for (i = 0; i < portslen; i++) { if (prevIsNumber && (ports[i] == 's' || ports[i] == 'r')) { return 1; } if (ports[i] >= '0' && ports[i] <= '9') { prevIsNumber = 1; } else { prevIsNumber = 0; } } } return 0; } static int set_ports_option(struct mg_context *phys_ctx) { const char *list; int on = 1; #if defined(USE_IPV6) int off = 0; #endif struct vec vec; struct socket so, *ptr; struct pollfd *pfd; union usa usa; socklen_t len; int ip_version; int portsTotal = 0; int portsOk = 0; if (!phys_ctx) { return 0; } memset(&so, 0, sizeof(so)); memset(&usa, 0, sizeof(usa)); len = sizeof(usa); list = phys_ctx->dd.config[LISTENING_PORTS]; while ((list = next_option(list, &vec, NULL)) != NULL) { portsTotal++; if (!parse_port_string(&vec, &so, &ip_version)) { mg_cry_internal( fc(phys_ctx), "%.*s: invalid port spec (entry %i). Expecting list of: %s", (int)vec.len, vec.ptr, portsTotal, "[IP_ADDRESS:]PORT[s|r]"); continue; } #if !defined(NO_SSL) if (so.is_ssl && phys_ctx->dd.ssl_ctx == NULL) { mg_cry_internal(fc(phys_ctx), "Cannot add SSL socket (entry %i)", portsTotal); continue; } #endif if ((so.sock = socket(so.lsa.sa.sa_family, SOCK_STREAM, 6)) == INVALID_SOCKET) { mg_cry_internal(fc(phys_ctx), "cannot create socket (entry %i)", portsTotal); continue; } #if defined(_WIN32) /* Windows SO_REUSEADDR lets many procs binds to a * socket, SO_EXCLUSIVEADDRUSE makes the bind fail * if someone already has the socket -- DTL */ /* NOTE: If SO_EXCLUSIVEADDRUSE is used, * Windows might need a few seconds before * the same port can be used again in the * same process, so a short Sleep may be * required between mg_stop and mg_start. */ if (setsockopt(so.sock, SOL_SOCKET, SO_EXCLUSIVEADDRUSE, (SOCK_OPT_TYPE)&on, sizeof(on)) != 0) { /* Set reuse option, but don't abort on errors. */ mg_cry_internal( fc(phys_ctx), "cannot set socket option SO_EXCLUSIVEADDRUSE (entry %i)", portsTotal); } #else if (setsockopt(so.sock, SOL_SOCKET, SO_REUSEADDR, (SOCK_OPT_TYPE)&on, sizeof(on)) != 0) { /* Set reuse option, but don't abort on errors. */ mg_cry_internal(fc(phys_ctx), "cannot set socket option SO_REUSEADDR (entry %i)", portsTotal); } #endif if (ip_version > 4) { /* Could be 6 for IPv6 onlyor 10 (4+6) for IPv4+IPv6 */ #if defined(USE_IPV6) if (ip_version > 6) { if (so.lsa.sa.sa_family == AF_INET6 && setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&off, sizeof(off)) != 0) { /* Set IPv6 only option, but don't abort on errors. */ mg_cry_internal( fc(phys_ctx), "cannot set socket option IPV6_V6ONLY=off (entry %i)", portsTotal); } } else { if (so.lsa.sa.sa_family == AF_INET6 && setsockopt(so.sock, IPPROTO_IPV6, IPV6_V6ONLY, (void *)&on, sizeof(on)) != 0) { /* Set IPv6 only option, but don't abort on errors. */ mg_cry_internal( fc(phys_ctx), "cannot set socket option IPV6_V6ONLY=on (entry %i)", portsTotal); } } #else mg_cry_internal(fc(phys_ctx), "%s", "IPv6 not available"); closesocket(so.sock); so.sock = INVALID_SOCKET; continue; #endif } if (so.lsa.sa.sa_family == AF_INET) { len = sizeof(so.lsa.sin); if (bind(so.sock, &so.lsa.sa, len) != 0) { mg_cry_internal(fc(phys_ctx), "cannot bind to %.*s: %d (%s)", (int)vec.len, vec.ptr, (int)ERRNO, strerror(errno)); closesocket(so.sock); so.sock = INVALID_SOCKET; continue; } } #if defined(USE_IPV6) else if (so.lsa.sa.sa_family == AF_INET6) { len = sizeof(so.lsa.sin6); if (bind(so.sock, &so.lsa.sa, len) != 0) { mg_cry_internal(fc(phys_ctx), "cannot bind to IPv6 %.*s: %d (%s)", (int)vec.len, vec.ptr, (int)ERRNO, strerror(errno)); closesocket(so.sock); so.sock = INVALID_SOCKET; continue; } } #endif else { mg_cry_internal( fc(phys_ctx), "cannot bind: address family not supported (entry %i)", portsTotal); closesocket(so.sock); so.sock = INVALID_SOCKET; continue; } if (listen(so.sock, SOMAXCONN) != 0) { mg_cry_internal(fc(phys_ctx), "cannot listen to %.*s: %d (%s)", (int)vec.len, vec.ptr, (int)ERRNO, strerror(errno)); closesocket(so.sock); so.sock = INVALID_SOCKET; continue; } if ((getsockname(so.sock, &(usa.sa), &len) != 0) || (usa.sa.sa_family != so.lsa.sa.sa_family)) { int err = (int)ERRNO; mg_cry_internal(fc(phys_ctx), "call to getsockname failed %.*s: %d (%s)", (int)vec.len, vec.ptr, err, strerror(errno)); closesocket(so.sock); so.sock = INVALID_SOCKET; continue; } /* Update lsa port in case of random free ports */ #if defined(USE_IPV6) if (so.lsa.sa.sa_family == AF_INET6) { so.lsa.sin6.sin6_port = usa.sin6.sin6_port; } else #endif { so.lsa.sin.sin_port = usa.sin.sin_port; } if ((ptr = (struct socket *) mg_realloc_ctx(phys_ctx->listening_sockets, (phys_ctx->num_listening_sockets + 1) * sizeof(phys_ctx->listening_sockets[0]), phys_ctx)) == NULL) { mg_cry_internal(fc(phys_ctx), "%s", "Out of memory"); closesocket(so.sock); so.sock = INVALID_SOCKET; continue; } if ((pfd = (struct pollfd *) mg_realloc_ctx(phys_ctx->listening_socket_fds, (phys_ctx->num_listening_sockets + 1) * sizeof(phys_ctx->listening_socket_fds[0]), phys_ctx)) == NULL) { mg_cry_internal(fc(phys_ctx), "%s", "Out of memory"); closesocket(so.sock); so.sock = INVALID_SOCKET; mg_free(ptr); continue; } set_close_on_exec(so.sock, fc(phys_ctx)); phys_ctx->listening_sockets = ptr; phys_ctx->listening_sockets[phys_ctx->num_listening_sockets] = so; phys_ctx->listening_socket_fds = pfd; phys_ctx->num_listening_sockets++; portsOk++; } if (portsOk != portsTotal) { close_all_listening_sockets(phys_ctx); portsOk = 0; } return portsOk; } static const char * header_val(const struct mg_connection *conn, const char *header) { const char *header_value; if ((header_value = mg_get_header(conn, header)) == NULL) { return "-"; } else { return header_value; } } #if defined(MG_EXTERNAL_FUNCTION_log_access) static void log_access(const struct mg_connection *conn); #include "external_log_access.inl" #else static void log_access(const struct mg_connection *conn) { const struct mg_request_info *ri; struct mg_file fi; char date[64], src_addr[IP_ADDR_STR_LEN]; struct tm *tm; const char *referer; const char *user_agent; char buf[4096]; if (!conn || !conn->dom_ctx) { return; } if (conn->dom_ctx->config[ACCESS_LOG_FILE] != NULL) { if (mg_fopen(conn, conn->dom_ctx->config[ACCESS_LOG_FILE], MG_FOPEN_MODE_APPEND, &fi) == 0) { fi.access.fp = NULL; } } else { fi.access.fp = NULL; } /* Log is written to a file and/or a callback. If both are not set, * executing the rest of the function is pointless. */ if ((fi.access.fp == NULL) && (conn->phys_ctx->callbacks.log_access == NULL)) { return; } tm = localtime(&conn->conn_birth_time); if (tm != NULL) { strftime(date, sizeof(date), "%d/%b/%Y:%H:%M:%S %z", tm); } else { mg_strlcpy(date, "01/Jan/1970:00:00:00 +0000", sizeof(date)); date[sizeof(date) - 1] = '\0'; } ri = &conn->request_info; sockaddr_to_string(src_addr, sizeof(src_addr), &conn->client.rsa); referer = header_val(conn, "Referer"); user_agent = header_val(conn, "User-Agent"); mg_snprintf(conn, NULL, /* Ignore truncation in access log */ buf, sizeof(buf), "%s - %s [%s] \"%s %s%s%s HTTP/%s\" %d %" INT64_FMT " %s %s", src_addr, (ri->remote_user == NULL) ? "-" : ri->remote_user, date, ri->request_method ? ri->request_method : "-", ri->request_uri ? ri->request_uri : "-", ri->query_string ? "?" : "", ri->query_string ? ri->query_string : "", ri->http_version, conn->status_code, conn->num_bytes_sent, referer, user_agent); if (conn->phys_ctx->callbacks.log_access) { conn->phys_ctx->callbacks.log_access(conn, buf); } if (fi.access.fp) { int ok = 1; flockfile(fi.access.fp); if (fprintf(fi.access.fp, "%s\n", buf) < 1) { ok = 0; } if (fflush(fi.access.fp) != 0) { ok = 0; } funlockfile(fi.access.fp); if (mg_fclose(&fi.access) != 0) { ok = 0; } if (!ok) { mg_cry_internal(conn, "Error writing log file %s", conn->dom_ctx->config[ACCESS_LOG_FILE]); } } } #endif /* Externally provided function */ /* Verify given socket address against the ACL. * Return -1 if ACL is malformed, 0 if address is disallowed, 1 if allowed. */ static int check_acl(struct mg_context *phys_ctx, uint32_t remote_ip) { int allowed, flag; uint32_t net, mask; struct vec vec; if (phys_ctx) { const char *list = phys_ctx->dd.config[ACCESS_CONTROL_LIST]; /* If any ACL is set, deny by default */ allowed = (list == NULL) ? '+' : '-'; while ((list = next_option(list, &vec, NULL)) != NULL) { flag = vec.ptr[0]; if ((flag != '+' && flag != '-') || (parse_net(&vec.ptr[1], &net, &mask) == 0)) { mg_cry_internal(fc(phys_ctx), "%s: subnet must be [+|-]x.x.x.x[/x]", __func__); return -1; } if (net == (remote_ip & mask)) { allowed = flag; } } return allowed == '+'; } return -1; } #if !defined(_WIN32) static int set_uid_option(struct mg_context *phys_ctx) { int success = 0; if (phys_ctx) { /* We are currently running as curr_uid. */ const uid_t curr_uid = getuid(); /* If set, we want to run as run_as_user. */ const char *run_as_user = phys_ctx->dd.config[RUN_AS_USER]; const struct passwd *to_pw = NULL; if (run_as_user != NULL && (to_pw = getpwnam(run_as_user)) == NULL) { /* run_as_user does not exist on the system. We can't proceed * further. */ mg_cry_internal(fc(phys_ctx), "%s: unknown user [%s]", __func__, run_as_user); } else if (run_as_user == NULL || curr_uid == to_pw->pw_uid) { /* There was either no request to change user, or we're already * running as run_as_user. Nothing else to do. */ success = 1; } else { /* Valid change request. */ if (setgid(to_pw->pw_gid) == -1) { mg_cry_internal(fc(phys_ctx), "%s: setgid(%s): %s", __func__, run_as_user, strerror(errno)); } else if (setgroups(0, NULL) == -1) { mg_cry_internal(fc(phys_ctx), "%s: setgroups(): %s", __func__, strerror(errno)); } else if (setuid(to_pw->pw_uid) == -1) { mg_cry_internal(fc(phys_ctx), "%s: setuid(%s): %s", __func__, run_as_user, strerror(errno)); } else { success = 1; } } } return success; } #endif /* !_WIN32 */ static void tls_dtor(void *key) { struct mg_workerTLS *tls = (struct mg_workerTLS *)key; /* key == pthread_getspecific(sTlsKey); */ if (tls) { if (tls->is_master == 2) { tls->is_master = -3; /* Mark memory as dead */ mg_free(tls); } } pthread_setspecific(sTlsKey, NULL); } #if !defined(NO_SSL) static int ssl_use_pem_file(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *pem, const char *chain); static const char *ssl_error(void); static int refresh_trust(struct mg_connection *conn) { static int reload_lock = 0; static long int data_check = 0; volatile int *p_reload_lock = (volatile int *)&reload_lock; struct stat cert_buf; long int t; const char *pem; const char *chain; int should_verify_peer; if ((pem = conn->dom_ctx->config[SSL_CERTIFICATE]) == NULL) { /* If peem is NULL and conn->phys_ctx->callbacks.init_ssl is not, * refresh_trust still can not work. */ return 0; } chain = conn->dom_ctx->config[SSL_CERTIFICATE_CHAIN]; if (chain == NULL) { /* pem is not NULL here */ chain = pem; } if (*chain == 0) { chain = NULL; } t = data_check; if (stat(pem, &cert_buf) != -1) { t = (long int)cert_buf.st_mtime; } if (data_check != t) { data_check = t; should_verify_peer = 0; if (conn->dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) { if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) { should_verify_peer = 1; } else if (mg_strcasecmp(conn->dom_ctx->config[SSL_DO_VERIFY_PEER], "optional") == 0) { should_verify_peer = 1; } } if (should_verify_peer) { char *ca_path = conn->dom_ctx->config[SSL_CA_PATH]; char *ca_file = conn->dom_ctx->config[SSL_CA_FILE]; if (SSL_CTX_load_verify_locations(conn->dom_ctx->ssl_ctx, ca_file, ca_path) != 1) { mg_cry_internal( fc(conn->phys_ctx), "SSL_CTX_load_verify_locations error: %s " "ssl_verify_peer requires setting " "either ssl_ca_path or ssl_ca_file. Is any of them " "present in " "the .conf file?", ssl_error()); return 0; } } if (1 == mg_atomic_inc(p_reload_lock)) { if (ssl_use_pem_file(conn->phys_ctx, conn->dom_ctx, pem, chain) == 0) { return 0; } *p_reload_lock = 0; } } /* lock while cert is reloading */ while (*p_reload_lock) { sleep(1); } return 1; } #if defined(OPENSSL_API_1_1) #else static pthread_mutex_t *ssl_mutexes; #endif /* OPENSSL_API_1_1 */ static int sslize(struct mg_connection *conn, SSL_CTX *s, int (*func)(SSL *), volatile int *stop_server) { int ret, err; int short_trust; unsigned i; if (!conn) { return 0; } short_trust = (conn->dom_ctx->config[SSL_SHORT_TRUST] != NULL) && (mg_strcasecmp(conn->dom_ctx->config[SSL_SHORT_TRUST], "yes") == 0); if (short_trust) { int trust_ret = refresh_trust(conn); if (!trust_ret) { return trust_ret; } } conn->ssl = SSL_new(s); if (conn->ssl == NULL) { return 0; } SSL_set_app_data(conn->ssl, (char *)conn); ret = SSL_set_fd(conn->ssl, conn->client.sock); if (ret != 1) { err = SSL_get_error(conn->ssl, ret); mg_cry_internal(conn, "SSL error %i, destroying SSL context", err); SSL_free(conn->ssl); conn->ssl = NULL; /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion: * https://wiki.openssl.org/index.php/Talk:Library_Initialization */ #if !defined(OPENSSL_API_1_1) ERR_remove_state(0); #endif return 0; } /* SSL functions may fail and require to be called again: * see https://www.openssl.org/docs/manmaster/ssl/SSL_get_error.html * Here "func" could be SSL_connect or SSL_accept. */ for (i = 16; i <= 1024; i *= 2) { ret = func(conn->ssl); if (ret != 1) { err = SSL_get_error(conn->ssl, ret); if ((err == SSL_ERROR_WANT_CONNECT) || (err == SSL_ERROR_WANT_ACCEPT) || (err == SSL_ERROR_WANT_READ) || (err == SSL_ERROR_WANT_WRITE) || (err == SSL_ERROR_WANT_X509_LOOKUP)) { /* Need to retry the function call "later". * See https://linux.die.net/man/3/ssl_get_error * This is typical for non-blocking sockets. */ if (*stop_server) { /* Don't wait if the server is going to be stopped. */ break; } mg_sleep(i); } else if (err == SSL_ERROR_SYSCALL) { /* This is an IO error. Look at errno. */ err = errno; mg_cry_internal(conn, "SSL syscall error %i", err); break; } else { /* This is an SSL specific error, e.g. SSL_ERROR_SSL */ mg_cry_internal(conn, "sslize error: %s", ssl_error()); break; } } else { /* success */ break; } } if (ret != 1) { SSL_free(conn->ssl); conn->ssl = NULL; /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion: * https://wiki.openssl.org/index.php/Talk:Library_Initialization */ #if !defined(OPENSSL_API_1_1) ERR_remove_state(0); #endif return 0; } return 1; } /* Return OpenSSL error message (from CRYPTO lib) */ static const char * ssl_error(void) { unsigned long err; err = ERR_get_error(); return ((err == 0) ? "" : ERR_error_string(err, NULL)); } static int hexdump2string(void *mem, int memlen, char *buf, int buflen) { int i; const char hexdigit[] = "0123456789abcdef"; if ((memlen <= 0) || (buflen <= 0)) { return 0; } if (buflen < (3 * memlen)) { return 0; } for (i = 0; i < memlen; i++) { if (i > 0) { buf[3 * i - 1] = ' '; } buf[3 * i] = hexdigit[(((uint8_t *)mem)[i] >> 4) & 0xF]; buf[3 * i + 1] = hexdigit[((uint8_t *)mem)[i] & 0xF]; } buf[3 * memlen - 1] = 0; return 1; } static void ssl_get_client_cert_info(struct mg_connection *conn) { X509 *cert = SSL_get_peer_certificate(conn->ssl); if (cert) { char str_subject[1024]; char str_issuer[1024]; char str_finger[1024]; unsigned char buf[256]; char *str_serial = NULL; unsigned int ulen; int ilen; unsigned char *tmp_buf; unsigned char *tmp_p; /* Handle to algorithm used for fingerprint */ const EVP_MD *digest = EVP_get_digestbyname("sha1"); /* Get Subject and issuer */ X509_NAME *subj = X509_get_subject_name(cert); X509_NAME *iss = X509_get_issuer_name(cert); /* Get serial number */ ASN1_INTEGER *serial = X509_get_serialNumber(cert); /* Translate serial number to a hex string */ BIGNUM *serial_bn = ASN1_INTEGER_to_BN(serial, NULL); str_serial = BN_bn2hex(serial_bn); BN_free(serial_bn); /* Translate subject and issuer to a string */ (void)X509_NAME_oneline(subj, str_subject, (int)sizeof(str_subject)); (void)X509_NAME_oneline(iss, str_issuer, (int)sizeof(str_issuer)); /* Calculate SHA1 fingerprint and store as a hex string */ ulen = 0; /* ASN1_digest is deprecated. Do the calculation manually, * using EVP_Digest. */ ilen = i2d_X509(cert, NULL); tmp_buf = (ilen > 0) ? (unsigned char *)mg_malloc_ctx((unsigned)ilen + 1, conn->phys_ctx) : NULL; if (tmp_buf) { tmp_p = tmp_buf; (void)i2d_X509(cert, &tmp_p); if (!EVP_Digest( tmp_buf, (unsigned)ilen, buf, &ulen, digest, NULL)) { ulen = 0; } mg_free(tmp_buf); } if (!hexdump2string( buf, (int)ulen, str_finger, (int)sizeof(str_finger))) { *str_finger = 0; } conn->request_info.client_cert = (struct mg_client_cert *) mg_malloc_ctx(sizeof(struct mg_client_cert), conn->phys_ctx); if (conn->request_info.client_cert) { conn->request_info.client_cert->peer_cert = (void *)cert; conn->request_info.client_cert->subject = mg_strdup_ctx(str_subject, conn->phys_ctx); conn->request_info.client_cert->issuer = mg_strdup_ctx(str_issuer, conn->phys_ctx); conn->request_info.client_cert->serial = mg_strdup_ctx(str_serial, conn->phys_ctx); conn->request_info.client_cert->finger = mg_strdup_ctx(str_finger, conn->phys_ctx); } else { mg_cry_internal(conn, "%s", "Out of memory: Cannot allocate memory for client " "certificate"); } /* Strings returned from bn_bn2hex must be freed using OPENSSL_free, * see https://linux.die.net/man/3/bn_bn2hex */ OPENSSL_free(str_serial); } } #if defined(OPENSSL_API_1_1) #else static void ssl_locking_callback(int mode, int mutex_num, const char *file, int line) { (void)line; (void)file; if (mode & 1) { /* 1 is CRYPTO_LOCK */ (void)pthread_mutex_lock(&ssl_mutexes[mutex_num]); } else { (void)pthread_mutex_unlock(&ssl_mutexes[mutex_num]); } } #endif /* OPENSSL_API_1_1 */ #if !defined(NO_SSL_DL) static void * load_dll(char *ebuf, size_t ebuf_len, const char *dll_name, struct ssl_func *sw) { union { void *p; void (*fp)(void); } u; void *dll_handle; struct ssl_func *fp; int ok; int truncated = 0; if ((dll_handle = dlopen(dll_name, RTLD_LAZY)) == NULL) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s: cannot load %s", __func__, dll_name); return NULL; } ok = 1; for (fp = sw; fp->name != NULL; fp++) { #if defined(_WIN32) /* GetProcAddress() returns pointer to function */ u.fp = (void (*)(void))dlsym(dll_handle, fp->name); #else /* dlsym() on UNIX returns void *. ISO C forbids casts of data * pointers to function pointers. We need to use a union to make a * cast. */ u.p = dlsym(dll_handle, fp->name); #endif /* _WIN32 */ if (u.fp == NULL) { if (ok) { mg_snprintf(NULL, &truncated, ebuf, ebuf_len, "%s: %s: cannot find %s", __func__, dll_name, fp->name); ok = 0; } else { size_t cur_len = strlen(ebuf); if (!truncated) { mg_snprintf(NULL, &truncated, ebuf + cur_len, ebuf_len - cur_len - 3, ", %s", fp->name); if (truncated) { /* If truncated, add "..." */ strcat(ebuf, "..."); } } } /* Debug: * printf("Missing function: %s\n", fp->name); */ } else { fp->ptr = u.fp; } } if (!ok) { (void)dlclose(dll_handle); return NULL; } return dll_handle; } static void *ssllib_dll_handle; /* Store the ssl library handle. */ static void *cryptolib_dll_handle; /* Store the crypto library handle. */ #endif /* NO_SSL_DL */ #if defined(SSL_ALREADY_INITIALIZED) static int cryptolib_users = 1; /* Reference counter for crypto library. */ #else static int cryptolib_users = 0; /* Reference counter for crypto library. */ #endif static int initialize_ssl(char *ebuf, size_t ebuf_len) { #if defined(OPENSSL_API_1_1) if (ebuf_len > 0) { ebuf[0] = 0; } #if !defined(NO_SSL_DL) if (!cryptolib_dll_handle) { cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw); if (!cryptolib_dll_handle) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s: error loading library %s", __func__, CRYPTO_LIB); DEBUG_TRACE("%s", ebuf); return 0; } } #endif /* NO_SSL_DL */ if (mg_atomic_inc(&cryptolib_users) > 1) { return 1; } #else /* not OPENSSL_API_1_1 */ int i, num_locks; size_t size; if (ebuf_len > 0) { ebuf[0] = 0; } #if !defined(NO_SSL_DL) if (!cryptolib_dll_handle) { cryptolib_dll_handle = load_dll(ebuf, ebuf_len, CRYPTO_LIB, crypto_sw); if (!cryptolib_dll_handle) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s: error loading library %s", __func__, CRYPTO_LIB); DEBUG_TRACE("%s", ebuf); return 0; } } #endif /* NO_SSL_DL */ if (mg_atomic_inc(&cryptolib_users) > 1) { return 1; } /* Initialize locking callbacks, needed for thread safety. * http://www.openssl.org/support/faq.html#PROG1 */ num_locks = CRYPTO_num_locks(); if (num_locks < 0) { num_locks = 0; } size = sizeof(pthread_mutex_t) * ((size_t)(num_locks)); /* allocate mutex array, if required */ if (num_locks == 0) { /* No mutex array required */ ssl_mutexes = NULL; } else { /* Mutex array required - allocate it */ ssl_mutexes = (pthread_mutex_t *)mg_malloc(size); /* Check OOM */ if (ssl_mutexes == NULL) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s: cannot allocate mutexes: %s", __func__, ssl_error()); DEBUG_TRACE("%s", ebuf); return 0; } /* initialize mutex array */ for (i = 0; i < num_locks; i++) { if (0 != pthread_mutex_init(&ssl_mutexes[i], &pthread_mutex_attr)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s: error initializing mutex %i of %i", __func__, i, num_locks); DEBUG_TRACE("%s", ebuf); mg_free(ssl_mutexes); return 0; } } } CRYPTO_set_locking_callback(&ssl_locking_callback); CRYPTO_set_id_callback(&mg_current_thread_id); #endif /* OPENSSL_API_1_1 */ #if !defined(NO_SSL_DL) if (!ssllib_dll_handle) { ssllib_dll_handle = load_dll(ebuf, ebuf_len, SSL_LIB, ssl_sw); if (!ssllib_dll_handle) { #if !defined(OPENSSL_API_1_1) mg_free(ssl_mutexes); #endif DEBUG_TRACE("%s", ebuf); return 0; } } #endif /* NO_SSL_DL */ #if defined(OPENSSL_API_1_1) /* Initialize SSL library */ OPENSSL_init_ssl(0, NULL); OPENSSL_init_ssl(OPENSSL_INIT_LOAD_SSL_STRINGS | OPENSSL_INIT_LOAD_CRYPTO_STRINGS, NULL); #else /* Initialize SSL library */ SSL_library_init(); SSL_load_error_strings(); #endif return 1; } static int ssl_use_pem_file(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *pem, const char *chain) { if (SSL_CTX_use_certificate_file(dom_ctx->ssl_ctx, pem, 1) == 0) { mg_cry_internal(fc(phys_ctx), "%s: cannot open certificate file %s: %s", __func__, pem, ssl_error()); return 0; } /* could use SSL_CTX_set_default_passwd_cb_userdata */ if (SSL_CTX_use_PrivateKey_file(dom_ctx->ssl_ctx, pem, 1) == 0) { mg_cry_internal(fc(phys_ctx), "%s: cannot open private key file %s: %s", __func__, pem, ssl_error()); return 0; } if (SSL_CTX_check_private_key(dom_ctx->ssl_ctx) == 0) { mg_cry_internal(fc(phys_ctx), "%s: certificate and private key do not match: %s", __func__, pem); return 0; } /* In contrast to OpenSSL, wolfSSL does not support certificate * chain files that contain private keys and certificates in * SSL_CTX_use_certificate_chain_file. * The CivetWeb-Server used pem-Files that contained both information. * In order to make wolfSSL work, it is split in two files. * One file that contains key and certificate used by the server and * an optional chain file for the ssl stack. */ if (chain) { if (SSL_CTX_use_certificate_chain_file(dom_ctx->ssl_ctx, chain) == 0) { mg_cry_internal(fc(phys_ctx), "%s: cannot use certificate chain file %s: %s", __func__, pem, ssl_error()); return 0; } } return 1; } #if defined(OPENSSL_API_1_1) static unsigned long ssl_get_protocol(int version_id) { long unsigned ret = (long unsigned)SSL_OP_ALL; if (version_id > 0) ret |= SSL_OP_NO_SSLv2; if (version_id > 1) ret |= SSL_OP_NO_SSLv3; if (version_id > 2) ret |= SSL_OP_NO_TLSv1; if (version_id > 3) ret |= SSL_OP_NO_TLSv1_1; return ret; } #else static long ssl_get_protocol(int version_id) { long ret = (long)SSL_OP_ALL; if (version_id > 0) ret |= SSL_OP_NO_SSLv2; if (version_id > 1) ret |= SSL_OP_NO_SSLv3; if (version_id > 2) ret |= SSL_OP_NO_TLSv1; if (version_id > 3) ret |= SSL_OP_NO_TLSv1_1; return ret; } #endif /* OPENSSL_API_1_1 */ /* SSL callback documentation: * https://www.openssl.org/docs/man1.1.0/ssl/SSL_set_info_callback.html * https://wiki.openssl.org/index.php/Manual:SSL_CTX_set_info_callback(3) * https://linux.die.net/man/3/ssl_set_info_callback */ /* Note: There is no "const" for the first argument in the documentation, * however some (maybe most, but not all) headers of OpenSSL versions / * OpenSSL compatibility layers have it. Having a different definition * will cause a warning in C and an error in C++. With inconsitent * definitions of this function, having a warning in one version or * another is unavoidable. */ static void ssl_info_callback(SSL *ssl, int what, int ret) { (void)ret; if (what & SSL_CB_HANDSHAKE_START) { SSL_get_app_data(ssl); } if (what & SSL_CB_HANDSHAKE_DONE) { /* TODO: check for openSSL 1.1 */ //#define SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS 0x0001 // ssl->s3->flags |= SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS; } } static int ssl_servername_callback(SSL *ssl, int *ad, void *arg) { struct mg_context *ctx = (struct mg_context *)arg; struct mg_domain_context *dom = (struct mg_domain_context *)ctx ? &(ctx->dd) : NULL; #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" #endif /* defined(__GNUC__) || defined(__MINGW32__) */ /* We used an aligned pointer in SSL_set_app_data */ struct mg_connection *conn = (struct mg_connection *)SSL_get_app_data(ssl); #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic pop #endif /* defined(__GNUC__) || defined(__MINGW32__) */ const char *servername = SSL_get_servername(ssl, TLSEXT_NAMETYPE_host_name); (void)ad; if ((ctx == NULL) || (conn->phys_ctx == ctx)) { DEBUG_TRACE("%s", "internal error - assertion failed"); return SSL_TLSEXT_ERR_NOACK; } /* Old clients (Win XP) will not support SNI. Then, there * is no server name available in the request - we can * only work with the default certificate. * Multiple HTTPS hosts on one IP+port are only possible * with a certificate containing all alternative names. */ if ((servername == NULL) || (*servername == 0)) { DEBUG_TRACE("%s", "SSL connection not supporting SNI"); conn->dom_ctx = &(ctx->dd); SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx); return SSL_TLSEXT_ERR_NOACK; } DEBUG_TRACE("TLS connection to host %s", servername); while (dom) { if (!mg_strcasecmp(servername, dom->config[AUTHENTICATION_DOMAIN])) { /* Found matching domain */ DEBUG_TRACE("TLS domain %s found", dom->config[AUTHENTICATION_DOMAIN]); SSL_set_SSL_CTX(ssl, dom->ssl_ctx); conn->dom_ctx = dom; return SSL_TLSEXT_ERR_OK; } dom = dom->next; } /* Default domain */ DEBUG_TRACE("TLS default domain %s used", ctx->dd.config[AUTHENTICATION_DOMAIN]); conn->dom_ctx = &(ctx->dd); SSL_set_SSL_CTX(ssl, conn->dom_ctx->ssl_ctx); return SSL_TLSEXT_ERR_OK; } /* Setup SSL CTX as required by CivetWeb */ static int init_ssl_ctx_impl(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx, const char *pem, const char *chain) { int callback_ret; int should_verify_peer; int peer_certificate_optional; const char *ca_path; const char *ca_file; int use_default_verify_paths; int verify_depth; struct timespec now_mt; md5_byte_t ssl_context_id[16]; md5_state_t md5state; int protocol_ver; #if defined(OPENSSL_API_1_1) if ((dom_ctx->ssl_ctx = SSL_CTX_new(TLS_server_method())) == NULL) { mg_cry_internal(fc(phys_ctx), "SSL_CTX_new (server) error: %s", ssl_error()); return 0; } #else if ((dom_ctx->ssl_ctx = SSL_CTX_new(SSLv23_server_method())) == NULL) { mg_cry_internal(fc(phys_ctx), "SSL_CTX_new (server) error: %s", ssl_error()); return 0; } #endif /* OPENSSL_API_1_1 */ SSL_CTX_clear_options(dom_ctx->ssl_ctx, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); protocol_ver = atoi(dom_ctx->config[SSL_PROTOCOL_VERSION]); SSL_CTX_set_options(dom_ctx->ssl_ctx, ssl_get_protocol(protocol_ver)); SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_SINGLE_DH_USE); SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_CIPHER_SERVER_PREFERENCE); SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION); SSL_CTX_set_options(dom_ctx->ssl_ctx, SSL_OP_NO_COMPRESSION); #if !defined(NO_SSL_DL) SSL_CTX_set_ecdh_auto(dom_ctx->ssl_ctx, 1); #endif /* NO_SSL_DL */ #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wincompatible-pointer-types" #endif #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wincompatible-pointer-types" #endif /* Depending on the OpenSSL version, the callback may be * 'void (*)(SSL *, int, int)' or 'void (*)(const SSL *, int, int)' * yielding in an "incompatible-pointer-type" warning for the other * version. It seems to be "unclear" what is correct: * https://bugs.launchpad.net/ubuntu/+source/openssl/+bug/1147526 * https://www.openssl.org/docs/man1.0.2/ssl/ssl.html * https://www.openssl.org/docs/man1.1.0/ssl/ssl.html * https://github.com/openssl/openssl/blob/1d97c8435171a7af575f73c526d79e1ef0ee5960/ssl/ssl.h#L1173 * Disable this warning here. * Alternative would be a version dependent ssl_info_callback and * a const-cast to call 'char *SSL_get_app_data(SSL *ssl)' there. */ SSL_CTX_set_info_callback(dom_ctx->ssl_ctx, ssl_info_callback); SSL_CTX_set_tlsext_servername_callback(dom_ctx->ssl_ctx, ssl_servername_callback); SSL_CTX_set_tlsext_servername_arg(dom_ctx->ssl_ctx, phys_ctx); #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma clang diagnostic pop #endif /* If a callback has been specified, call it. */ callback_ret = (phys_ctx->callbacks.init_ssl == NULL) ? 0 : (phys_ctx->callbacks.init_ssl(dom_ctx->ssl_ctx, phys_ctx->user_data)); /* If callback returns 0, civetweb sets up the SSL certificate. * If it returns 1, civetweb assumes the calback already did this. * If it returns -1, initializing ssl fails. */ if (callback_ret < 0) { mg_cry_internal(fc(phys_ctx), "SSL callback returned error: %i", callback_ret); return 0; } if (callback_ret > 0) { /* Callback did everything. */ return 1; } /* Use some combination of start time, domain and port as a SSL * context ID. This should be unique on the current machine. */ md5_init(&md5state); clock_gettime(CLOCK_MONOTONIC, &now_mt); md5_append(&md5state, (const md5_byte_t *)&now_mt, sizeof(now_mt)); md5_append(&md5state, (const md5_byte_t *)phys_ctx->dd.config[LISTENING_PORTS], strlen(phys_ctx->dd.config[LISTENING_PORTS])); md5_append(&md5state, (const md5_byte_t *)dom_ctx->config[AUTHENTICATION_DOMAIN], strlen(dom_ctx->config[AUTHENTICATION_DOMAIN])); md5_append(&md5state, (const md5_byte_t *)phys_ctx, sizeof(*phys_ctx)); md5_append(&md5state, (const md5_byte_t *)dom_ctx, sizeof(*dom_ctx)); md5_finish(&md5state, ssl_context_id); SSL_CTX_set_session_id_context(dom_ctx->ssl_ctx, (unsigned char *)ssl_context_id, sizeof(ssl_context_id)); if (pem != NULL) { if (!ssl_use_pem_file(phys_ctx, dom_ctx, pem, chain)) { return 0; } } /* Should we support client certificates? */ /* Default is "no". */ should_verify_peer = 0; peer_certificate_optional = 0; if (dom_ctx->config[SSL_DO_VERIFY_PEER] != NULL) { if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "yes") == 0) { /* Yes, they are mandatory */ should_verify_peer = 1; peer_certificate_optional = 0; } else if (mg_strcasecmp(dom_ctx->config[SSL_DO_VERIFY_PEER], "optional") == 0) { /* Yes, they are optional */ should_verify_peer = 1; peer_certificate_optional = 1; } } use_default_verify_paths = (dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS] != NULL) && (mg_strcasecmp(dom_ctx->config[SSL_DEFAULT_VERIFY_PATHS], "yes") == 0); if (should_verify_peer) { ca_path = dom_ctx->config[SSL_CA_PATH]; ca_file = dom_ctx->config[SSL_CA_FILE]; if (SSL_CTX_load_verify_locations(dom_ctx->ssl_ctx, ca_file, ca_path) != 1) { mg_cry_internal(fc(phys_ctx), "SSL_CTX_load_verify_locations error: %s " "ssl_verify_peer requires setting " "either ssl_ca_path or ssl_ca_file. " "Is any of them present in the " ".conf file?", ssl_error()); return 0; } if (peer_certificate_optional) { SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER, NULL); } else { SSL_CTX_set_verify(dom_ctx->ssl_ctx, SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT, NULL); } if (use_default_verify_paths && (SSL_CTX_set_default_verify_paths(dom_ctx->ssl_ctx) != 1)) { mg_cry_internal(fc(phys_ctx), "SSL_CTX_set_default_verify_paths error: %s", ssl_error()); return 0; } if (dom_ctx->config[SSL_VERIFY_DEPTH]) { verify_depth = atoi(dom_ctx->config[SSL_VERIFY_DEPTH]); SSL_CTX_set_verify_depth(dom_ctx->ssl_ctx, verify_depth); } } if (dom_ctx->config[SSL_CIPHER_LIST] != NULL) { if (SSL_CTX_set_cipher_list(dom_ctx->ssl_ctx, dom_ctx->config[SSL_CIPHER_LIST]) != 1) { mg_cry_internal(fc(phys_ctx), "SSL_CTX_set_cipher_list error: %s", ssl_error()); } } return 1; } /* Check if SSL is required. * If so, dynamically load SSL library * and set up ctx->ssl_ctx pointer. */ static int init_ssl_ctx(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx) { void *ssl_ctx = 0; int callback_ret; const char *pem; const char *chain; char ebuf[128]; if (!phys_ctx) { return 0; } if (!dom_ctx) { dom_ctx = &(phys_ctx->dd); } if (!is_ssl_port_used(dom_ctx->config[LISTENING_PORTS])) { /* No SSL port is set. No need to setup SSL. */ return 1; } /* Check for external SSL_CTX */ callback_ret = (phys_ctx->callbacks.external_ssl_ctx == NULL) ? 0 : (phys_ctx->callbacks.external_ssl_ctx(&ssl_ctx, phys_ctx->user_data)); if (callback_ret < 0) { mg_cry_internal(fc(phys_ctx), "external_ssl_ctx callback returned error: %i", callback_ret); return 0; } else if (callback_ret > 0) { dom_ctx->ssl_ctx = (SSL_CTX *)ssl_ctx; if (!initialize_ssl(ebuf, sizeof(ebuf))) { mg_cry_internal(fc(phys_ctx), "%s", ebuf); return 0; } return 1; } /* else: external_ssl_ctx does not exist or returns 0, * CivetWeb should continue initializing SSL */ /* If PEM file is not specified and the init_ssl callback * is not specified, setup will fail. */ if (((pem = dom_ctx->config[SSL_CERTIFICATE]) == NULL) && (phys_ctx->callbacks.init_ssl == NULL)) { /* No certificate and no callback: * Essential data to set up TLS is missing. */ mg_cry_internal(fc(phys_ctx), "Initializing SSL failed: -%s is not set", config_options[SSL_CERTIFICATE].name); return 0; } chain = dom_ctx->config[SSL_CERTIFICATE_CHAIN]; if (chain == NULL) { chain = pem; } if ((chain != NULL) && (*chain == 0)) { chain = NULL; } if (!initialize_ssl(ebuf, sizeof(ebuf))) { mg_cry_internal(fc(phys_ctx), "%s", ebuf); return 0; } return init_ssl_ctx_impl(phys_ctx, dom_ctx, pem, chain); } static void uninitialize_ssl(void) { #if defined(OPENSSL_API_1_1) if (mg_atomic_dec(&cryptolib_users) == 0) { /* Shutdown according to * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl */ CONF_modules_unload(1); #else int i; if (mg_atomic_dec(&cryptolib_users) == 0) { /* Shutdown according to * https://wiki.openssl.org/index.php/Library_Initialization#Cleanup * http://stackoverflow.com/questions/29845527/how-to-properly-uninitialize-openssl */ CRYPTO_set_locking_callback(NULL); CRYPTO_set_id_callback(NULL); ENGINE_cleanup(); CONF_modules_unload(1); ERR_free_strings(); EVP_cleanup(); CRYPTO_cleanup_all_ex_data(); ERR_remove_state(0); for (i = 0; i < CRYPTO_num_locks(); i++) { pthread_mutex_destroy(&ssl_mutexes[i]); } mg_free(ssl_mutexes); ssl_mutexes = NULL; #endif /* OPENSSL_API_1_1 */ } } #endif /* !NO_SSL */ static int set_gpass_option(struct mg_context *phys_ctx, struct mg_domain_context *dom_ctx) { if (phys_ctx) { struct mg_file file = STRUCT_FILE_INITIALIZER; const char *path; if (!dom_ctx) { dom_ctx = &(phys_ctx->dd); } path = dom_ctx->config[GLOBAL_PASSWORDS_FILE]; if ((path != NULL) && !mg_stat(fc(phys_ctx), path, &file.stat)) { mg_cry_internal(fc(phys_ctx), "Cannot open %s: %s", path, strerror(ERRNO)); return 0; } return 1; } return 0; } static int set_acl_option(struct mg_context *phys_ctx) { return check_acl(phys_ctx, (uint32_t)0x7f000001UL) != -1; } static void reset_per_request_attributes(struct mg_connection *conn) { if (!conn) { return; } conn->connection_type = CONNECTION_TYPE_INVALID; /* Not yet a valid request/response */ conn->num_bytes_sent = conn->consumed_content = 0; conn->path_info = NULL; conn->status_code = -1; conn->content_len = -1; conn->is_chunked = 0; conn->must_close = 0; conn->request_len = 0; conn->throttle = 0; conn->data_len = 0; conn->chunk_remainder = 0; conn->accept_gzip = 0; conn->response_info.content_length = conn->request_info.content_length = -1; conn->response_info.http_version = conn->request_info.http_version = NULL; conn->response_info.num_headers = conn->request_info.num_headers = 0; conn->response_info.status_text = NULL; conn->response_info.status_code = 0; conn->request_info.remote_user = NULL; conn->request_info.request_method = NULL; conn->request_info.request_uri = NULL; conn->request_info.local_uri = NULL; #if defined(MG_LEGACY_INTERFACE) /* Legacy before split into local_uri and request_uri */ conn->request_info.uri = NULL; #endif } #if 0 /* Note: set_sock_timeout is not required for non-blocking sockets. * Leave this function here (commented out) for reference until * CivetWeb 1.9 is tested, and the tests confirme this function is * no longer required. */ static int set_sock_timeout(SOCKET sock, int milliseconds) { int r0 = 0, r1, r2; #if defined(_WIN32) /* Windows specific */ DWORD tv = (DWORD)milliseconds; #else /* Linux, ... (not Windows) */ struct timeval tv; /* TCP_USER_TIMEOUT/RFC5482 (http://tools.ietf.org/html/rfc5482): * max. time waiting for the acknowledged of TCP data before the connection * will be forcefully closed and ETIMEDOUT is returned to the application. * If this option is not set, the default timeout of 20-30 minutes is used. */ /* #define TCP_USER_TIMEOUT (18) */ #if defined(TCP_USER_TIMEOUT) unsigned int uto = (unsigned int)milliseconds; r0 = setsockopt(sock, 6, TCP_USER_TIMEOUT, (const void *)&uto, sizeof(uto)); #endif memset(&tv, 0, sizeof(tv)); tv.tv_sec = milliseconds / 1000; tv.tv_usec = (milliseconds * 1000) % 1000000; #endif /* _WIN32 */ r1 = setsockopt( sock, SOL_SOCKET, SO_RCVTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv)); r2 = setsockopt( sock, SOL_SOCKET, SO_SNDTIMEO, (SOCK_OPT_TYPE)&tv, sizeof(tv)); return r0 || r1 || r2; } #endif static int set_tcp_nodelay(SOCKET sock, int nodelay_on) { if (setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (SOCK_OPT_TYPE)&nodelay_on, sizeof(nodelay_on)) != 0) { /* Error */ return 1; } /* OK */ return 0; } static void close_socket_gracefully(struct mg_connection *conn) { #if defined(_WIN32) char buf[MG_BUF_LEN]; int n; #endif struct linger linger; int error_code = 0; int linger_timeout = -2; socklen_t opt_len = sizeof(error_code); if (!conn) { return; } /* http://msdn.microsoft.com/en-us/library/ms739165(v=vs.85).aspx: * "Note that enabling a nonzero timeout on a nonblocking socket * is not recommended.", so set it to blocking now */ set_blocking_mode(conn->client.sock); /* Send FIN to the client */ shutdown(conn->client.sock, SHUTDOWN_WR); #if defined(_WIN32) /* Read and discard pending incoming data. If we do not do that and * close * the socket, the data in the send buffer may be discarded. This * behaviour is seen on Windows, when client keeps sending data * when server decides to close the connection; then when client * does recv() it gets no data back. */ do { n = pull_inner(NULL, conn, buf, sizeof(buf), /* Timeout in s: */ 1.0); } while (n > 0); #endif if (conn->dom_ctx->config[LINGER_TIMEOUT]) { linger_timeout = atoi(conn->dom_ctx->config[LINGER_TIMEOUT]); } /* Set linger option according to configuration */ if (linger_timeout >= 0) { /* Set linger option to avoid socket hanging out after close. This * prevent ephemeral port exhaust problem under high QPS. */ linger.l_onoff = 1; #if defined(_MSC_VER) #pragma warning(push) #pragma warning(disable : 4244) #endif #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wconversion" #endif /* Data type of linger structure elements may differ, * so we don't know what cast we need here. * Disable type conversion warnings. */ linger.l_linger = (linger_timeout + 999) / 1000; #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic pop #endif #if defined(_MSC_VER) #pragma warning(pop) #endif } else { linger.l_onoff = 0; linger.l_linger = 0; } if (linger_timeout < -1) { /* Default: don't configure any linger */ } else if (getsockopt(conn->client.sock, SOL_SOCKET, SO_ERROR, #if defined(_WIN32) /* WinSock uses different data type here */ (char *)&error_code, #else &error_code, #endif &opt_len) != 0) { /* Cannot determine if socket is already closed. This should * not occur and never did in a test. Log an error message * and continue. */ mg_cry_internal(conn, "%s: getsockopt(SOL_SOCKET SO_ERROR) failed: %s", __func__, strerror(ERRNO)); } else if (error_code == ECONNRESET) { /* Socket already closed by client/peer, close socket without linger */ } else { /* Set linger timeout */ if (setsockopt(conn->client.sock, SOL_SOCKET, SO_LINGER, (char *)&linger, sizeof(linger)) != 0) { mg_cry_internal( conn, "%s: setsockopt(SOL_SOCKET SO_LINGER(%i,%i)) failed: %s", __func__, linger.l_onoff, linger.l_linger, strerror(ERRNO)); } } /* Now we know that our FIN is ACK-ed, safe to close */ closesocket(conn->client.sock); conn->client.sock = INVALID_SOCKET; } static void close_connection(struct mg_connection *conn) { #if defined(USE_SERVER_STATS) conn->conn_state = 6; /* to close */ #endif #if defined(USE_LUA) && defined(USE_WEBSOCKET) if (conn->lua_websocket_state) { lua_websocket_close(conn, conn->lua_websocket_state); conn->lua_websocket_state = NULL; } #endif mg_lock_connection(conn); /* Set close flag, so keep-alive loops will stop */ conn->must_close = 1; /* call the connection_close callback if assigned */ if (conn->phys_ctx->callbacks.connection_close != NULL) { if (conn->phys_ctx->context_type == CONTEXT_SERVER) { conn->phys_ctx->callbacks.connection_close(conn); } } /* Reset user data, after close callback is called. * Do not reuse it. If the user needs a destructor, * it must be done in the connection_close callback. */ mg_set_user_connection_data(conn, NULL); #if defined(USE_SERVER_STATS) conn->conn_state = 7; /* closing */ #endif #if !defined(NO_SSL) if (conn->ssl != NULL) { /* Run SSL_shutdown twice to ensure completely close SSL connection */ SSL_shutdown(conn->ssl); SSL_free(conn->ssl); /* Avoid CRYPTO_cleanup_all_ex_data(); See discussion: * https://wiki.openssl.org/index.php/Talk:Library_Initialization */ #if !defined(OPENSSL_API_1_1) ERR_remove_state(0); #endif conn->ssl = NULL; } #endif if (conn->client.sock != INVALID_SOCKET) { close_socket_gracefully(conn); conn->client.sock = INVALID_SOCKET; } if (conn->host) { mg_free((void *)conn->host); conn->host = NULL; } mg_unlock_connection(conn); #if defined(USE_SERVER_STATS) conn->conn_state = 8; /* closed */ #endif } void mg_close_connection(struct mg_connection *conn) { #if defined(USE_WEBSOCKET) struct mg_context *client_ctx = NULL; #endif /* defined(USE_WEBSOCKET) */ if ((conn == NULL) || (conn->phys_ctx == NULL)) { return; } #if defined(USE_WEBSOCKET) if (conn->phys_ctx->context_type == CONTEXT_SERVER) { if (conn->in_websocket_handling) { /* Set close flag, so the server thread can exit. */ conn->must_close = 1; return; } } if (conn->phys_ctx->context_type == CONTEXT_WS_CLIENT) { unsigned int i; /* ws/wss client */ client_ctx = conn->phys_ctx; /* client context: loops must end */ client_ctx->stop_flag = 1; conn->must_close = 1; /* We need to get the client thread out of the select/recv call * here. */ /* Since we use a sleep quantum of some seconds to check for recv * timeouts, we will just wait a few seconds in mg_join_thread. */ /* join worker thread */ for (i = 0; i < client_ctx->cfg_worker_threads; i++) { if (client_ctx->worker_threadids[i] != 0) { mg_join_thread(client_ctx->worker_threadids[i]); } } } #endif /* defined(USE_WEBSOCKET) */ close_connection(conn); #if !defined(NO_SSL) if (conn->client_ssl_ctx != NULL) { SSL_CTX_free((SSL_CTX *)conn->client_ssl_ctx); } #endif #if defined(USE_WEBSOCKET) if (client_ctx != NULL) { /* free context */ mg_free(client_ctx->worker_threadids); mg_free(client_ctx); (void)pthread_mutex_destroy(&conn->mutex); mg_free(conn); } else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { mg_free(conn); } #else if (conn->phys_ctx->context_type == CONTEXT_HTTP_CLIENT) { /* Client */ mg_free(conn); } #endif /* defined(USE_WEBSOCKET) */ } /* Only for memory statistics */ static struct mg_context common_client_context; static struct mg_connection * mg_connect_client_impl(const struct mg_client_options *client_options, int use_ssl, char *ebuf, size_t ebuf_len) { struct mg_connection *conn = NULL; SOCKET sock; union usa sa; struct sockaddr *psa; socklen_t len; unsigned max_req_size = (unsigned)atoi(config_options[MAX_REQUEST_SIZE].default_value); /* Size of structures, aligned to 8 bytes */ size_t conn_size = ((sizeof(struct mg_connection) + 7) >> 3) << 3; size_t ctx_size = ((sizeof(struct mg_context) + 7) >> 3) << 3; conn = (struct mg_connection *)mg_calloc_ctx(1, conn_size + ctx_size + max_req_size, &common_client_context); if (conn == NULL) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "calloc(): %s", strerror(ERRNO)); return NULL; } #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wcast-align" #endif /* defined(__GNUC__) || defined(__MINGW32__) */ /* conn_size is aligned to 8 bytes */ conn->phys_ctx = (struct mg_context *)(((char *)conn) + conn_size); #if defined(__GNUC__) || defined(__MINGW32__) #pragma GCC diagnostic pop #endif /* defined(__GNUC__) || defined(__MINGW32__) */ conn->buf = (((char *)conn) + conn_size + ctx_size); conn->buf_size = (int)max_req_size; conn->phys_ctx->context_type = CONTEXT_HTTP_CLIENT; conn->dom_ctx = &(conn->phys_ctx->dd); if (!connect_socket(&common_client_context, client_options->host, client_options->port, use_ssl, ebuf, ebuf_len, &sock, &sa)) { /* ebuf is set by connect_socket, * free all memory and return NULL; */ mg_free(conn); return NULL; } #if !defined(NO_SSL) #if defined(OPENSSL_API_1_1) if (use_ssl && (conn->client_ssl_ctx = SSL_CTX_new(TLS_client_method())) == NULL) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "SSL_CTX_new error"); closesocket(sock); mg_free(conn); return NULL; } #else if (use_ssl && (conn->client_ssl_ctx = SSL_CTX_new(SSLv23_client_method())) == NULL) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "SSL_CTX_new error"); closesocket(sock); mg_free(conn); return NULL; } #endif /* OPENSSL_API_1_1 */ #endif /* NO_SSL */ #if defined(USE_IPV6) len = (sa.sa.sa_family == AF_INET) ? sizeof(conn->client.rsa.sin) : sizeof(conn->client.rsa.sin6); psa = (sa.sa.sa_family == AF_INET) ? (struct sockaddr *)&(conn->client.rsa.sin) : (struct sockaddr *)&(conn->client.rsa.sin6); #else len = sizeof(conn->client.rsa.sin); psa = (struct sockaddr *)&(conn->client.rsa.sin); #endif conn->client.sock = sock; conn->client.lsa = sa; if (getsockname(sock, psa, &len) != 0) { mg_cry_internal(conn, "%s: getsockname() failed: %s", __func__, strerror(ERRNO)); } conn->client.is_ssl = use_ssl ? 1 : 0; if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "Can not create mutex"); #if !defined(NO_SSL) SSL_CTX_free(conn->client_ssl_ctx); #endif closesocket(sock); mg_free(conn); return NULL; } #if !defined(NO_SSL) if (use_ssl) { common_client_context.dd.ssl_ctx = conn->client_ssl_ctx; /* TODO: Check ssl_verify_peer and ssl_ca_path here. * SSL_CTX_set_verify call is needed to switch off server * certificate checking, which is off by default in OpenSSL and * on in yaSSL. */ /* TODO: SSL_CTX_set_verify(conn->client_ssl_ctx, * SSL_VERIFY_PEER, verify_ssl_server); */ if (client_options->client_cert) { if (!ssl_use_pem_file(&common_client_context, &(common_client_context.dd), client_options->client_cert, NULL)) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "Can not use SSL client certificate"); SSL_CTX_free(conn->client_ssl_ctx); closesocket(sock); mg_free(conn); return NULL; } } if (client_options->server_cert) { SSL_CTX_load_verify_locations(conn->client_ssl_ctx, client_options->server_cert, NULL); SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_PEER, NULL); } else { SSL_CTX_set_verify(conn->client_ssl_ctx, SSL_VERIFY_NONE, NULL); } if (!sslize(conn, conn->client_ssl_ctx, SSL_connect, &(conn->phys_ctx->stop_flag))) { mg_snprintf(NULL, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "SSL connection error"); SSL_CTX_free(conn->client_ssl_ctx); closesocket(sock); mg_free(conn); return NULL; } } #endif if (0 != set_non_blocking_mode(sock)) { mg_cry_internal(conn, "Cannot set non-blocking mode for client %s:%i", client_options->host, client_options->port); } return conn; } CIVETWEB_API struct mg_connection * mg_connect_client_secure(const struct mg_client_options *client_options, char *error_buffer, size_t error_buffer_size) { return mg_connect_client_impl(client_options, 1, error_buffer, error_buffer_size); } struct mg_connection * mg_connect_client(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size) { struct mg_client_options opts; memset(&opts, 0, sizeof(opts)); opts.host = host; opts.port = port; return mg_connect_client_impl(&opts, use_ssl, error_buffer, error_buffer_size); } static const struct { const char *proto; size_t proto_len; unsigned default_port; } abs_uri_protocols[] = {{"http://", 7, 80}, {"https://", 8, 443}, {"ws://", 5, 80}, {"wss://", 6, 443}, {NULL, 0, 0}}; /* Check if the uri is valid. * return 0 for invalid uri, * return 1 for *, * return 2 for relative uri, * return 3 for absolute uri without port, * return 4 for absolute uri with port */ static int get_uri_type(const char *uri) { int i; const char *hostend, *portbegin; char *portend; unsigned long port; /* According to the HTTP standard * http://www.w3.org/Protocols/rfc2616/rfc2616-sec5.html#sec5.1.2 * URI can be an asterisk (*) or should start with slash (relative uri), * or it should start with the protocol (absolute uri). */ if ((uri[0] == '*') && (uri[1] == '\0')) { /* asterisk */ return 1; } /* Valid URIs according to RFC 3986 * (https://www.ietf.org/rfc/rfc3986.txt) * must only contain reserved characters :/?#[]@!$&'()*+,;= * and unreserved characters A-Z a-z 0-9 and -._~ * and % encoded symbols. */ for (i = 0; uri[i] != 0; i++) { if (uri[i] < 33) { /* control characters and spaces are invalid */ return 0; } if (uri[i] > 126) { /* non-ascii characters must be % encoded */ return 0; } else { switch (uri[i]) { case '"': /* 34 */ case '<': /* 60 */ case '>': /* 62 */ case '\\': /* 92 */ case '^': /* 94 */ case '`': /* 96 */ case '{': /* 123 */ case '|': /* 124 */ case '}': /* 125 */ return 0; default: /* character is ok */ break; } } } /* A relative uri starts with a / character */ if (uri[0] == '/') { /* relative uri */ return 2; } /* It could be an absolute uri: */ /* This function only checks if the uri is valid, not if it is * addressing the current server. So civetweb can also be used * as a proxy server. */ for (i = 0; abs_uri_protocols[i].proto != NULL; i++) { if (mg_strncasecmp(uri, abs_uri_protocols[i].proto, abs_uri_protocols[i].proto_len) == 0) { hostend = strchr(uri + abs_uri_protocols[i].proto_len, '/'); if (!hostend) { return 0; } portbegin = strchr(uri + abs_uri_protocols[i].proto_len, ':'); if (!portbegin) { return 3; } port = strtoul(portbegin + 1, &portend, 10); if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) { return 0; } return 4; } } return 0; } /* Return NULL or the relative uri at the current server */ static const char * get_rel_url_at_current_server(const char *uri, const struct mg_connection *conn) { const char *server_domain; size_t server_domain_len; size_t request_domain_len = 0; unsigned long port = 0; int i, auth_domain_check_enabled; const char *hostbegin = NULL; const char *hostend = NULL; const char *portbegin; char *portend; auth_domain_check_enabled = !mg_strcasecmp(conn->dom_ctx->config[ENABLE_AUTH_DOMAIN_CHECK], "yes"); /* DNS is case insensitive, so use case insensitive string compare here */ for (i = 0; abs_uri_protocols[i].proto != NULL; i++) { if (mg_strncasecmp(uri, abs_uri_protocols[i].proto, abs_uri_protocols[i].proto_len) == 0) { hostbegin = uri + abs_uri_protocols[i].proto_len; hostend = strchr(hostbegin, '/'); if (!hostend) { return 0; } portbegin = strchr(hostbegin, ':'); if ((!portbegin) || (portbegin > hostend)) { port = abs_uri_protocols[i].default_port; request_domain_len = (size_t)(hostend - hostbegin); } else { port = strtoul(portbegin + 1, &portend, 10); if ((portend != hostend) || (port <= 0) || !is_valid_port(port)) { return 0; } request_domain_len = (size_t)(portbegin - hostbegin); } /* protocol found, port set */ break; } } if (!port) { /* port remains 0 if the protocol is not found */ return 0; } /* Check if the request is directed to a different server. */ /* First check if the port is the same (IPv4 and IPv6). */ #if defined(USE_IPV6) if (conn->client.lsa.sa.sa_family == AF_INET6) { if (ntohs(conn->client.lsa.sin6.sin6_port) != port) { /* Request is directed to a different port */ return 0; } } else #endif { if (ntohs(conn->client.lsa.sin.sin_port) != port) { /* Request is directed to a different port */ return 0; } } /* Finally check if the server corresponds to the authentication * domain of the server (the server domain). * Allow full matches (like http://mydomain.com/path/file.ext), and * allow subdomain matches (like http://www.mydomain.com/path/file.ext), * but do not allow substrings (like * http://notmydomain.com/path/file.ext * or http://mydomain.com.fake/path/file.ext). */ if (auth_domain_check_enabled) { server_domain = conn->dom_ctx->config[AUTHENTICATION_DOMAIN]; server_domain_len = strlen(server_domain); if ((server_domain_len == 0) || (hostbegin == NULL)) { return 0; } if ((request_domain_len == server_domain_len) && (!memcmp(server_domain, hostbegin, server_domain_len))) { /* Request is directed to this server - full name match. */ } else { if (request_domain_len < (server_domain_len + 2)) { /* Request is directed to another server: The server name * is longer than the request name. * Drop this case here to avoid overflows in the * following checks. */ return 0; } if (hostbegin[request_domain_len - server_domain_len - 1] != '.') { /* Request is directed to another server: It could be a * substring * like notmyserver.com */ return 0; } if (0 != memcmp(server_domain, hostbegin + request_domain_len - server_domain_len, server_domain_len)) { /* Request is directed to another server: * The server name is different. */ return 0; } } } return hostend; } static int get_message(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err) { if (ebuf_len > 0) { ebuf[0] = '\0'; } *err = 0; reset_per_request_attributes(conn); if (!conn) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Internal error"); *err = 500; return 0; } /* Set the time the request was received. This value should be used for * timeouts. */ clock_gettime(CLOCK_MONOTONIC, &(conn->req_time)); conn->request_len = read_message(NULL, conn, conn->buf, conn->buf_size, &conn->data_len); DEBUG_ASSERT(conn->request_len < 0 || conn->data_len >= conn->request_len); if ((conn->request_len >= 0) && (conn->data_len < conn->request_len)) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Invalid message size"); *err = 500; return 0; } if ((conn->request_len == 0) && (conn->data_len == conn->buf_size)) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Message too large"); *err = 413; return 0; } if (conn->request_len <= 0) { if (conn->data_len > 0) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Malformed message"); *err = 400; } else { /* Server did not recv anything -> just close the connection */ conn->must_close = 1; mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "No data received"); *err = 0; } return 0; } return 1; } static int get_request(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err) { const char *cl; if (!get_message(conn, ebuf, ebuf_len, err)) { return 0; } if (parse_http_request(conn->buf, conn->buf_size, &conn->request_info) <= 0) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request"); *err = 400; return 0; } /* Message is a valid request */ /* Is there a "host" ? */ conn->host = alloc_get_host(conn); if (!conn->host) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request: Host mismatch"); *err = 400; return 0; } /* Do we know the content length? */ if ((cl = get_header(conn->request_info.http_headers, conn->request_info.num_headers, "Content-Length")) != NULL) { /* Request/response has content length set */ char *endptr = NULL; conn->content_len = strtoll(cl, &endptr, 10); if (endptr == cl) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request"); *err = 411; return 0; } /* Publish the content length back to the request info. */ conn->request_info.content_length = conn->content_len; } else if ((cl = get_header(conn->request_info.http_headers, conn->request_info.num_headers, "Transfer-Encoding")) != NULL && !mg_strcasecmp(cl, "chunked")) { conn->is_chunked = 1; conn->content_len = -1; /* unknown content length */ } else { const struct mg_http_method_info *meth = get_http_method_info(conn->request_info.request_method); if (!meth) { /* No valid HTTP method */ mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request"); *err = 411; return 0; } if (meth->request_has_body) { /* POST or PUT request without content length set */ conn->content_len = -1; /* unknown content length */ } else { /* Other request */ conn->content_len = 0; /* No content */ } } conn->connection_type = CONNECTION_TYPE_REQUEST; /* Valid request */ return 1; } /* conn is assumed to be valid in this internal function */ static int get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int *err) { const char *cl; if (!get_message(conn, ebuf, ebuf_len, err)) { return 0; } if (parse_http_response(conn->buf, conn->buf_size, &conn->response_info) <= 0) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad response"); *err = 400; return 0; } /* Message is a valid response */ /* Do we know the content length? */ if ((cl = get_header(conn->response_info.http_headers, conn->response_info.num_headers, "Content-Length")) != NULL) { /* Request/response has content length set */ char *endptr = NULL; conn->content_len = strtoll(cl, &endptr, 10); if (endptr == cl) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Bad request"); *err = 411; return 0; } /* Publish the content length back to the response info. */ conn->response_info.content_length = conn->content_len; /* TODO: check if it is still used in response_info */ conn->request_info.content_length = conn->content_len; } else if ((cl = get_header(conn->response_info.http_headers, conn->response_info.num_headers, "Transfer-Encoding")) != NULL && !mg_strcasecmp(cl, "chunked")) { conn->is_chunked = 1; conn->content_len = -1; /* unknown content length */ } else { conn->content_len = -1; /* unknown content length */ } conn->connection_type = CONNECTION_TYPE_RESPONSE; /* Valid response */ return 1; } int mg_get_response(struct mg_connection *conn, char *ebuf, size_t ebuf_len, int timeout) { int err, ret; char txt[32]; /* will not overflow */ char *save_timeout; char *new_timeout; if (ebuf_len > 0) { ebuf[0] = '\0'; } if (!conn) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Parameter error"); return -1; } /* Implementation of API function for HTTP clients */ save_timeout = conn->dom_ctx->config[REQUEST_TIMEOUT]; if (timeout >= 0) { mg_snprintf(conn, NULL, txt, sizeof(txt), "%i", timeout); new_timeout = txt; /* Not required for non-blocking sockets. set_sock_timeout(conn->client.sock, timeout); */ } else { new_timeout = NULL; } conn->dom_ctx->config[REQUEST_TIMEOUT] = new_timeout; ret = get_response(conn, ebuf, ebuf_len, &err); conn->dom_ctx->config[REQUEST_TIMEOUT] = save_timeout; #if defined(MG_LEGACY_INTERFACE) /* TODO: 1) uri is deprecated; * 2) here, ri.uri is the http response code */ conn->request_info.uri = conn->request_info.request_uri; #endif conn->request_info.local_uri = conn->request_info.request_uri; /* TODO (mid): Define proper return values - maybe return length? * For the first test use <0 for error and >0 for OK */ return (ret == 0) ? -1 : +1; } struct mg_connection * mg_download(const char *host, int port, int use_ssl, char *ebuf, size_t ebuf_len, const char *fmt, ...) { struct mg_connection *conn; va_list ap; int i; int reqerr; if (ebuf_len > 0) { ebuf[0] = '\0'; } va_start(ap, fmt); /* open a connection */ conn = mg_connect_client(host, port, use_ssl, ebuf, ebuf_len); if (conn != NULL) { i = mg_vprintf(conn, fmt, ap); if (i <= 0) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, ebuf_len, "%s", "Error sending request"); } else { get_response(conn, ebuf, ebuf_len, &reqerr); #if defined(MG_LEGACY_INTERFACE) /* TODO: 1) uri is deprecated; * 2) here, ri.uri is the http response code */ conn->request_info.uri = conn->request_info.request_uri; #endif conn->request_info.local_uri = conn->request_info.request_uri; } } /* if an error occurred, close the connection */ if ((ebuf[0] != '\0') && (conn != NULL)) { mg_close_connection(conn); conn = NULL; } va_end(ap); return conn; } struct websocket_client_thread_data { struct mg_connection *conn; mg_websocket_data_handler data_handler; mg_websocket_close_handler close_handler; void *callback_data; }; #if defined(USE_WEBSOCKET) #if defined(_WIN32) static unsigned __stdcall websocket_client_thread(void *data) #else static void * websocket_client_thread(void *data) #endif { struct websocket_client_thread_data *cdata = (struct websocket_client_thread_data *)data; #if !defined(_WIN32) struct sigaction sa; /* Ignore SIGPIPE */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, NULL); #endif mg_set_thread_name("ws-clnt"); if (cdata->conn->phys_ctx) { if (cdata->conn->phys_ctx->callbacks.init_thread) { /* 3 indicates a websocket client thread */ /* TODO: check if conn->phys_ctx can be set */ cdata->conn->phys_ctx->callbacks.init_thread(cdata->conn->phys_ctx, 3); } } read_websocket(cdata->conn, cdata->data_handler, cdata->callback_data); DEBUG_TRACE("%s", "Websocket client thread exited\n"); if (cdata->close_handler != NULL) { cdata->close_handler(cdata->conn, cdata->callback_data); } /* The websocket_client context has only this thread. If it runs out, set the stop_flag to 2 (= "stopped"). */ cdata->conn->phys_ctx->stop_flag = 2; mg_free((void *)cdata); #if defined(_WIN32) return 0; #else return NULL; #endif } #endif struct mg_connection * mg_connect_websocket_client(const char *host, int port, int use_ssl, char *error_buffer, size_t error_buffer_size, const char *path, const char *origin, mg_websocket_data_handler data_func, mg_websocket_close_handler close_func, void *user_data) { struct mg_connection *conn = NULL; #if defined(USE_WEBSOCKET) struct mg_context *newctx = NULL; struct websocket_client_thread_data *thread_data; static const char *magic = "x3JJHMbDL1EzLkh9GBhXDw=="; static const char *handshake_req; if (origin != NULL) { handshake_req = "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key: %s\r\n" "Sec-WebSocket-Version: 13\r\n" "Origin: %s\r\n" "\r\n"; } else { handshake_req = "GET %s HTTP/1.1\r\n" "Host: %s\r\n" "Upgrade: websocket\r\n" "Connection: Upgrade\r\n" "Sec-WebSocket-Key: %s\r\n" "Sec-WebSocket-Version: 13\r\n" "\r\n"; } #if defined(__clang__) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wformat-nonliteral" #endif /* Establish the client connection and request upgrade */ conn = mg_download(host, port, use_ssl, error_buffer, error_buffer_size, handshake_req, path, host, magic, origin); #if defined(__clang__) #pragma clang diagnostic pop #endif /* Connection object will be null if something goes wrong */ if (conn == NULL) { if (!*error_buffer) { /* There should be already an error message */ mg_snprintf(conn, NULL, /* No truncation check for ebuf */ error_buffer, error_buffer_size, "Unexpected error"); } return NULL; } if (conn->response_info.status_code != 101) { /* We sent an "upgrade" request. For a correct websocket * protocol handshake, we expect a "101 Continue" response. * Otherwise it is a protocol violation. Maybe the HTTP * Server does not know websockets. */ if (!*error_buffer) { /* set an error, if not yet set */ mg_snprintf(conn, NULL, /* No truncation check for ebuf */ error_buffer, error_buffer_size, "Unexpected server reply"); } DEBUG_TRACE("Websocket client connect error: %s\r\n", error_buffer); mg_free(conn); return NULL; } /* For client connections, mg_context is fake. Since we need to set a * callback function, we need to create a copy and modify it. */ newctx = (struct mg_context *)mg_malloc(sizeof(struct mg_context)); if (!newctx) { DEBUG_TRACE("%s\r\n", "Out of memory"); mg_free(conn); return NULL; } memcpy(newctx, conn->phys_ctx, sizeof(struct mg_context)); newctx->user_data = user_data; newctx->context_type = CONTEXT_WS_CLIENT; /* ws/wss client context */ newctx->cfg_worker_threads = 1; /* one worker thread will be created */ newctx->worker_threadids = (pthread_t *)mg_calloc_ctx(newctx->cfg_worker_threads, sizeof(pthread_t), newctx); conn->phys_ctx = newctx; conn->dom_ctx = &(newctx->dd); thread_data = (struct websocket_client_thread_data *) mg_calloc_ctx(sizeof(struct websocket_client_thread_data), 1, newctx); if (!thread_data) { DEBUG_TRACE("%s\r\n", "Out of memory"); mg_free(newctx); mg_free(conn); return NULL; } thread_data->conn = conn; thread_data->data_handler = data_func; thread_data->close_handler = close_func; thread_data->callback_data = user_data; /* Start a thread to read the websocket client connection * This thread will automatically stop when mg_disconnect is * called on the client connection */ if (mg_start_thread_with_id(websocket_client_thread, (void *)thread_data, newctx->worker_threadids) != 0) { mg_free((void *)thread_data); mg_free((void *)newctx->worker_threadids); mg_free((void *)newctx); mg_free((void *)conn); conn = NULL; DEBUG_TRACE("%s", "Websocket client connect thread could not be started\r\n"); } #else /* Appease "unused parameter" warnings */ (void)host; (void)port; (void)use_ssl; (void)error_buffer; (void)error_buffer_size; (void)path; (void)origin; (void)user_data; (void)data_func; (void)close_func; #endif return conn; } /* Prepare connection data structure */ static void init_connection(struct mg_connection *conn) { /* Is keep alive allowed by the server */ int keep_alive_enabled = !mg_strcasecmp(conn->dom_ctx->config[ENABLE_KEEP_ALIVE], "yes"); if (!keep_alive_enabled) { conn->must_close = 1; } /* Important: on new connection, reset the receiving buffer. Credit * goes to crule42. */ conn->data_len = 0; conn->handled_requests = 0; mg_set_user_connection_data(conn, NULL); #if defined(USE_SERVER_STATS) conn->conn_state = 2; /* init */ #endif /* call the init_connection callback if assigned */ if (conn->phys_ctx->callbacks.init_connection != NULL) { if (conn->phys_ctx->context_type == CONTEXT_SERVER) { void *conn_data = NULL; conn->phys_ctx->callbacks.init_connection(conn, &conn_data); mg_set_user_connection_data(conn, conn_data); } } } /* Process a connection - may handle multiple requests * using the same connection. * Must be called with a valid connection (conn and * conn->phys_ctx must be valid). */ static void process_new_connection(struct mg_connection *conn) { struct mg_request_info *ri = &conn->request_info; int keep_alive, discard_len; char ebuf[100]; const char *hostend; int reqerr, uri_type; #if defined(USE_SERVER_STATS) int mcon = mg_atomic_inc(&(conn->phys_ctx->active_connections)); mg_atomic_add(&(conn->phys_ctx->total_connections), 1); if (mcon > (conn->phys_ctx->max_connections)) { /* could use atomic compare exchange, but this * seems overkill for statistics data */ conn->phys_ctx->max_connections = mcon; } #endif init_connection(conn); DEBUG_TRACE("Start processing connection from %s", conn->request_info.remote_addr); /* Loop over multiple requests sent using the same connection * (while "keep alive"). */ do { DEBUG_TRACE("calling get_request (%i times for this connection)", conn->handled_requests + 1); #if defined(USE_SERVER_STATS) conn->conn_state = 3; /* ready */ #endif if (!get_request(conn, ebuf, sizeof(ebuf), &reqerr)) { /* The request sent by the client could not be understood by * the server, or it was incomplete or a timeout. Send an * error message and close the connection. */ if (reqerr > 0) { DEBUG_ASSERT(ebuf[0] != '\0'); mg_send_http_error(conn, reqerr, "%s", ebuf); } } else if (strcmp(ri->http_version, "1.0") && strcmp(ri->http_version, "1.1")) { mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, sizeof(ebuf), "Bad HTTP version: [%s]", ri->http_version); mg_send_http_error(conn, 505, "%s", ebuf); } if (ebuf[0] == '\0') { uri_type = get_uri_type(conn->request_info.request_uri); switch (uri_type) { case 1: /* Asterisk */ conn->request_info.local_uri = NULL; break; case 2: /* relative uri */ conn->request_info.local_uri = conn->request_info.request_uri; break; case 3: case 4: /* absolute uri (with/without port) */ hostend = get_rel_url_at_current_server( conn->request_info.request_uri, conn); if (hostend) { conn->request_info.local_uri = hostend; } else { conn->request_info.local_uri = NULL; } break; default: mg_snprintf(conn, NULL, /* No truncation check for ebuf */ ebuf, sizeof(ebuf), "Invalid URI"); mg_send_http_error(conn, 400, "%s", ebuf); conn->request_info.local_uri = NULL; break; } #if defined(MG_LEGACY_INTERFACE) /* Legacy before split into local_uri and request_uri */ conn->request_info.uri = conn->request_info.local_uri; #endif } DEBUG_TRACE("http: %s, error: %s", (ri->http_version ? ri->http_version : "none"), (ebuf[0] ? ebuf : "none")); if (ebuf[0] == '\0') { if (conn->request_info.local_uri) { /* handle request to local server */ #if defined(USE_SERVER_STATS) conn->conn_state = 4; /* processing */ #endif handle_request(conn); #if defined(USE_SERVER_STATS) conn->conn_state = 5; /* processed */ mg_atomic_add(&(conn->phys_ctx->total_data_read), conn->consumed_content); mg_atomic_add(&(conn->phys_ctx->total_data_written), conn->num_bytes_sent); #endif DEBUG_TRACE("%s", "handle_request done"); if (conn->phys_ctx->callbacks.end_request != NULL) { conn->phys_ctx->callbacks.end_request(conn, conn->status_code); DEBUG_TRACE("%s", "end_request callback done"); } log_access(conn); } else { /* TODO: handle non-local request (PROXY) */ conn->must_close = 1; } } else { conn->must_close = 1; } if (ri->remote_user != NULL) { mg_free((void *)ri->remote_user); /* Important! When having connections with and without auth * would cause double free and then crash */ ri->remote_user = NULL; } /* NOTE(lsm): order is important here. should_keep_alive() call * is using parsed request, which will be invalid after * memmove's below. * Therefore, memorize should_keep_alive() result now for later * use in loop exit condition. */ keep_alive = (conn->phys_ctx->stop_flag == 0) && should_keep_alive(conn) && (conn->content_len >= 0); /* Discard all buffered data for this request */ discard_len = ((conn->content_len >= 0) && (conn->request_len > 0) && ((conn->request_len + conn->content_len) < (int64_t)conn->data_len)) ? (int)(conn->request_len + conn->content_len) : conn->data_len; DEBUG_ASSERT(discard_len >= 0); if (discard_len < 0) { DEBUG_TRACE("internal error: discard_len = %li", (long int)discard_len); break; } conn->data_len -= discard_len; if (conn->data_len > 0) { DEBUG_TRACE("discard_len = %lu", (long unsigned)discard_len); memmove(conn->buf, conn->buf + discard_len, (size_t)conn->data_len); } DEBUG_ASSERT(conn->data_len >= 0); DEBUG_ASSERT(conn->data_len <= conn->buf_size); if ((conn->data_len < 0) || (conn->data_len > conn->buf_size)) { DEBUG_TRACE("internal error: data_len = %li, buf_size = %li", (long int)conn->data_len, (long int)conn->buf_size); break; } conn->handled_requests++; } while (keep_alive); DEBUG_TRACE("Done processing connection from %s (%f sec)", conn->request_info.remote_addr, difftime(time(NULL), conn->conn_birth_time)); close_connection(conn); #if defined(USE_SERVER_STATS) mg_atomic_add(&(conn->phys_ctx->total_requests), conn->handled_requests); mg_atomic_dec(&(conn->phys_ctx->active_connections)); #endif } #if defined(ALTERNATIVE_QUEUE) static void produce_socket(struct mg_context *ctx, const struct socket *sp) { unsigned int i; while (!ctx->stop_flag) { for (i = 0; i < ctx->cfg_worker_threads; i++) { /* find a free worker slot and signal it */ if (ctx->client_socks[i].in_use == 0) { ctx->client_socks[i] = *sp; ctx->client_socks[i].in_use = 1; event_signal(ctx->client_wait_events[i]); return; } } /* queue is full */ mg_sleep(1); } } static int consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index) { DEBUG_TRACE("%s", "going idle"); ctx->client_socks[thread_index].in_use = 0; event_wait(ctx->client_wait_events[thread_index]); *sp = ctx->client_socks[thread_index]; DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1); return !ctx->stop_flag; } #else /* ALTERNATIVE_QUEUE */ /* Worker threads take accepted socket from the queue */ static int consume_socket(struct mg_context *ctx, struct socket *sp, int thread_index) { #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue))) (void)thread_index; (void)pthread_mutex_lock(&ctx->thread_mutex); DEBUG_TRACE("%s", "going idle"); /* If the queue is empty, wait. We're idle at this point. */ while ((ctx->sq_head == ctx->sq_tail) && (ctx->stop_flag == 0)) { pthread_cond_wait(&ctx->sq_full, &ctx->thread_mutex); } /* If we're stopping, sq_head may be equal to sq_tail. */ if (ctx->sq_head > ctx->sq_tail) { /* Copy socket from the queue and increment tail */ *sp = ctx->queue[ctx->sq_tail % QUEUE_SIZE(ctx)]; ctx->sq_tail++; DEBUG_TRACE("grabbed socket %d, going busy", sp ? sp->sock : -1); /* Wrap pointers if needed */ while (ctx->sq_tail > QUEUE_SIZE(ctx)) { ctx->sq_tail -= QUEUE_SIZE(ctx); ctx->sq_head -= QUEUE_SIZE(ctx); } } (void)pthread_cond_signal(&ctx->sq_empty); (void)pthread_mutex_unlock(&ctx->thread_mutex); return !ctx->stop_flag; #undef QUEUE_SIZE } /* Master thread adds accepted socket to a queue */ static void produce_socket(struct mg_context *ctx, const struct socket *sp) { #define QUEUE_SIZE(ctx) ((int)(ARRAY_SIZE(ctx->queue))) if (!ctx) { return; } (void)pthread_mutex_lock(&ctx->thread_mutex); /* If the queue is full, wait */ while ((ctx->stop_flag == 0) && (ctx->sq_head - ctx->sq_tail >= QUEUE_SIZE(ctx))) { (void)pthread_cond_wait(&ctx->sq_empty, &ctx->thread_mutex); } if (ctx->sq_head - ctx->sq_tail < QUEUE_SIZE(ctx)) { /* Copy socket to the queue and increment head */ ctx->queue[ctx->sq_head % QUEUE_SIZE(ctx)] = *sp; ctx->sq_head++; DEBUG_TRACE("queued socket %d", sp ? sp->sock : -1); } (void)pthread_cond_signal(&ctx->sq_full); (void)pthread_mutex_unlock(&ctx->thread_mutex); #undef QUEUE_SIZE } #endif /* ALTERNATIVE_QUEUE */ struct worker_thread_args { struct mg_context *ctx; int index; }; static void * worker_thread_run(struct worker_thread_args *thread_args) { struct mg_context *ctx = thread_args->ctx; struct mg_connection *conn; struct mg_workerTLS tls; #if defined(MG_LEGACY_INTERFACE) uint32_t addr; #endif mg_set_thread_name("worker"); tls.is_master = 0; tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max); #if defined(_WIN32) tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL); #endif /* Initialize thread local storage before calling any callback */ pthread_setspecific(sTlsKey, &tls); if (ctx->callbacks.init_thread) { /* call init_thread for a worker thread (type 1) */ ctx->callbacks.init_thread(ctx, 1); } /* Connection structure has been pre-allocated */ if (((int)thread_args->index < 0) || ((unsigned)thread_args->index >= (unsigned)ctx->cfg_worker_threads)) { mg_cry_internal(fc(ctx), "Internal error: Invalid worker index %i", (int)thread_args->index); return NULL; } conn = ctx->worker_connections + thread_args->index; /* Request buffers are not pre-allocated. They are private to the * request and do not contain any state information that might be * of interest to anyone observing a server status. */ conn->buf = (char *)mg_malloc_ctx(ctx->max_request_size, conn->phys_ctx); if (conn->buf == NULL) { mg_cry_internal(fc(ctx), "Out of memory: Cannot allocate buffer for worker %i", (int)thread_args->index); return NULL; } conn->buf_size = (int)ctx->max_request_size; conn->phys_ctx = ctx; conn->dom_ctx = &(ctx->dd); /* Use default domain and default host */ conn->host = NULL; /* until we have more information. */ conn->thread_index = thread_args->index; conn->request_info.user_data = ctx->user_data; /* Allocate a mutex for this connection to allow communication both * within the request handler and from elsewhere in the application */ if (0 != pthread_mutex_init(&conn->mutex, &pthread_mutex_attr)) { mg_free(conn->buf); mg_cry_internal(fc(ctx), "%s", "Cannot create mutex"); return NULL; } #if defined(USE_SERVER_STATS) conn->conn_state = 1; /* not consumed */ #endif #if defined(ALTERNATIVE_QUEUE) while ((ctx->stop_flag == 0) && consume_socket(ctx, &conn->client, conn->thread_index)) { #else /* Call consume_socket() even when ctx->stop_flag > 0, to let it * signal sq_empty condvar to wake up the master waiting in * produce_socket() */ while (consume_socket(ctx, &conn->client, conn->thread_index)) { #endif conn->conn_birth_time = time(NULL); /* Fill in IP, port info early so even if SSL setup below fails, * error handler would have the corresponding info. * Thanks to Johannes Winkelmann for the patch. */ #if defined(USE_IPV6) if (conn->client.rsa.sa.sa_family == AF_INET6) { conn->request_info.remote_port = ntohs(conn->client.rsa.sin6.sin6_port); } else #endif { conn->request_info.remote_port = ntohs(conn->client.rsa.sin.sin_port); } sockaddr_to_string(conn->request_info.remote_addr, sizeof(conn->request_info.remote_addr), &conn->client.rsa); DEBUG_TRACE("Start processing connection from %s", conn->request_info.remote_addr); conn->request_info.is_ssl = conn->client.is_ssl; if (conn->client.is_ssl) { #if !defined(NO_SSL) /* HTTPS connection */ if (sslize(conn, conn->dom_ctx->ssl_ctx, SSL_accept, &(conn->phys_ctx->stop_flag))) { /* conn->dom_ctx is set in get_request */ /* Get SSL client certificate information (if set) */ ssl_get_client_cert_info(conn); /* process HTTPS connection */ process_new_connection(conn); /* Free client certificate info */ if (conn->request_info.client_cert) { mg_free((void *)(conn->request_info.client_cert->subject)); mg_free((void *)(conn->request_info.client_cert->issuer)); mg_free((void *)(conn->request_info.client_cert->serial)); mg_free((void *)(conn->request_info.client_cert->finger)); /* Free certificate memory */ X509_free( (X509 *)conn->request_info.client_cert->peer_cert); conn->request_info.client_cert->peer_cert = 0; conn->request_info.client_cert->subject = 0; conn->request_info.client_cert->issuer = 0; conn->request_info.client_cert->serial = 0; conn->request_info.client_cert->finger = 0; mg_free(conn->request_info.client_cert); conn->request_info.client_cert = 0; } } else { /* make sure the connection is cleaned up on SSL failure */ close_connection(conn); } #endif } else { /* process HTTP connection */ process_new_connection(conn); } DEBUG_TRACE("%s", "Connection closed"); } pthread_setspecific(sTlsKey, NULL); #if defined(_WIN32) CloseHandle(tls.pthread_cond_helper_mutex); #endif pthread_mutex_destroy(&conn->mutex); /* Free the request buffer. */ conn->buf_size = 0; mg_free(conn->buf); conn->buf = NULL; #if defined(USE_SERVER_STATS) conn->conn_state = 9; /* done */ #endif DEBUG_TRACE("%s", "exiting"); return NULL; } /* Threads have different return types on Windows and Unix. */ #if defined(_WIN32) static unsigned __stdcall worker_thread(void *thread_func_param) { struct worker_thread_args *pwta = (struct worker_thread_args *)thread_func_param; worker_thread_run(pwta); mg_free(thread_func_param); return 0; } #else static void * worker_thread(void *thread_func_param) { struct worker_thread_args *pwta = (struct worker_thread_args *)thread_func_param; struct sigaction sa; /* Ignore SIGPIPE */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, NULL); worker_thread_run(pwta); mg_free(thread_func_param); return NULL; } #endif /* _WIN32 */ /* This is an internal function, thus all arguments are expected to be * valid - a NULL check is not required. */ static void accept_new_connection(const struct socket *listener, struct mg_context *ctx) { struct socket so; char src_addr[IP_ADDR_STR_LEN]; socklen_t len = sizeof(so.rsa); int on = 1; if ((so.sock = accept(listener->sock, &so.rsa.sa, &len)) == INVALID_SOCKET) { } else if (!check_acl(ctx, ntohl(*(uint32_t *)&so.rsa.sin.sin_addr))) { sockaddr_to_string(src_addr, sizeof(src_addr), &so.rsa); mg_cry_internal(fc(ctx), "%s: %s is not allowed to connect", __func__, src_addr); closesocket(so.sock); } else { /* Put so socket structure into the queue */ DEBUG_TRACE("Accepted socket %d", (int)so.sock); set_close_on_exec(so.sock, fc(ctx)); so.is_ssl = listener->is_ssl; so.ssl_redir = listener->ssl_redir; if (getsockname(so.sock, &so.lsa.sa, &len) != 0) { mg_cry_internal(fc(ctx), "%s: getsockname() failed: %s", __func__, strerror(ERRNO)); } /* Set TCP keep-alive. This is needed because if HTTP-level * keep-alive * is enabled, and client resets the connection, server won't get * TCP FIN or RST and will keep the connection open forever. With * TCP keep-alive, next keep-alive handshake will figure out that * the client is down and will close the server end. * Thanks to Igor Klopov who suggested the patch. */ if (setsockopt(so.sock, SOL_SOCKET, SO_KEEPALIVE, (SOCK_OPT_TYPE)&on, sizeof(on)) != 0) { mg_cry_internal( fc(ctx), "%s: setsockopt(SOL_SOCKET SO_KEEPALIVE) failed: %s", __func__, strerror(ERRNO)); } /* Disable TCP Nagle's algorithm. Normally TCP packets are coalesced * to effectively fill up the underlying IP packet payload and * reduce the overhead of sending lots of small buffers. However * this hurts the server's throughput (ie. operations per second) * when HTTP 1.1 persistent connections are used and the responses * are relatively small (eg. less than 1400 bytes). */ if ((ctx->dd.config[CONFIG_TCP_NODELAY] != NULL) && (!strcmp(ctx->dd.config[CONFIG_TCP_NODELAY], "1"))) { if (set_tcp_nodelay(so.sock, 1) != 0) { mg_cry_internal( fc(ctx), "%s: setsockopt(IPPROTO_TCP TCP_NODELAY) failed: %s", __func__, strerror(ERRNO)); } } /* We are using non-blocking sockets. Thus, the * set_sock_timeout(so.sock, timeout); * call is no longer required. */ /* The "non blocking" property should already be * inherited from the parent socket. Set it for * non-compliant socket implementations. */ set_non_blocking_mode(so.sock); so.in_use = 0; produce_socket(ctx, &so); } } static void master_thread_run(void *thread_func_param) { struct mg_context *ctx = (struct mg_context *)thread_func_param; struct mg_workerTLS tls; struct pollfd *pfd; unsigned int i; unsigned int workerthreadcount; if (!ctx) { return; } mg_set_thread_name("master"); /* Increase priority of the master thread */ #if defined(_WIN32) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); #elif defined(USE_MASTER_THREAD_PRIORITY) int min_prio = sched_get_priority_min(SCHED_RR); int max_prio = sched_get_priority_max(SCHED_RR); if ((min_prio >= 0) && (max_prio >= 0) && ((USE_MASTER_THREAD_PRIORITY) <= max_prio) && ((USE_MASTER_THREAD_PRIORITY) >= min_prio)) { struct sched_param sched_param = {0}; sched_param.sched_priority = (USE_MASTER_THREAD_PRIORITY); pthread_setschedparam(pthread_self(), SCHED_RR, &sched_param); } #endif /* Initialize thread local storage */ #if defined(_WIN32) tls.pthread_cond_helper_mutex = CreateEvent(NULL, FALSE, FALSE, NULL); #endif tls.is_master = 1; pthread_setspecific(sTlsKey, &tls); if (ctx->callbacks.init_thread) { /* Callback for the master thread (type 0) */ ctx->callbacks.init_thread(ctx, 0); } /* Server starts *now* */ ctx->start_time = time(NULL); /* Start the server */ pfd = ctx->listening_socket_fds; while (ctx->stop_flag == 0) { for (i = 0; i < ctx->num_listening_sockets; i++) { pfd[i].fd = ctx->listening_sockets[i].sock; pfd[i].events = POLLIN; } if (poll(pfd, ctx->num_listening_sockets, 200) > 0) { for (i = 0; i < ctx->num_listening_sockets; i++) { /* NOTE(lsm): on QNX, poll() returns POLLRDNORM after the * successful poll, and POLLIN is defined as * (POLLRDNORM | POLLRDBAND) * Therefore, we're checking pfd[i].revents & POLLIN, not * pfd[i].revents == POLLIN. */ if ((ctx->stop_flag == 0) && (pfd[i].revents & POLLIN)) { accept_new_connection(&ctx->listening_sockets[i], ctx); } } } } /* Here stop_flag is 1 - Initiate shutdown. */ DEBUG_TRACE("%s", "stopping workers"); /* Stop signal received: somebody called mg_stop. Quit. */ close_all_listening_sockets(ctx); /* Wakeup workers that are waiting for connections to handle. */ (void)pthread_mutex_lock(&ctx->thread_mutex); #if defined(ALTERNATIVE_QUEUE) for (i = 0; i < ctx->cfg_worker_threads; i++) { event_signal(ctx->client_wait_events[i]); /* Since we know all sockets, we can shutdown the connections. */ if (ctx->client_socks[i].in_use) { shutdown(ctx->client_socks[i].sock, SHUTDOWN_BOTH); } } #else pthread_cond_broadcast(&ctx->sq_full); #endif (void)pthread_mutex_unlock(&ctx->thread_mutex); /* Join all worker threads to avoid leaking threads. */ workerthreadcount = ctx->cfg_worker_threads; for (i = 0; i < workerthreadcount; i++) { if (ctx->worker_threadids[i] != 0) { mg_join_thread(ctx->worker_threadids[i]); } } #if defined(USE_LUA) /* Free Lua state of lua background task */ if (ctx->lua_background_state) { lua_State *lstate = (lua_State *)ctx->lua_background_state; lua_getglobal(lstate, LUABACKGROUNDPARAMS); if (lua_istable(lstate, -1)) { reg_boolean(lstate, "shutdown", 1); lua_pop(lstate, 1); mg_sleep(2); } lua_close(lstate); ctx->lua_background_state = 0; } #endif DEBUG_TRACE("%s", "exiting"); #if defined(_WIN32) CloseHandle(tls.pthread_cond_helper_mutex); #endif pthread_setspecific(sTlsKey, NULL); /* Signal mg_stop() that we're done. * WARNING: This must be the very last thing this * thread does, as ctx becomes invalid after this line. */ ctx->stop_flag = 2; } /* Threads have different return types on Windows and Unix. */ #if defined(_WIN32) static unsigned __stdcall master_thread(void *thread_func_param) { master_thread_run(thread_func_param); return 0; } #else static void * master_thread(void *thread_func_param) { struct sigaction sa; /* Ignore SIGPIPE */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = SIG_IGN; sigaction(SIGPIPE, &sa, NULL); master_thread_run(thread_func_param); return NULL; } #endif /* _WIN32 */ static void free_context(struct mg_context *ctx) { int i; struct mg_handler_info *tmp_rh; if (ctx == NULL) { return; } if (ctx->callbacks.exit_context) { ctx->callbacks.exit_context(ctx); } /* All threads exited, no sync is needed. Destroy thread mutex and * condvars */ (void)pthread_mutex_destroy(&ctx->thread_mutex); #if defined(ALTERNATIVE_QUEUE) mg_free(ctx->client_socks); for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) { event_destroy(ctx->client_wait_events[i]); } mg_free(ctx->client_wait_events); #else (void)pthread_cond_destroy(&ctx->sq_empty); (void)pthread_cond_destroy(&ctx->sq_full); #endif /* Destroy other context global data structures mutex */ (void)pthread_mutex_destroy(&ctx->nonce_mutex); #if defined(USE_TIMERS) timers_exit(ctx); #endif /* Deallocate config parameters */ for (i = 0; i < NUM_OPTIONS; i++) { if (ctx->dd.config[i] != NULL) { #if defined(_MSC_VER) #pragma warning(suppress : 6001) #endif mg_free(ctx->dd.config[i]); } } /* Deallocate request handlers */ while (ctx->dd.handlers) { tmp_rh = ctx->dd.handlers; ctx->dd.handlers = tmp_rh->next; if (tmp_rh->handler_type == REQUEST_HANDLER) { pthread_cond_destroy(&tmp_rh->refcount_cond); pthread_mutex_destroy(&tmp_rh->refcount_mutex); } mg_free(tmp_rh->uri); mg_free(tmp_rh); } #if !defined(NO_SSL) /* Deallocate SSL context */ if (ctx->dd.ssl_ctx != NULL) { void *ssl_ctx = (void *)ctx->dd.ssl_ctx; int callback_ret = (ctx->callbacks.external_ssl_ctx == NULL) ? 0 : (ctx->callbacks.external_ssl_ctx(&ssl_ctx, ctx->user_data)); if (callback_ret == 0) { SSL_CTX_free(ctx->dd.ssl_ctx); } /* else: ignore error and ommit SSL_CTX_free in case * callback_ret is 1 */ } #endif /* !NO_SSL */ /* Deallocate worker thread ID array */ if (ctx->worker_threadids != NULL) { mg_free(ctx->worker_threadids); } /* Deallocate worker thread ID array */ if (ctx->worker_connections != NULL) { mg_free(ctx->worker_connections); } /* deallocate system name string */ mg_free(ctx->systemName); /* Deallocate context itself */ mg_free(ctx); } void mg_stop(struct mg_context *ctx) { pthread_t mt; if (!ctx) { return; } /* We don't use a lock here. Calling mg_stop with the same ctx from * two threads is not allowed. */ mt = ctx->masterthreadid; if (mt == 0) { return; } ctx->masterthreadid = 0; /* Set stop flag, so all threads know they have to exit. */ ctx->stop_flag = 1; /* Wait until everything has stopped. */ while (ctx->stop_flag != 2) { (void)mg_sleep(10); } mg_join_thread(mt); free_context(ctx); #if defined(_WIN32) (void)WSACleanup(); #endif /* _WIN32 */ } static void get_system_name(char **sysName) { #if defined(_WIN32) #if !defined(__SYMBIAN32__) #if defined(_WIN32_WCE) *sysName = mg_strdup("WinCE"); #else char name[128]; DWORD dwVersion = 0; DWORD dwMajorVersion = 0; DWORD dwMinorVersion = 0; DWORD dwBuild = 0; BOOL wowRet, isWoW = FALSE; #if defined(_MSC_VER) #pragma warning(push) /* GetVersion was declared deprecated */ #pragma warning(disable : 4996) #endif dwVersion = GetVersion(); #if defined(_MSC_VER) #pragma warning(pop) #endif dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion))); dwBuild = ((dwVersion < 0x80000000) ? (DWORD)(HIWORD(dwVersion)) : 0); (void)dwBuild; wowRet = IsWow64Process(GetCurrentProcess(), &isWoW); sprintf(name, "Windows %u.%u%s", (unsigned)dwMajorVersion, (unsigned)dwMinorVersion, (wowRet ? (isWoW ? " (WoW64)" : "") : " (?)")); *sysName = mg_strdup(name); #endif #else *sysName = mg_strdup("Symbian"); #endif #else struct utsname name; memset(&name, 0, sizeof(name)); uname(&name); *sysName = mg_strdup(name.sysname); #endif } struct mg_context * mg_start(const struct mg_callbacks *callbacks, void *user_data, const char **options) { struct mg_context *ctx; const char *name, *value, *default_value; int idx, ok, workerthreadcount; unsigned int i; int itmp; void (*exit_callback)(const struct mg_context *ctx) = 0; struct mg_workerTLS tls; #if defined(_WIN32) WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); #endif /* _WIN32 */ /* Allocate context and initialize reasonable general case defaults. */ if ((ctx = (struct mg_context *)mg_calloc(1, sizeof(*ctx))) == NULL) { return NULL; } /* Random number generator will initialize at the first call */ ctx->dd.auth_nonce_mask = (uint64_t)get_random() ^ (uint64_t)(ptrdiff_t)(options); if (mg_init_library_called == 0) { /* Legacy INIT, if mg_start is called without mg_init_library. * Note: This may cause a memory leak */ const char *ports_option = config_options[LISTENING_PORTS].default_value; if (options) { const char **run_options = options; const char *optname = config_options[LISTENING_PORTS].name; /* Try to find the "listening_ports" option */ while (*run_options) { if (!strcmp(*run_options, optname)) { ports_option = run_options[1]; } run_options += 2; } } if (is_ssl_port_used(ports_option)) { /* Initialize with SSL support */ mg_init_library(MG_FEATURES_TLS); } else { /* Initialize without SSL support */ mg_init_library(MG_FEATURES_DEFAULT); } } tls.is_master = -1; tls.thread_idx = (unsigned)mg_atomic_inc(&thread_idx_max); #if defined(_WIN32) tls.pthread_cond_helper_mutex = NULL; #endif pthread_setspecific(sTlsKey, &tls); ok = (0 == pthread_mutex_init(&ctx->thread_mutex, &pthread_mutex_attr)); #if !defined(ALTERNATIVE_QUEUE) ok &= (0 == pthread_cond_init(&ctx->sq_empty, NULL)); ok &= (0 == pthread_cond_init(&ctx->sq_full, NULL)); #endif ok &= (0 == pthread_mutex_init(&ctx->nonce_mutex, &pthread_mutex_attr)); if (!ok) { /* Fatal error - abort start. However, this situation should never * occur in practice. */ mg_cry_internal(fc(ctx), "%s", "Cannot initialize thread synchronization objects"); mg_free(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } if (callbacks) { ctx->callbacks = *callbacks; exit_callback = callbacks->exit_context; ctx->callbacks.exit_context = 0; } ctx->user_data = user_data; ctx->dd.handlers = NULL; ctx->dd.next = NULL; #if defined(USE_LUA) && defined(USE_WEBSOCKET) ctx->dd.shared_lua_websockets = NULL; #endif /* Store options */ while (options && (name = *options++) != NULL) { if ((idx = get_option_index(name)) == -1) { mg_cry_internal(fc(ctx), "Invalid option: %s", name); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } else if ((value = *options++) == NULL) { mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } if (ctx->dd.config[idx] != NULL) { mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name); mg_free(ctx->dd.config[idx]); } ctx->dd.config[idx] = mg_strdup_ctx(value, ctx); DEBUG_TRACE("[%s] -> [%s]", name, value); } /* Set default value if needed */ for (i = 0; config_options[i].name != NULL; i++) { default_value = config_options[i].default_value; if ((ctx->dd.config[i] == NULL) && (default_value != NULL)) { ctx->dd.config[i] = mg_strdup_ctx(default_value, ctx); } } /* Request size option */ itmp = atoi(ctx->dd.config[MAX_REQUEST_SIZE]); if (itmp < 1024) { mg_cry_internal(fc(ctx), "%s", "max_request_size too small"); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } ctx->max_request_size = (unsigned)itmp; /* Worker thread count option */ workerthreadcount = atoi(ctx->dd.config[NUM_THREADS]); if (workerthreadcount > MAX_WORKER_THREADS) { mg_cry_internal(fc(ctx), "%s", "Too many worker threads"); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } if (workerthreadcount <= 0) { mg_cry_internal(fc(ctx), "%s", "Invalid number of worker threads"); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } /* Document root */ #if defined(NO_FILES) if (ctx->dd.config[DOCUMENT_ROOT] != NULL) { mg_cry_internal(fc(ctx), "%s", "Document root must not be set"); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } #endif get_system_name(&ctx->systemName); #if defined(USE_LUA) /* If a Lua background script has been configured, start it. */ if (ctx->dd.config[LUA_BACKGROUND_SCRIPT] != NULL) { char ebuf[256]; struct vec opt_vec; struct vec eq_vec; const char *sparams; lua_State *state = mg_prepare_lua_context_script( ctx->dd.config[LUA_BACKGROUND_SCRIPT], ctx, ebuf, sizeof(ebuf)); if (!state) { mg_cry_internal(fc(ctx), "lua_background_script error: %s", ebuf); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } ctx->lua_background_state = (void *)state; lua_newtable(state); reg_boolean(state, "shutdown", 0); sparams = ctx->dd.config[LUA_BACKGROUND_SCRIPT_PARAMS]; while ((sparams = next_option(sparams, &opt_vec, &eq_vec)) != NULL) { reg_llstring( state, opt_vec.ptr, opt_vec.len, eq_vec.ptr, eq_vec.len); if (mg_strncasecmp(sparams, opt_vec.ptr, opt_vec.len) == 0) break; } lua_setglobal(state, LUABACKGROUNDPARAMS); } else { ctx->lua_background_state = 0; } #endif /* NOTE(lsm): order is important here. SSL certificates must * be initialized before listening ports. UID must be set last. */ if (!set_gpass_option(ctx, NULL) || #if !defined(NO_SSL) !init_ssl_ctx(ctx, NULL) || #endif !set_ports_option(ctx) || #if !defined(_WIN32) !set_uid_option(ctx) || #endif !set_acl_option(ctx)) { free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } ctx->cfg_worker_threads = ((unsigned int)(workerthreadcount)); ctx->worker_threadids = (pthread_t *)mg_calloc_ctx(ctx->cfg_worker_threads, sizeof(pthread_t), ctx); if (ctx->worker_threadids == NULL) { mg_cry_internal(fc(ctx), "%s", "Not enough memory for worker thread ID array"); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } ctx->worker_connections = (struct mg_connection *)mg_calloc_ctx(ctx->cfg_worker_threads, sizeof(struct mg_connection), ctx); if (ctx->worker_connections == NULL) { mg_cry_internal(fc(ctx), "%s", "Not enough memory for worker thread connection array"); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } #if defined(ALTERNATIVE_QUEUE) ctx->client_wait_events = (void **)mg_calloc_ctx(sizeof(ctx->client_wait_events[0]), ctx->cfg_worker_threads, ctx); if (ctx->client_wait_events == NULL) { mg_cry_internal(fc(ctx), "%s", "Not enough memory for worker event array"); mg_free(ctx->worker_threadids); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } ctx->client_socks = (struct socket *)mg_calloc_ctx(sizeof(ctx->client_socks[0]), ctx->cfg_worker_threads, ctx); if (ctx->client_socks == NULL) { mg_cry_internal(fc(ctx), "%s", "Not enough memory for worker socket array"); mg_free(ctx->client_wait_events); mg_free(ctx->worker_threadids); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } for (i = 0; (unsigned)i < ctx->cfg_worker_threads; i++) { ctx->client_wait_events[i] = event_create(); if (ctx->client_wait_events[i] == 0) { mg_cry_internal(fc(ctx), "Error creating worker event %i", i); while (i > 0) { i--; event_destroy(ctx->client_wait_events[i]); } mg_free(ctx->client_socks); mg_free(ctx->client_wait_events); mg_free(ctx->worker_threadids); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } } #endif #if defined(USE_TIMERS) if (timers_init(ctx) != 0) { mg_cry_internal(fc(ctx), "%s", "Error creating timers"); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } #endif /* Context has been created - init user libraries */ if (ctx->callbacks.init_context) { ctx->callbacks.init_context(ctx); } ctx->callbacks.exit_context = exit_callback; ctx->context_type = CONTEXT_SERVER; /* server context */ /* Start master (listening) thread */ mg_start_thread_with_id(master_thread, ctx, &ctx->masterthreadid); /* Start worker threads */ for (i = 0; i < ctx->cfg_worker_threads; i++) { struct worker_thread_args *wta = (struct worker_thread_args *) mg_malloc_ctx(sizeof(struct worker_thread_args), ctx); if (wta) { wta->ctx = ctx; wta->index = (int)i; } if ((wta == NULL) || (mg_start_thread_with_id(worker_thread, wta, &ctx->worker_threadids[i]) != 0)) { /* thread was not created */ if (wta != NULL) { mg_free(wta); } if (i > 0) { mg_cry_internal(fc(ctx), "Cannot start worker thread %i: error %ld", i + 1, (long)ERRNO); } else { mg_cry_internal(fc(ctx), "Cannot create threads: error %ld", (long)ERRNO); free_context(ctx); pthread_setspecific(sTlsKey, NULL); return NULL; } break; } } pthread_setspecific(sTlsKey, NULL); return ctx; } #if defined(MG_EXPERIMENTAL_INTERFACES) /* Add an additional domain to an already running web server. */ int mg_start_domain(struct mg_context *ctx, const char **options) { const char *name; const char *value; const char *default_value; struct mg_domain_context *new_dom; struct mg_domain_context *dom; int idx, i; if ((ctx == NULL) || (ctx->stop_flag != 0) || (options == NULL)) { return -1; } new_dom = (struct mg_domain_context *) mg_calloc_ctx(1, sizeof(struct mg_domain_context), ctx); if (!new_dom) { /* Out of memory */ return -6; } /* Store options - TODO: unite duplicate code */ while (options && (name = *options++) != NULL) { if ((idx = get_option_index(name)) == -1) { mg_cry_internal(fc(ctx), "Invalid option: %s", name); mg_free(new_dom); return -2; } else if ((value = *options++) == NULL) { mg_cry_internal(fc(ctx), "%s: option value cannot be NULL", name); mg_free(new_dom); return -2; } if (new_dom->config[idx] != NULL) { mg_cry_internal(fc(ctx), "warning: %s: duplicate option", name); mg_free(new_dom->config[idx]); } new_dom->config[idx] = mg_strdup_ctx(value, ctx); DEBUG_TRACE("[%s] -> [%s]", name, value); } /* Authentication domain is mandatory */ /* TODO: Maybe use a new option hostname? */ if (!new_dom->config[AUTHENTICATION_DOMAIN]) { mg_cry_internal(fc(ctx), "%s", "authentication domain required"); mg_free(new_dom); return -4; } /* Set default value if needed. Take the config value from * ctx as a default value. */ for (i = 0; config_options[i].name != NULL; i++) { default_value = ctx->dd.config[i]; if ((new_dom->config[i] == NULL) && (default_value != NULL)) { new_dom->config[i] = mg_strdup_ctx(default_value, ctx); } } new_dom->handlers = NULL; new_dom->next = NULL; new_dom->nonce_count = 0; new_dom->auth_nonce_mask = (uint64_t)get_random() ^ ((uint64_t)get_random() << 31); #if defined(USE_LUA) && defined(USE_WEBSOCKET) new_dom->shared_lua_websockets = NULL; #endif if (!init_ssl_ctx(ctx, new_dom)) { /* Init SSL failed */ mg_free(new_dom); return -3; } /* Add element to linked list. */ mg_lock_context(ctx); idx = 0; dom = &(ctx->dd); for (;;) { if (!strcasecmp(new_dom->config[AUTHENTICATION_DOMAIN], dom->config[AUTHENTICATION_DOMAIN])) { /* Domain collision */ mg_cry_internal(fc(ctx), "domain %s already in use", new_dom->config[AUTHENTICATION_DOMAIN]); mg_free(new_dom); return -5; } /* Count number of domains */ idx++; if (dom->next == NULL) { dom->next = new_dom; break; } dom = dom->next; } mg_unlock_context(ctx); /* Return domain number */ return idx; } #endif /* Feature check API function */ unsigned mg_check_feature(unsigned feature) { static const unsigned feature_set = 0 /* Set bits for available features according to API documentation. * This bit mask is created at compile time, according to the active * preprocessor defines. It is a single const value at runtime. */ #if !defined(NO_FILES) | MG_FEATURES_FILES #endif #if !defined(NO_SSL) | MG_FEATURES_SSL #endif #if !defined(NO_CGI) | MG_FEATURES_CGI #endif #if defined(USE_IPV6) | MG_FEATURES_IPV6 #endif #if defined(USE_WEBSOCKET) | MG_FEATURES_WEBSOCKET #endif #if defined(USE_LUA) | MG_FEATURES_LUA #endif #if defined(USE_DUKTAPE) | MG_FEATURES_SSJS #endif #if !defined(NO_CACHING) | MG_FEATURES_CACHE #endif #if defined(USE_SERVER_STATS) | MG_FEATURES_STATS #endif #if defined(USE_ZLIB) | MG_FEATURES_COMPRESSION #endif /* Set some extra bits not defined in the API documentation. * These bits may change without further notice. */ #if defined(MG_LEGACY_INTERFACE) | 0x00008000u #endif #if defined(MG_EXPERIMENTAL_INTERFACES) | 0x00004000u #endif #if defined(MEMORY_DEBUGGING) | 0x00001000u #endif #if defined(USE_TIMERS) | 0x00020000u #endif #if !defined(NO_NONCE_CHECK) | 0x00040000u #endif #if !defined(NO_POPEN) | 0x00080000u #endif ; return (feature & feature_set); } /* strcat with additional NULL check to avoid clang scan-build warning. */ #define strcat0(a, b) \ { \ if ((a != NULL) && (b != NULL)) { \ strcat(a, b); \ } \ } /* Get system information. It can be printed or stored by the caller. * Return the size of available information. */ static int mg_get_system_info_impl(char *buffer, int buflen) { char block[256]; int system_info_length = 0; #if defined(_WIN32) const char *eol = "\r\n"; #else const char *eol = "\n"; #endif const char *eoobj = "}"; int reserved_len = (int)strlen(eoobj) + (int)strlen(eol); if ((buffer == NULL) || (buflen < 1)) { buflen = 0; } else { *buffer = 0; } mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } /* Server version */ { const char *version = mg_version(); mg_snprintf(NULL, NULL, block, sizeof(block), "\"version\" : \"%s\",%s", version, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } } /* System info */ { #if defined(_WIN32) DWORD dwVersion = 0; DWORD dwMajorVersion = 0; DWORD dwMinorVersion = 0; SYSTEM_INFO si; GetSystemInfo(&si); #if defined(_MSC_VER) #pragma warning(push) /* GetVersion was declared deprecated */ #pragma warning(disable : 4996) #endif dwVersion = GetVersion(); #if defined(_MSC_VER) #pragma warning(pop) #endif dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion))); dwMinorVersion = (DWORD)(HIBYTE(LOWORD(dwVersion))); mg_snprintf(NULL, NULL, block, sizeof(block), "\"os\" : \"Windows %u.%u\",%s", (unsigned)dwMajorVersion, (unsigned)dwMinorVersion, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } mg_snprintf(NULL, NULL, block, sizeof(block), "\"cpu\" : \"type %u, cores %u, mask %x\",%s", (unsigned)si.wProcessorArchitecture, (unsigned)si.dwNumberOfProcessors, (unsigned)si.dwActiveProcessorMask, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #else struct utsname name; memset(&name, 0, sizeof(name)); uname(&name); mg_snprintf(NULL, NULL, block, sizeof(block), "\"os\" : \"%s %s (%s) - %s\",%s", name.sysname, name.version, name.release, name.machine, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #endif } /* Features */ { mg_snprintf(NULL, NULL, block, sizeof(block), "\"features\" : %lu,%s" "\"feature_list\" : \"Server:%s%s%s%s%s%s%s%s%s\",%s", (unsigned long)mg_check_feature(0xFFFFFFFFu), eol, mg_check_feature(MG_FEATURES_FILES) ? " Files" : "", mg_check_feature(MG_FEATURES_SSL) ? " HTTPS" : "", mg_check_feature(MG_FEATURES_CGI) ? " CGI" : "", mg_check_feature(MG_FEATURES_IPV6) ? " IPv6" : "", mg_check_feature(MG_FEATURES_WEBSOCKET) ? " WebSockets" : "", mg_check_feature(MG_FEATURES_LUA) ? " Lua" : "", mg_check_feature(MG_FEATURES_SSJS) ? " JavaScript" : "", mg_check_feature(MG_FEATURES_CACHE) ? " Cache" : "", mg_check_feature(MG_FEATURES_STATS) ? " Stats" : "", eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #if defined(USE_LUA) mg_snprintf(NULL, NULL, block, sizeof(block), "\"lua_version\" : \"%u (%s)\",%s", (unsigned)LUA_VERSION_NUM, LUA_RELEASE, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #endif #if defined(USE_DUKTAPE) mg_snprintf(NULL, NULL, block, sizeof(block), "\"javascript\" : \"Duktape %u.%u.%u\",%s", (unsigned)DUK_VERSION / 10000, ((unsigned)DUK_VERSION / 100) % 100, (unsigned)DUK_VERSION % 100, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #endif } /* Build date */ { #if defined(__GNUC__) #pragma GCC diagnostic push /* Disable bogus compiler warning -Wdate-time */ #pragma GCC diagnostic ignored "-Wdate-time" #endif mg_snprintf(NULL, NULL, block, sizeof(block), "\"build\" : \"%s\",%s", __DATE__, eol); #if defined(__GNUC__) #pragma GCC diagnostic pop #endif system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } } /* Compiler information */ /* http://sourceforge.net/p/predef/wiki/Compilers/ */ { #if defined(_MSC_VER) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"MSC: %u (%u)\",%s", (unsigned)_MSC_VER, (unsigned)_MSC_FULL_VER, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #elif defined(__MINGW64__) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"MinGW64: %u.%u\",%s", (unsigned)__MINGW64_VERSION_MAJOR, (unsigned)__MINGW64_VERSION_MINOR, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"MinGW32: %u.%u\",%s", (unsigned)__MINGW32_MAJOR_VERSION, (unsigned)__MINGW32_MINOR_VERSION, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #elif defined(__MINGW32__) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"MinGW32: %u.%u\",%s", (unsigned)__MINGW32_MAJOR_VERSION, (unsigned)__MINGW32_MINOR_VERSION, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #elif defined(__clang__) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"clang: %u.%u.%u (%s)\",%s", __clang_major__, __clang_minor__, __clang_patchlevel__, __clang_version__, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #elif defined(__GNUC__) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"gcc: %u.%u.%u\",%s", (unsigned)__GNUC__, (unsigned)__GNUC_MINOR__, (unsigned)__GNUC_PATCHLEVEL__, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #elif defined(__INTEL_COMPILER) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"Intel C/C++: %u\",%s", (unsigned)__INTEL_COMPILER, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #elif defined(__BORLANDC__) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"Borland C: 0x%x\",%s", (unsigned)__BORLANDC__, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #elif defined(__SUNPRO_C) mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"Solaris: 0x%x\",%s", (unsigned)__SUNPRO_C, eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #else mg_snprintf(NULL, NULL, block, sizeof(block), "\"compiler\" : \"other\",%s", eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } #endif } /* Determine 32/64 bit data mode. * see https://en.wikipedia.org/wiki/64-bit_computing */ { mg_snprintf(NULL, NULL, block, sizeof(block), "\"data_model\" : \"int:%u/%u/%u/%u, float:%u/%u/%u, " "char:%u/%u, " "ptr:%u, size:%u, time:%u\"%s", (unsigned)sizeof(short), (unsigned)sizeof(int), (unsigned)sizeof(long), (unsigned)sizeof(long long), (unsigned)sizeof(float), (unsigned)sizeof(double), (unsigned)sizeof(long double), (unsigned)sizeof(char), (unsigned)sizeof(wchar_t), (unsigned)sizeof(void *), (unsigned)sizeof(size_t), (unsigned)sizeof(time_t), eol); system_info_length += (int)strlen(block); if (system_info_length < buflen) { strcat0(buffer, block); } } /* Terminate string */ if ((buflen > 0) && buffer && buffer[0]) { if (system_info_length < buflen) { strcat0(buffer, eoobj); strcat0(buffer, eol); } } system_info_length += reserved_len; return system_info_length; } #if defined(USE_SERVER_STATS) /* Get context information. It can be printed or stored by the caller. * Return the size of available information. */ static int mg_get_context_info_impl(const struct mg_context *ctx, char *buffer, int buflen) { char block[256]; int context_info_length = 0; #if defined(_WIN32) const char *eol = "\r\n"; #else const char *eol = "\n"; #endif struct mg_memory_stat *ms = get_memory_stat((struct mg_context *)ctx); const char *eoobj = "}"; int reserved_len = (int)strlen(eoobj) + (int)strlen(eol); if ((buffer == NULL) || (buflen < 1)) { buflen = 0; } else { *buffer = 0; } mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol); context_info_length += (int)strlen(block); if (context_info_length < buflen) { strcat0(buffer, block); } if (ms) { /* <-- should be always true */ /* Memory information */ mg_snprintf(NULL, NULL, block, sizeof(block), "\"memory\" : {%s" "\"blocks\" : %i,%s" "\"used\" : %" INT64_FMT ",%s" "\"maxUsed\" : %" INT64_FMT "%s" "}%s%s", eol, ms->blockCount, eol, ms->totalMemUsed, eol, ms->maxMemUsed, eol, (ctx ? "," : ""), eol); context_info_length += (int)strlen(block); if (context_info_length + reserved_len < buflen) { strcat0(buffer, block); } } if (ctx) { /* Declare all variables at begin of the block, to comply * with old C standards. */ char start_time_str[64] = {0}; char now_str[64] = {0}; time_t start_time = ctx->start_time; time_t now = time(NULL); /* Connections information */ mg_snprintf(NULL, NULL, block, sizeof(block), "\"connections\" : {%s" "\"active\" : %i,%s" "\"maxActive\" : %i,%s" "\"total\" : %" INT64_FMT "%s" "},%s", eol, ctx->active_connections, eol, ctx->max_connections, eol, ctx->total_connections, eol, eol); context_info_length += (int)strlen(block); if (context_info_length + reserved_len < buflen) { strcat0(buffer, block); } /* Requests information */ mg_snprintf(NULL, NULL, block, sizeof(block), "\"requests\" : {%s" "\"total\" : %" INT64_FMT "%s" "},%s", eol, ctx->total_requests, eol, eol); context_info_length += (int)strlen(block); if (context_info_length + reserved_len < buflen) { strcat0(buffer, block); } /* Data information */ mg_snprintf(NULL, NULL, block, sizeof(block), "\"data\" : {%s" "\"read\" : %" INT64_FMT "%s," "\"written\" : %" INT64_FMT "%s" "},%s", eol, ctx->total_data_read, eol, ctx->total_data_written, eol, eol); context_info_length += (int)strlen(block); if (context_info_length + reserved_len < buflen) { strcat0(buffer, block); } /* Execution time information */ gmt_time_string(start_time_str, sizeof(start_time_str) - 1, &start_time); gmt_time_string(now_str, sizeof(now_str) - 1, &now); mg_snprintf(NULL, NULL, block, sizeof(block), "\"time\" : {%s" "\"uptime\" : %.0f,%s" "\"start\" : \"%s\",%s" "\"now\" : \"%s\"%s" "}%s", eol, difftime(now, start_time), eol, start_time_str, eol, now_str, eol, eol); context_info_length += (int)strlen(block); if (context_info_length + reserved_len < buflen) { strcat0(buffer, block); } } /* Terminate string */ if ((buflen > 0) && buffer && buffer[0]) { if (context_info_length < buflen) { strcat0(buffer, eoobj); strcat0(buffer, eol); } } context_info_length += reserved_len; return context_info_length; } #endif #if defined(MG_EXPERIMENTAL_INTERFACES) /* Get connection information. It can be printed or stored by the caller. * Return the size of available information. */ static int mg_get_connection_info_impl(const struct mg_context *ctx, int idx, char *buffer, int buflen) { const struct mg_connection *conn; const struct mg_request_info *ri; char block[256]; int connection_info_length = 0; int state = 0; const char *state_str = "unknown"; #if defined(_WIN32) const char *eol = "\r\n"; #else const char *eol = "\n"; #endif const char *eoobj = "}"; int reserved_len = (int)strlen(eoobj) + (int)strlen(eol); if ((buffer == NULL) || (buflen < 1)) { buflen = 0; } else { *buffer = 0; } if ((ctx == NULL) || (idx < 0)) { /* Parameter error */ return 0; } if ((unsigned)idx >= ctx->cfg_worker_threads) { /* Out of range */ return 0; } /* Take connection [idx]. This connection is not locked in * any way, so some other thread might use it. */ conn = (ctx->worker_connections) + idx; /* Initialize output string */ mg_snprintf(NULL, NULL, block, sizeof(block), "{%s", eol); connection_info_length += (int)strlen(block); if (connection_info_length < buflen) { strcat0(buffer, block); } /* Init variables */ ri = &(conn->request_info); #if defined(USE_SERVER_STATS) state = conn->conn_state; /* State as string */ switch (state) { case 0: state_str = "undefined"; break; case 1: state_str = "not used"; break; case 2: state_str = "init"; break; case 3: state_str = "ready"; break; case 4: state_str = "processing"; break; case 5: state_str = "processed"; break; case 6: state_str = "to close"; break; case 7: state_str = "closing"; break; case 8: state_str = "closed"; break; case 9: state_str = "done"; break; } #endif /* Connection info */ if ((state >= 3) && (state < 9)) { mg_snprintf(NULL, NULL, block, sizeof(block), "\"connection\" : {%s" "\"remote\" : {%s" "\"protocol\" : \"%s\",%s" "\"addr\" : \"%s\",%s" "\"port\" : %u%s" "},%s" "\"handled_requests\" : %u%s" "},%s", eol, eol, get_proto_name(conn), eol, ri->remote_addr, eol, ri->remote_port, eol, eol, conn->handled_requests, eol, eol); connection_info_length += (int)strlen(block); if (connection_info_length + reserved_len < buflen) { strcat0(buffer, block); } } /* Request info */ if ((state >= 4) && (state < 6)) { mg_snprintf(NULL, NULL, block, sizeof(block), "\"request_info\" : {%s" "\"method\" : \"%s\",%s" "\"uri\" : \"%s\",%s" "\"query\" : %s%s%s%s" "},%s", eol, ri->request_method, eol, ri->request_uri, eol, ri->query_string ? "\"" : "", ri->query_string ? ri->query_string : "null", ri->query_string ? "\"" : "", eol, eol); connection_info_length += (int)strlen(block); if (connection_info_length + reserved_len < buflen) { strcat0(buffer, block); } } /* Execution time information */ if ((state >= 2) && (state < 9)) { char start_time_str[64] = {0}; char now_str[64] = {0}; time_t start_time = conn->conn_birth_time; time_t now = time(NULL); gmt_time_string(start_time_str, sizeof(start_time_str) - 1, &start_time); gmt_time_string(now_str, sizeof(now_str) - 1, &now); mg_snprintf(NULL, NULL, block, sizeof(block), "\"time\" : {%s" "\"uptime\" : %.0f,%s" "\"start\" : \"%s\",%s" "\"now\" : \"%s\"%s" "},%s", eol, difftime(now, start_time), eol, start_time_str, eol, now_str, eol, eol); connection_info_length += (int)strlen(block); if (connection_info_length + reserved_len < buflen) { strcat0(buffer, block); } } /* Remote user name */ if ((ri->remote_user) && (state < 9)) { mg_snprintf(NULL, NULL, block, sizeof(block), "\"user\" : {%s" "\"name\" : \"%s\",%s" "},%s", eol, ri->remote_user, eol, eol); connection_info_length += (int)strlen(block); if (connection_info_length + reserved_len < buflen) { strcat0(buffer, block); } } /* Data block */ if (state >= 3) { mg_snprintf(NULL, NULL, block, sizeof(block), "\"data\" : {%s" "\"read\" : %" INT64_FMT ",%s" "\"written\" : %" INT64_FMT "%s" "},%s", eol, conn->consumed_content, eol, conn->num_bytes_sent, eol, eol); connection_info_length += (int)strlen(block); if (connection_info_length + reserved_len < buflen) { strcat0(buffer, block); } } /* State */ mg_snprintf(NULL, NULL, block, sizeof(block), "\"state\" : \"%s\"%s", state_str, eol); connection_info_length += (int)strlen(block); if (connection_info_length + reserved_len < buflen) { strcat0(buffer, block); } /* Terminate string */ if ((buflen > 0) && buffer && buffer[0]) { if (connection_info_length < buflen) { strcat0(buffer, eoobj); strcat0(buffer, eol); } } connection_info_length += reserved_len; return connection_info_length; } #endif /* Get system information. It can be printed or stored by the caller. * Return the size of available information. */ int mg_get_system_info(char *buffer, int buflen) { if ((buffer == NULL) || (buflen < 1)) { return mg_get_system_info_impl(NULL, 0); } else { /* Reset buffer, so we can always use strcat. */ buffer[0] = 0; return mg_get_system_info_impl(buffer, buflen); } } /* Get context information. It can be printed or stored by the caller. * Return the size of available information. */ int mg_get_context_info(const struct mg_context *ctx, char *buffer, int buflen) { #if defined(USE_SERVER_STATS) if ((buffer == NULL) || (buflen < 1)) { return mg_get_context_info_impl(ctx, NULL, 0); } else { /* Reset buffer, so we can always use strcat. */ buffer[0] = 0; return mg_get_context_info_impl(ctx, buffer, buflen); } #else (void)ctx; if ((buffer != NULL) && (buflen > 0)) { buffer[0] = 0; } return 0; #endif } #if defined(MG_EXPERIMENTAL_INTERFACES) int mg_get_connection_info(const struct mg_context *ctx, int idx, char *buffer, int buflen) { if ((buffer == NULL) || (buflen < 1)) { return mg_get_connection_info_impl(ctx, idx, NULL, 0); } else { /* Reset buffer, so we can always use strcat. */ buffer[0] = 0; return mg_get_connection_info_impl(ctx, idx, buffer, buflen); } } #endif /* Initialize this library. This function does not need to be thread safe. */ unsigned mg_init_library(unsigned features) { #if !defined(NO_SSL) char ebuf[128]; #endif unsigned features_to_init = mg_check_feature(features & 0xFFu); unsigned features_inited = features_to_init; if (mg_init_library_called <= 0) { /* Not initialized yet */ if (0 != pthread_mutex_init(&global_lock_mutex, NULL)) { return 0; } } mg_global_lock(); if (mg_init_library_called <= 0) { if (0 != pthread_key_create(&sTlsKey, tls_dtor)) { /* Fatal error - abort start. However, this situation should * never occur in practice. */ mg_global_unlock(); return 0; } #if defined(_WIN32) InitializeCriticalSection(&global_log_file_lock); #endif #if !defined(_WIN32) pthread_mutexattr_init(&pthread_mutex_attr); pthread_mutexattr_settype(&pthread_mutex_attr, PTHREAD_MUTEX_RECURSIVE); #endif #if defined(USE_LUA) lua_init_optional_libraries(); #endif } mg_global_unlock(); #if !defined(NO_SSL) if (features_to_init & MG_FEATURES_SSL) { if (!mg_ssl_initialized) { if (initialize_ssl(ebuf, sizeof(ebuf))) { mg_ssl_initialized = 1; } else { (void)ebuf; DEBUG_TRACE("Initializing SSL failed: %s", ebuf); features_inited &= ~((unsigned)(MG_FEATURES_SSL)); } } else { /* ssl already initialized */ } } #endif /* Start WinSock for Windows */ mg_global_lock(); if (mg_init_library_called <= 0) { #if defined(_WIN32) WSADATA data; WSAStartup(MAKEWORD(2, 2), &data); #endif /* _WIN32 */ mg_init_library_called = 1; } else { mg_init_library_called++; } mg_global_unlock(); return features_inited; } /* Un-initialize this library. */ unsigned mg_exit_library(void) { if (mg_init_library_called <= 0) { return 0; } mg_global_lock(); mg_init_library_called--; if (mg_init_library_called == 0) { #if defined(_WIN32) (void)WSACleanup(); #endif /* _WIN32 */ #if !defined(NO_SSL) if (mg_ssl_initialized) { uninitialize_ssl(); mg_ssl_initialized = 0; } #endif #if defined(_WIN32) (void)DeleteCriticalSection(&global_log_file_lock); #endif /* _WIN32 */ #if !defined(_WIN32) (void)pthread_mutexattr_destroy(&pthread_mutex_attr); #endif (void)pthread_key_delete(sTlsKey); #if defined(USE_LUA) lua_exit_optional_libraries(); #endif mg_global_unlock(); (void)pthread_mutex_destroy(&global_lock_mutex); return 1; } mg_global_unlock(); return 1; } /* End of civetweb.c */
./CrossVul/dataset_final_sorted/CWE-200/c/good_203_0
crossvul-cpp_data_bad_1596_2
404: Not Found
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1596_2
crossvul-cpp_data_bad_5678_0
/* * algif_hash: User-space interface for hash algorithms * * This file provides the user-space API for hash algorithms. * * Copyright (c) 2010 Herbert Xu <herbert@gondor.apana.org.au> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the Free * Software Foundation; either version 2 of the License, or (at your option) * any later version. * */ #include <crypto/hash.h> #include <crypto/if_alg.h> #include <linux/init.h> #include <linux/kernel.h> #include <linux/mm.h> #include <linux/module.h> #include <linux/net.h> #include <net/sock.h> struct hash_ctx { struct af_alg_sgl sgl; u8 *result; struct af_alg_completion completion; unsigned int len; bool more; struct ahash_request req; }; static int hash_sendmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t ignored) { int limit = ALG_MAX_PAGES * PAGE_SIZE; struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned long iovlen; struct iovec *iov; long copied = 0; int err; if (limit > sk->sk_sndbuf) limit = sk->sk_sndbuf; lock_sock(sk); if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } ctx->more = 0; for (iov = msg->msg_iov, iovlen = msg->msg_iovlen; iovlen > 0; iovlen--, iov++) { unsigned long seglen = iov->iov_len; char __user *from = iov->iov_base; while (seglen) { int len = min_t(unsigned long, seglen, limit); int newlen; newlen = af_alg_make_sg(&ctx->sgl, from, len, 0); if (newlen < 0) { err = copied ? 0 : newlen; goto unlock; } ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, NULL, newlen); err = af_alg_wait_for_completion( crypto_ahash_update(&ctx->req), &ctx->completion); af_alg_free_sg(&ctx->sgl); if (err) goto unlock; seglen -= newlen; from += newlen; copied += newlen; } } err = 0; ctx->more = msg->msg_flags & MSG_MORE; if (!ctx->more) { ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); } unlock: release_sock(sk); return err ?: copied; } static ssize_t hash_sendpage(struct socket *sock, struct page *page, int offset, size_t size, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; int err; lock_sock(sk); sg_init_table(ctx->sgl.sg, 1); sg_set_page(ctx->sgl.sg, page, size, offset); ahash_request_set_crypt(&ctx->req, ctx->sgl.sg, ctx->result, size); if (!(flags & MSG_MORE)) { if (ctx->more) err = crypto_ahash_finup(&ctx->req); else err = crypto_ahash_digest(&ctx->req); } else { if (!ctx->more) { err = crypto_ahash_init(&ctx->req); if (err) goto unlock; } err = crypto_ahash_update(&ctx->req); } err = af_alg_wait_for_completion(err, &ctx->completion); if (err) goto unlock; ctx->more = flags & MSG_MORE; unlock: release_sock(sk); return err ?: size; } static int hash_recvmsg(struct kiocb *unused, struct socket *sock, struct msghdr *msg, size_t len, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; unsigned ds = crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req)); int err; if (len > ds) len = ds; else if (len < ds) msg->msg_flags |= MSG_TRUNC; lock_sock(sk); if (ctx->more) { ctx->more = 0; ahash_request_set_crypt(&ctx->req, NULL, ctx->result, 0); err = af_alg_wait_for_completion(crypto_ahash_final(&ctx->req), &ctx->completion); if (err) goto unlock; } err = memcpy_toiovec(msg->msg_iov, ctx->result, len); unlock: release_sock(sk); return err ?: len; } static int hash_accept(struct socket *sock, struct socket *newsock, int flags) { struct sock *sk = sock->sk; struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; struct ahash_request *req = &ctx->req; char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))]; struct sock *sk2; struct alg_sock *ask2; struct hash_ctx *ctx2; int err; err = crypto_ahash_export(req, state); if (err) return err; err = af_alg_accept(ask->parent, newsock); if (err) return err; sk2 = newsock->sk; ask2 = alg_sk(sk2); ctx2 = ask2->private; ctx2->more = 1; err = crypto_ahash_import(&ctx2->req, state); if (err) { sock_orphan(sk2); sock_put(sk2); } return err; } static struct proto_ops algif_hash_ops = { .family = PF_ALG, .connect = sock_no_connect, .socketpair = sock_no_socketpair, .getname = sock_no_getname, .ioctl = sock_no_ioctl, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .getsockopt = sock_no_getsockopt, .mmap = sock_no_mmap, .bind = sock_no_bind, .setsockopt = sock_no_setsockopt, .poll = sock_no_poll, .release = af_alg_release, .sendmsg = hash_sendmsg, .sendpage = hash_sendpage, .recvmsg = hash_recvmsg, .accept = hash_accept, }; static void *hash_bind(const char *name, u32 type, u32 mask) { return crypto_alloc_ahash(name, type, mask); } static void hash_release(void *private) { crypto_free_ahash(private); } static int hash_setkey(void *private, const u8 *key, unsigned int keylen) { return crypto_ahash_setkey(private, key, keylen); } static void hash_sock_destruct(struct sock *sk) { struct alg_sock *ask = alg_sk(sk); struct hash_ctx *ctx = ask->private; sock_kfree_s(sk, ctx->result, crypto_ahash_digestsize(crypto_ahash_reqtfm(&ctx->req))); sock_kfree_s(sk, ctx, ctx->len); af_alg_release_parent(sk); } static int hash_accept_parent(void *private, struct sock *sk) { struct hash_ctx *ctx; struct alg_sock *ask = alg_sk(sk); unsigned len = sizeof(*ctx) + crypto_ahash_reqsize(private); unsigned ds = crypto_ahash_digestsize(private); ctx = sock_kmalloc(sk, len, GFP_KERNEL); if (!ctx) return -ENOMEM; ctx->result = sock_kmalloc(sk, ds, GFP_KERNEL); if (!ctx->result) { sock_kfree_s(sk, ctx, len); return -ENOMEM; } memset(ctx->result, 0, ds); ctx->len = len; ctx->more = 0; af_alg_init_completion(&ctx->completion); ask->private = ctx; ahash_request_set_tfm(&ctx->req, private); ahash_request_set_callback(&ctx->req, CRYPTO_TFM_REQ_MAY_BACKLOG, af_alg_complete, &ctx->completion); sk->sk_destruct = hash_sock_destruct; return 0; } static const struct af_alg_type algif_type_hash = { .bind = hash_bind, .release = hash_release, .setkey = hash_setkey, .accept = hash_accept_parent, .ops = &algif_hash_ops, .name = "hash", .owner = THIS_MODULE }; static int __init algif_hash_init(void) { return af_alg_register_type(&algif_type_hash); } static void __exit algif_hash_exit(void) { int err = af_alg_unregister_type(&algif_type_hash); BUG_ON(err); } module_init(algif_hash_init); module_exit(algif_hash_exit); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5678_0
crossvul-cpp_data_bad_437_0
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Main program structure. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <stdlib.h> #include <sys/utsname.h> #include <sys/resource.h> #include <stdbool.h> #ifdef HAVE_SIGNALFD #include <sys/signalfd.h> #endif #include <errno.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include <getopt.h> #include <linux/version.h> #include <ctype.h> #include "main.h" #include "global_data.h" #include "daemon.h" #include "config.h" #include "git-commit.h" #include "utils.h" #include "signals.h" #include "pidfile.h" #include "bitops.h" #include "logger.h" #include "parser.h" #include "notify.h" #include "utils.h" #ifdef _WITH_LVS_ #include "check_parser.h" #include "check_daemon.h" #endif #ifdef _WITH_VRRP_ #include "vrrp_daemon.h" #include "vrrp_parser.h" #include "vrrp_if.h" #ifdef _WITH_JSON_ #include "vrrp_json.h" #endif #endif #ifdef _WITH_BFD_ #include "bfd_daemon.h" #include "bfd_parser.h" #endif #include "global_parser.h" #if HAVE_DECL_CLONE_NEWNET #include "namespaces.h" #endif #include "scheduler.h" #include "keepalived_netlink.h" #include "git-commit.h" #if defined THREAD_DUMP || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ #include "scheduler.h" #endif #include "process.h" #ifdef _TIMER_CHECK_ #include "timer.h" #endif #ifdef _SMTP_ALERT_DEBUG_ #include "smtp.h" #endif #if defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ #include "check_http.h" #endif #ifdef _TSM_DEBUG_ #include "vrrp_scheduler.h" #endif /* musl libc doesn't define the following */ #ifndef W_EXITCODE #define W_EXITCODE(ret, sig) ((ret) << 8 | (sig)) #endif #ifndef WCOREFLAG #define WCOREFLAG ((int32_t)WCOREDUMP(0xffffffff)) #endif #define VERSION_STRING PACKAGE_NAME " v" PACKAGE_VERSION " (" GIT_DATE ")" #define COPYRIGHT_STRING "Copyright(C) 2001-" GIT_YEAR " Alexandre Cassen, <acassen@gmail.com>" #define CHILD_WAIT_SECS 5 /* global var */ const char *version_string = VERSION_STRING; /* keepalived version */ char *conf_file = KEEPALIVED_CONFIG_FILE; /* Configuration file */ int log_facility = LOG_DAEMON; /* Optional logging facilities */ bool reload; /* Set during a reload */ char *main_pidfile; /* overrule default pidfile */ static bool free_main_pidfile; #ifdef _WITH_LVS_ pid_t checkers_child; /* Healthcheckers child process ID */ char *checkers_pidfile; /* overrule default pidfile */ static bool free_checkers_pidfile; #endif #ifdef _WITH_VRRP_ pid_t vrrp_child; /* VRRP child process ID */ char *vrrp_pidfile; /* overrule default pidfile */ static bool free_vrrp_pidfile; #endif #ifdef _WITH_BFD_ pid_t bfd_child; /* BFD child process ID */ char *bfd_pidfile; /* overrule default pidfile */ static bool free_bfd_pidfile; #endif unsigned long daemon_mode; /* VRRP/CHECK/BFD subsystem selection */ #ifdef _WITH_SNMP_ bool snmp; /* Enable SNMP support */ const char *snmp_socket; /* Socket to use for SNMP agent */ #endif static char *syslog_ident; /* syslog ident if not default */ bool use_pid_dir; /* Put pid files in /var/run/keepalived or @localstatedir@/run/keepalived */ unsigned os_major; /* Kernel version */ unsigned os_minor; unsigned os_release; char *hostname; /* Initial part of hostname */ #if HAVE_DECL_CLONE_NEWNET static char *override_namespace; /* If namespace specified on command line */ #endif unsigned child_wait_time = CHILD_WAIT_SECS; /* Time to wait for children to exit */ /* Log facility table */ static struct { int facility; } LOG_FACILITY[] = { {LOG_LOCAL0}, {LOG_LOCAL1}, {LOG_LOCAL2}, {LOG_LOCAL3}, {LOG_LOCAL4}, {LOG_LOCAL5}, {LOG_LOCAL6}, {LOG_LOCAL7} }; #define LOG_FACILITY_MAX ((sizeof(LOG_FACILITY) / sizeof(LOG_FACILITY[0])) - 1) /* umask settings */ bool umask_cmdline; static mode_t umask_val = S_IXUSR | S_IWGRP | S_IXGRP | S_IWOTH | S_IXOTH; /* Control producing core dumps */ static bool set_core_dump_pattern = false; static bool create_core_dump = false; static const char *core_dump_pattern = "core"; static char *orig_core_dump_pattern = NULL; /* debug flags */ #if defined _TIMER_CHECK_ || defined _SMTP_ALERT_DEBUG_ || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ || defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ || defined _TSM_DEBUG_ || defined _VRRP_FD_DEBUG_ || defined _NETLINK_TIMERS_ #define WITH_DEBUG_OPTIONS 1 #endif #ifdef _TIMER_CHECK_ static char timer_debug; #endif #ifdef _SMTP_ALERT_DEBUG_ static char smtp_debug; #endif #ifdef _EPOLL_DEBUG_ static char epoll_debug; #endif #ifdef _EPOLL_THREAD_DUMP_ static char epoll_thread_debug; #endif #ifdef _REGEX_DEBUG_ static char regex_debug; #endif #ifdef _WITH_REGEX_TIMERS_ static char regex_timers; #endif #ifdef _TSM_DEBUG_ static char tsm_debug; #endif #ifdef _VRRP_FD_DEBUG_ static char vrrp_fd_debug; #endif #ifdef _NETLINK_TIMERS_ static char netlink_timer_debug; #endif void free_parent_mallocs_startup(bool am_child) { if (am_child) { #if HAVE_DECL_CLONE_NEWNET free_dirname(); #endif #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else free(syslog_ident); #endif syslog_ident = NULL; FREE_PTR(orig_core_dump_pattern); } if (free_main_pidfile) { FREE_PTR(main_pidfile); free_main_pidfile = false; } } void free_parent_mallocs_exit(void) { #ifdef _WITH_VRRP_ if (free_vrrp_pidfile) FREE_PTR(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (free_checkers_pidfile) FREE_PTR(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (free_bfd_pidfile) FREE_PTR(bfd_pidfile); #endif FREE_PTR(config_id); } char * make_syslog_ident(const char* name) { size_t ident_len = strlen(name) + 1; char *ident; #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) ident_len += strlen(global_data->network_namespace) + 1; #endif if (global_data->instance_name) ident_len += strlen(global_data->instance_name) + 1; /* If we are writing MALLOC/FREE info to the log, we have * trouble FREEing the syslog_ident */ #ifndef _MEM_CHECK_LOG_ ident = MALLOC(ident_len); #else ident = malloc(ident_len); #endif if (!ident) return NULL; strcpy(ident, name); #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { strcat(ident, "_"); strcat(ident, global_data->network_namespace); } #endif if (global_data->instance_name) { strcat(ident, "_"); strcat(ident, global_data->instance_name); } return ident; } static char * make_pidfile_name(const char* start, const char* instance, const char* extn) { size_t len; char *name; len = strlen(start) + 1; if (instance) len += strlen(instance) + 1; if (extn) len += strlen(extn); name = MALLOC(len); if (!name) { log_message(LOG_INFO, "Unable to make pidfile name for %s", start); return NULL; } strcpy(name, start); if (instance) { strcat(name, "_"); strcat(name, instance); } if (extn) strcat(name, extn); return name; } #ifdef _WITH_VRRP_ bool running_vrrp(void) { return (__test_bit(DAEMON_VRRP, &daemon_mode) && (global_data->have_vrrp_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_LVS_ bool running_checker(void) { return (__test_bit(DAEMON_CHECKERS, &daemon_mode) && (global_data->have_checker_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_BFD_ bool running_bfd(void) { return (__test_bit(DAEMON_BFD, &daemon_mode) && (global_data->have_bfd_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif static char const * find_keepalived_child_name(pid_t pid) { #ifdef _WITH_LVS_ if (pid == checkers_child) return PROG_CHECK; #endif #ifdef _WITH_VRRP_ if (pid == vrrp_child) return PROG_VRRP; #endif #ifdef _WITH_BFD_ if (pid == bfd_child) return PROG_BFD; #endif return NULL; } static vector_t * global_init_keywords(void) { /* global definitions mapping */ init_global_keywords(true); #ifdef _WITH_VRRP_ init_vrrp_keywords(false); #endif #ifdef _WITH_LVS_ init_check_keywords(false); #endif #ifdef _WITH_BFD_ init_bfd_keywords(false); #endif return keywords; } static void read_config_file(void) { init_data(conf_file, global_init_keywords); } /* Daemon stop sequence */ void stop_keepalived(void) { #ifndef _DEBUG_ /* Just cleanup memory & exit */ thread_destroy_master(master); #ifdef _WITH_VRRP_ if (__test_bit(DAEMON_VRRP, &daemon_mode)) pidfile_rm(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (__test_bit(DAEMON_CHECKERS, &daemon_mode)) pidfile_rm(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (__test_bit(DAEMON_BFD, &daemon_mode)) pidfile_rm(bfd_pidfile); #endif pidfile_rm(main_pidfile); #endif } /* Daemon init sequence */ static int start_keepalived(void) { bool have_child = false; #ifdef _WITH_BFD_ /* must be opened before vrrp and bfd start */ open_bfd_pipes(); #endif #ifdef _WITH_LVS_ /* start healthchecker child */ if (running_checker()) { start_check_child(); have_child = true; } #endif #ifdef _WITH_VRRP_ /* start vrrp child */ if (running_vrrp()) { start_vrrp_child(); have_child = true; } #endif #ifdef _WITH_BFD_ /* start bfd child */ if (running_bfd()) { start_bfd_child(); have_child = true; } #endif return have_child; } static void validate_config(void) { #ifdef _WITH_VRRP_ kernel_netlink_read_interfaces(); #endif #ifdef _WITH_LVS_ /* validate healthchecker config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_CHECKER; #endif check_validate_config(); #endif #ifdef _WITH_VRRP_ /* validate vrrp config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_VRRP; #endif vrrp_validate_config(); #endif #ifdef _WITH_BFD_ /* validate bfd config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_BFD; #endif bfd_validate_config(); #endif } static void config_test_exit(void) { config_err_t config_err = get_config_status(); switch (config_err) { case CONFIG_OK: exit(KEEPALIVED_EXIT_OK); case CONFIG_FILE_NOT_FOUND: case CONFIG_BAD_IF: case CONFIG_FATAL: exit(KEEPALIVED_EXIT_CONFIG); case CONFIG_SECURITY_ERROR: exit(KEEPALIVED_EXIT_CONFIG_TEST_SECURITY); default: exit(KEEPALIVED_EXIT_CONFIG_TEST); } } #ifndef _DEBUG_ static bool reload_config(void) { bool unsupported_change = false; log_message(LOG_INFO, "Reloading ..."); /* Make sure there isn't an attempt to change the network namespace or instance name */ old_global_data = global_data; global_data = NULL; global_data = alloc_global_data(); read_config_file(); init_global_data(global_data, old_global_data); #if HAVE_DECL_CLONE_NEWNET if (!!old_global_data->network_namespace != !!global_data->network_namespace || (global_data->network_namespace && strcmp(old_global_data->network_namespace, global_data->network_namespace))) { log_message(LOG_INFO, "Cannot change network namespace at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->network_namespace); global_data->network_namespace = old_global_data->network_namespace; old_global_data->network_namespace = NULL; #endif if (!!old_global_data->instance_name != !!global_data->instance_name || (global_data->instance_name && strcmp(old_global_data->instance_name, global_data->instance_name))) { log_message(LOG_INFO, "Cannot change instance name at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->instance_name); global_data->instance_name = old_global_data->instance_name; old_global_data->instance_name = NULL; if (unsupported_change) { /* We cannot reload the configuration, so continue with the old config */ free_global_data (global_data); global_data = old_global_data; } else free_global_data (old_global_data); return !unsupported_change; } /* SIGHUP/USR1/USR2 handler */ static void propagate_signal(__attribute__((unused)) void *v, int sig) { if (sig == SIGHUP) { if (!reload_config()) return; } /* Signal child processes */ #ifdef _WITH_VRRP_ if (vrrp_child > 0) kill(vrrp_child, sig); else if (sig == SIGHUP && running_vrrp()) start_vrrp_child(); #endif #ifdef _WITH_LVS_ if (sig == SIGHUP) { if (checkers_child > 0) kill(checkers_child, sig); else if (running_checker()) start_check_child(); } #endif #ifdef _WITH_BFD_ if (sig == SIGHUP) { if (bfd_child > 0) kill(bfd_child, sig); else if (running_bfd()) start_bfd_child(); } #endif } /* Terminate handler */ static void sigend(__attribute__((unused)) void *v, __attribute__((unused)) int sig) { int status; int ret; int wait_count = 0; struct timeval start_time, now; #ifdef HAVE_SIGNALFD struct timeval timeout = { .tv_sec = child_wait_time, .tv_usec = 0 }; int signal_fd = master->signal_fd; fd_set read_set; struct signalfd_siginfo siginfo; sigset_t sigmask; #else sigset_t old_set, child_wait; struct timespec timeout = { .tv_sec = child_wait_time, .tv_nsec = 0 }; #endif /* register the terminate thread */ thread_add_terminate_event(master); log_message(LOG_INFO, "Stopping"); #ifdef HAVE_SIGNALFD /* We only want to receive SIGCHLD now */ sigemptyset(&sigmask); sigaddset(&sigmask, SIGCHLD); signalfd(signal_fd, &sigmask, 0); FD_ZERO(&read_set); #else sigmask_func(0, NULL, &old_set); if (!sigismember(&old_set, SIGCHLD)) { sigemptyset(&child_wait); sigaddset(&child_wait, SIGCHLD); sigmask_func(SIG_BLOCK, &child_wait, NULL); } #endif #ifdef _WITH_VRRP_ if (vrrp_child > 0) { if (kill(vrrp_child, SIGTERM)) { /* ESRCH means no such process */ if (errno == ESRCH) vrrp_child = 0; } else wait_count++; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0) { if (kill(checkers_child, SIGTERM)) { if (errno == ESRCH) checkers_child = 0; } else wait_count++; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0) { if (kill(bfd_child, SIGTERM)) { if (errno == ESRCH) bfd_child = 0; } else wait_count++; } #endif gettimeofday(&start_time, NULL); while (wait_count) { #ifdef HAVE_SIGNALFD FD_SET(signal_fd, &read_set); ret = select(signal_fd + 1, &read_set, NULL, NULL, &timeout); if (ret == 0) break; if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "Terminating select returned errno %d", errno); break; } if (!FD_ISSET(signal_fd, &read_set)) { log_message(LOG_INFO, "Terminating select did not return select_fd"); continue; } if (read(signal_fd, &siginfo, sizeof(siginfo)) != sizeof(siginfo)) { log_message(LOG_INFO, "Terminating signal read did not read entire siginfo"); break; } status = siginfo.ssi_code == CLD_EXITED ? W_EXITCODE(siginfo.ssi_status, 0) : siginfo.ssi_code == CLD_KILLED ? W_EXITCODE(0, siginfo.ssi_status) : WCOREFLAG; #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #else ret = sigtimedwait(&child_wait, NULL, &timeout); if (ret == -1) { if (errno == EINTR) continue; if (errno == EAGAIN) break; } #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == waitpid(vrrp_child, &status, WNOHANG)) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == waitpid(checkers_child, &status, WNOHANG)) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == waitpid(bfd_child, &status, WNOHANG)) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #endif if (wait_count) { gettimeofday(&now, NULL); timeout.tv_sec = child_wait_time - (now.tv_sec - start_time.tv_sec); #ifdef HAVE_SIGNALFD timeout.tv_usec = (start_time.tv_usec - now.tv_usec); if (timeout.tv_usec < 0) { timeout.tv_usec += 1000000L; timeout.tv_sec--; } #else timeout.tv_nsec = (start_time.tv_usec - now.tv_usec) * 1000; if (timeout.tv_nsec < 0) { timeout.tv_nsec += 1000000000L; timeout.tv_sec--; } #endif if (timeout.tv_sec < 0) break; } } /* A child may not have terminated, so force its termination */ #ifdef _WITH_VRRP_ if (vrrp_child) { log_message(LOG_INFO, "vrrp process failed to die - forcing termination"); kill(vrrp_child, SIGKILL); } #endif #ifdef _WITH_LVS_ if (checkers_child) { log_message(LOG_INFO, "checker process failed to die - forcing termination"); kill(checkers_child, SIGKILL); } #endif #ifdef _WITH_BFD_ if (bfd_child) { log_message(LOG_INFO, "bfd process failed to die - forcing termination"); kill(bfd_child, SIGKILL); } #endif #ifndef HAVE_SIGNALFD if (!sigismember(&old_set, SIGCHLD)) sigmask_func(SIG_UNBLOCK, &child_wait, NULL); #endif } #endif /* Initialize signal handler */ static void signal_init(void) { #ifndef _DEBUG_ signal_set(SIGHUP, propagate_signal, NULL); signal_set(SIGUSR1, propagate_signal, NULL); signal_set(SIGUSR2, propagate_signal, NULL); #ifdef _WITH_JSON_ signal_set(SIGJSON, propagate_signal, NULL); #endif signal_set(SIGINT, sigend, NULL); signal_set(SIGTERM, sigend, NULL); #endif signal_ignore(SIGPIPE); } /* To create a core file when abrt is running (a RedHat distribution), * and keepalived isn't installed from an RPM package, edit the file * “/etc/abrt/abrt.conf”, and change the value of the field * “ProcessUnpackaged” to “yes”. * * Alternatively, use the -M command line option. */ static void update_core_dump_pattern(const char *pattern_str) { int fd; bool initialising = (orig_core_dump_pattern == NULL); /* CORENAME_MAX_SIZE in kernel source include/linux/binfmts.h defines * the maximum string length, * see core_pattern[CORENAME_MAX_SIZE] in * fs/coredump.c. Currently (Linux 4.10) defines it to be 128, but the * definition is not exposed to user-space. */ #define CORENAME_MAX_SIZE 128 if (initialising) orig_core_dump_pattern = MALLOC(CORENAME_MAX_SIZE); fd = open ("/proc/sys/kernel/core_pattern", O_RDWR); if (fd == -1 || (initialising && read(fd, orig_core_dump_pattern, CORENAME_MAX_SIZE - 1) == -1) || write(fd, pattern_str, strlen(pattern_str)) == -1) { log_message(LOG_INFO, "Unable to read/write core_pattern"); if (fd != -1) close(fd); FREE(orig_core_dump_pattern); return; } close(fd); if (!initialising) FREE_PTR(orig_core_dump_pattern); } static void core_dump_init(void) { struct rlimit orig_rlim, rlim; if (set_core_dump_pattern) { /* If we set the core_pattern here, we will attempt to restore it when we * exit. This will be fine if it is a child of ours that core dumps, * but if we ourself core dump, then the core_pattern will not be restored */ update_core_dump_pattern(core_dump_pattern); } if (create_core_dump) { rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; if (getrlimit(RLIMIT_CORE, &orig_rlim) == -1) log_message(LOG_INFO, "Failed to get core file size"); else if (setrlimit(RLIMIT_CORE, &rlim) == -1) log_message(LOG_INFO, "Failed to set core file size"); else set_child_rlimit(RLIMIT_CORE, &orig_rlim); } } static mode_t set_umask(const char *optarg) { long umask_long; mode_t umask_val; char *endptr; umask_long = strtoll(optarg, &endptr, 0); if (*endptr || umask_long < 0 || umask_long & ~0777L) { fprintf(stderr, "Invalid --umask option %s", optarg); return; } umask_val = umask_long & 0777; umask(umask_val); umask_cmdline = true; return umask_val; } void initialise_debug_options(void) { #if defined WITH_DEBUG_OPTIONS && !defined _DEBUG_ char mask = 0; if (prog_type == PROG_TYPE_PARENT) mask = 1 << PROG_TYPE_PARENT; #if _WITH_BFD_ else if (prog_type == PROG_TYPE_BFD) mask = 1 << PROG_TYPE_BFD; #endif #if _WITH_LVS_ else if (prog_type == PROG_TYPE_CHECKER) mask = 1 << PROG_TYPE_CHECKER; #endif #if _WITH_VRRP_ else if (prog_type == PROG_TYPE_VRRP) mask = 1 << PROG_TYPE_VRRP; #endif #ifdef _TIMER_CHECK_ do_timer_check = !!(timer_debug & mask); #endif #ifdef _SMTP_ALERT_DEBUG_ do_smtp_alert_debug = !!(smtp_debug & mask); #endif #ifdef _EPOLL_DEBUG_ do_epoll_debug = !!(epoll_debug & mask); #endif #ifdef _EPOLL_THREAD_DUMP_ do_epoll_thread_dump = !!(epoll_thread_debug & mask); #endif #ifdef _REGEX_DEBUG_ do_regex_debug = !!(regex_debug & mask); #endif #ifdef _WITH_REGEX_TIMERS_ do_regex_timers = !!(regex_timers & mask); #endif #ifdef _TSM_DEBUG_ do_tsm_debug = !!(tsm_debug & mask); #endif #ifdef _VRRP_FD_DEBUG_ do_vrrp_fd_debug = !!(vrrp_fd_debug & mask); #endif #ifdef _NETLINK_TIMERS_ do_netlink_timers = !!(netlink_timer_debug & mask); #endif #endif } #ifdef WITH_DEBUG_OPTIONS static void set_debug_options(const char *options) { char all_processes, processes; char opt; const char *opt_p = options; #ifdef _DEBUG_ all_processes = 1; #else all_processes = (1 << PROG_TYPE_PARENT); #if _WITH_BFD_ all_processes |= (1 << PROG_TYPE_BFD); #endif #if _WITH_LVS_ all_processes |= (1 << PROG_TYPE_CHECKER); #endif #if _WITH_VRRP_ all_processes |= (1 << PROG_TYPE_VRRP); #endif #endif if (!options) { #ifdef _TIMER_CHECK_ timer_debug = all_processes; #endif #ifdef _SMTP_ALERT_DEBUG_ smtp_debug = all_processes; #endif #ifdef _EPOLL_DEBUG_ epoll_debug = all_processes; #endif #ifdef _EPOLL_THREAD_DUMP_ epoll_thread_debug = all_processes; #endif #ifdef _REGEX_DEBUG_ regex_debug = all_processes; #endif #ifdef _WITH_REGEX_TIMERS_ regex_timers = all_processes; #endif #ifdef _TSM_DEBUG_ tsm_debug = all_processes; #endif #ifdef _VRRP_FD_DEBUG_ vrrp_fd_debug = all_processes; #endif #ifdef _NETLINK_TIMERS_ netlink_timer_debug = all_processes; #endif return; } opt_p = options; do { if (!isupper(*opt_p)) { fprintf(stderr, "Unknown debug option'%c' in '%s'\n", *opt_p, options); return; } opt = *opt_p++; #ifdef _DEBUG_ processes = all_processes; #else if (!*opt_p || isupper(*opt_p)) processes = all_processes; else { processes = 0; while (*opt_p && !isupper(*opt_p)) { switch (*opt_p) { case 'p': processes |= (1 << PROG_TYPE_PARENT); break; #if _WITH_BFD_ case 'b': processes |= (1 << PROG_TYPE_BFD); break; #endif #if _WITH_LVS_ case 'c': processes |= (1 << PROG_TYPE_CHECKER); break; #endif #if _WITH_VRRP_ case 'v': processes |= (1 << PROG_TYPE_VRRP); break; #endif default: fprintf(stderr, "Unknown debug process '%c' in '%s'\n", *opt_p, options); return; } opt_p++; } } #endif switch (opt) { #ifdef _TIMER_CHECK_ case 'T': timer_debug = processes; break; #endif #ifdef _SMTP_ALERT_DEBUG_ case 'M': smtp_debug = processes; break; #endif #ifdef _EPOLL_DEBUG_ case 'E': epoll_debug = processes; break; #endif #ifdef _EPOLL_THREAD_DUMP_ case 'D': epoll_thread_debug = processes; break; #endif #ifdef _REGEX_DEBUG_ case 'R': regex_debug = processes; break; #endif #ifdef _WITH_REGEX_TIMERS_ case 'X': regex_timers = processes; break; #endif #ifdef _TSM_DEBUG_ case 'S': tsm_debug = processes; break; #endif #ifdef _VRRP_FD_DEBUG_ case 'F': vrrp_fd_debug = processes; break; #endif #ifdef _NETLINK_TIMERS_ case 'N': netlink_timer_debug = processes; break; #endif default: fprintf(stderr, "Unknown debug type '%c' in '%s'\n", opt, options); return; } } while (opt_p && *opt_p); } #endif /* Usage function */ static void usage(const char *prog) { fprintf(stderr, "Usage: %s [OPTION...]\n", prog); fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n"); #if defined _WITH_VRRP_ && defined _WITH_LVS_ fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n"); fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n"); #endif fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n"); fprintf(stderr, " -l, --log-console Log messages to local console\n"); fprintf(stderr, " -D, --log-detail Detailed log messages\n"); fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n"); fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n"); fprintf(stderr, " --flush-log-file Flush log file on write\n"); fprintf(stderr, " -G, --no-syslog Don't log via syslog\n"); fprintf(stderr, " -u, --umask=MASK umask for file creation (in numeric form)\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n"); fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n"); #endif fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n"); fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n"); fprintf(stderr, " -d, --dump-conf Dump the configuration data\n"); fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n"); fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n"); #endif #ifdef _WITH_SNMP_ fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n"); fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n"); #endif #if HAVE_DECL_CLONE_NEWNET fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n"); #endif fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n"); fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n"); #ifdef _MEM_CHECK_LOG_ fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n"); #endif fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n" " or any lines beginning @^ that do match.\n" " The config-id defaults to the node name if option not used\n"); fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS" #ifdef _WITH_JSON_ ", JSON" #endif "\n"); fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n" " stderr by default\n"); #ifdef _WITH_PERF_ fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n"); #endif #ifdef WITH_DEBUG_OPTIONS fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n"); #ifdef _TIMER_CHECK_ fprintf(stderr, " T - timer debug\n"); #endif #ifdef _SMTP_ALERT_DEBUG_ fprintf(stderr, " M - email alert debug\n"); #endif #ifdef _EPOLL_DEBUG_ fprintf(stderr, " E - epoll debug\n"); #endif #ifdef _EPOLL_THREAD_DUMP_ fprintf(stderr, " D - epoll thread dump debug\n"); #endif #ifdef _VRRP_FD_DEBUG fprintf(stderr, " F - vrrp fd dump debug\n"); #endif #ifdef _REGEX_DEBUG_ fprintf(stderr, " R - regex debug\n"); #endif #ifdef _WITH_REGEX_TIMERS_ fprintf(stderr, " X - regex timers\n"); #endif #ifdef _TSM_DEBUG_ fprintf(stderr, " S - TSM debug\n"); #endif #ifdef _NETLINK_TIMERS_ fprintf(stderr, " N - netlink timer debug\n"); #endif fprintf(stderr, " Example --debug=TpMEvcp\n"); #endif fprintf(stderr, " -v, --version Display the version number\n"); fprintf(stderr, " -h, --help Display this help message\n"); } /* Command line parser */ static bool parse_cmdline(int argc, char **argv) { int c; bool reopen_log = false; int signum; struct utsname uname_buf; int longindex; int curind; bool bad_option = false; unsigned facility; mode_t new_umask_val; struct option long_options[] = { {"use-file", required_argument, NULL, 'f'}, #if defined _WITH_VRRP_ && defined _WITH_LVS_ {"vrrp", no_argument, NULL, 'P'}, {"check", no_argument, NULL, 'C'}, #endif #ifdef _WITH_BFD_ {"no_bfd", no_argument, NULL, 'B'}, #endif {"all", no_argument, NULL, 3 }, {"log-console", no_argument, NULL, 'l'}, {"log-detail", no_argument, NULL, 'D'}, {"log-facility", required_argument, NULL, 'S'}, {"log-file", optional_argument, NULL, 'g'}, {"flush-log-file", no_argument, NULL, 2 }, {"no-syslog", no_argument, NULL, 'G'}, {"umask", required_argument, NULL, 'u'}, #ifdef _WITH_VRRP_ {"release-vips", no_argument, NULL, 'X'}, {"dont-release-vrrp", no_argument, NULL, 'V'}, #endif #ifdef _WITH_LVS_ {"dont-release-ipvs", no_argument, NULL, 'I'}, #endif {"dont-respawn", no_argument, NULL, 'R'}, {"dont-fork", no_argument, NULL, 'n'}, {"dump-conf", no_argument, NULL, 'd'}, {"pid", required_argument, NULL, 'p'}, #ifdef _WITH_VRRP_ {"vrrp_pid", required_argument, NULL, 'r'}, #endif #ifdef _WITH_LVS_ {"checkers_pid", required_argument, NULL, 'c'}, {"address-monitoring", no_argument, NULL, 'a'}, #endif #ifdef _WITH_BFD_ {"bfd_pid", required_argument, NULL, 'b'}, #endif #ifdef _WITH_SNMP_ {"snmp", no_argument, NULL, 'x'}, {"snmp-agent-socket", required_argument, NULL, 'A'}, #endif {"core-dump", no_argument, NULL, 'm'}, {"core-dump-pattern", optional_argument, NULL, 'M'}, #ifdef _MEM_CHECK_LOG_ {"mem-check-log", no_argument, NULL, 'L'}, #endif #if HAVE_DECL_CLONE_NEWNET {"namespace", required_argument, NULL, 's'}, #endif {"config-id", required_argument, NULL, 'i'}, {"signum", required_argument, NULL, 4 }, {"config-test", optional_argument, NULL, 't'}, #ifdef _WITH_PERF_ {"perf", optional_argument, NULL, 5 }, #endif #ifdef WITH_DEBUG_OPTIONS {"debug", optional_argument, NULL, 6 }, #endif {"version", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0 } }; /* Unfortunately, if a short option is used, getopt_long() doesn't change the value * of longindex, so we need to ensure that before calling getopt_long(), longindex * is set to a known invalid value */ curind = optind; while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndu:DRS:f:p:i:mM::g::Gt::" #if defined _WITH_VRRP_ && defined _WITH_LVS_ "PC" #endif #ifdef _WITH_VRRP_ "r:VX" #endif #ifdef _WITH_LVS_ "ac:I" #endif #ifdef _WITH_BFD_ "Bb:" #endif #ifdef _WITH_SNMP_ "xA:" #endif #ifdef _MEM_CHECK_LOG_ "L" #endif #if HAVE_DECL_CLONE_NEWNET "s:" #endif , long_options, &longindex)) != -1) { /* Check for an empty option argument. For example --use-file= returns * a 0 length option, which we don't want */ if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) { c = ':'; optarg = NULL; } switch (c) { case 'v': fprintf(stderr, "%s", version_string); #ifdef GIT_COMMIT fprintf(stderr, ", git commit %s", GIT_COMMIT); #endif fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING); fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); uname(&uname_buf); fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version); fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS); fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS); fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS); exit(0); break; case 'h': usage(argv[0]); exit(0); break; case 'l': __set_bit(LOG_CONSOLE_BIT, &debug); reopen_log = true; break; case 'n': __set_bit(DONT_FORK_BIT, &debug); break; case 'd': __set_bit(DUMP_CONF_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'V': __set_bit(DONT_RELEASE_VRRP_BIT, &debug); break; #endif #ifdef _WITH_LVS_ case 'I': __set_bit(DONT_RELEASE_IPVS_BIT, &debug); break; #endif case 'D': if (__test_bit(LOG_DETAIL_BIT, &debug)) __set_bit(LOG_EXTRA_DETAIL_BIT, &debug); else __set_bit(LOG_DETAIL_BIT, &debug); break; case 'R': __set_bit(DONT_RESPAWN_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'X': __set_bit(RELEASE_VIPS_BIT, &debug); break; #endif case 'S': if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false)) fprintf(stderr, "Invalid log facility '%s'\n", optarg); else { log_facility = LOG_FACILITY[facility].facility; reopen_log = true; } break; case 'g': if (optarg && optarg[0]) log_file_name = optarg; else log_file_name = "/tmp/keepalived.log"; open_log_file(log_file_name, NULL, NULL, NULL); break; case 'G': __set_bit(NO_SYSLOG_BIT, &debug); reopen_log = true; break; case 'u': new_umask_val = set_umask(optarg); if (umask_cmdline) umask_val = new_umask_val; break; case 't': __set_bit(CONFIG_TEST_BIT, &debug); __set_bit(DONT_RESPAWN_BIT, &debug); __set_bit(DONT_FORK_BIT, &debug); __set_bit(NO_SYSLOG_BIT, &debug); if (optarg && optarg[0]) { int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { fprintf(stderr, "Unable to open config-test log file %s\n", optarg); exit(EXIT_FAILURE); } dup2(fd, STDERR_FILENO); close(fd); } break; case 'f': conf_file = optarg; break; case 2: /* --flush-log-file */ set_flush_log_file(); break; #if defined _WITH_VRRP_ && defined _WITH_LVS_ case 'P': __clear_bit(DAEMON_CHECKERS, &daemon_mode); break; case 'C': __clear_bit(DAEMON_VRRP, &daemon_mode); break; #endif #ifdef _WITH_BFD_ case 'B': __clear_bit(DAEMON_BFD, &daemon_mode); break; #endif case 'p': main_pidfile = optarg; break; #ifdef _WITH_LVS_ case 'c': checkers_pidfile = optarg; break; case 'a': __set_bit(LOG_ADDRESS_CHANGES, &debug); break; #endif #ifdef _WITH_VRRP_ case 'r': vrrp_pidfile = optarg; break; #endif #ifdef _WITH_BFD_ case 'b': bfd_pidfile = optarg; break; #endif #ifdef _WITH_SNMP_ case 'x': snmp = 1; break; case 'A': snmp_socket = optarg; break; #endif case 'M': set_core_dump_pattern = true; if (optarg && optarg[0]) core_dump_pattern = optarg; /* ... falls through ... */ case 'm': create_core_dump = true; break; #ifdef _MEM_CHECK_LOG_ case 'L': __set_bit(MEM_CHECK_LOG_BIT, &debug); break; #endif #if HAVE_DECL_CLONE_NEWNET case 's': override_namespace = MALLOC(strlen(optarg) + 1); strcpy(override_namespace, optarg); break; #endif case 'i': FREE_PTR(config_id); config_id = MALLOC(strlen(optarg) + 1); strcpy(config_id, optarg); break; case 4: /* --signum */ signum = get_signum(optarg); if (signum == -1) { fprintf(stderr, "Unknown sigfunc %s\n", optarg); exit(1); } printf("%d\n", signum); exit(0); break; case 3: /* --all */ __set_bit(RUN_ALL_CHILDREN, &daemon_mode); #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif break; #ifdef _WITH_PERF_ case 5: if (optarg && optarg[0]) { if (!strcmp(optarg, "run")) perf_run = PERF_RUN; else if (!strcmp(optarg, "all")) perf_run = PERF_ALL; else if (!strcmp(optarg, "end")) perf_run = PERF_END; else log_message(LOG_INFO, "Unknown perf start point %s", optarg); } else perf_run = PERF_RUN; break; #endif #ifdef WITH_DEBUG_OPTIONS case 6: set_debug_options(optarg && optarg[0] ? optarg : NULL); break; #endif case '?': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Unknown option -%c\n", optopt); else fprintf(stderr, "Unknown option %s\n", argv[curind]); bad_option = true; break; case ':': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Missing parameter for option -%c\n", optopt); else fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name); bad_option = true; break; default: exit(1); break; } curind = optind; } if (optind < argc) { printf("Unexpected argument(s): "); while (optind < argc) printf("%s ", argv[optind++]); printf("\n"); } if (bad_option) exit(1); return reopen_log; } #ifdef THREAD_DUMP static void register_parent_thread_addresses(void) { register_scheduler_addresses(); register_signal_thread_addresses(); #ifdef _WITH_LVS_ register_check_parent_addresses(); #endif #ifdef _WITH_VRRP_ register_vrrp_parent_addresses(); #endif #ifdef _WITH_BFD_ register_bfd_parent_addresses(); #endif #ifndef _DEBUG_ register_signal_handler_address("propagate_signal", propagate_signal); register_signal_handler_address("sigend", sigend); #endif register_signal_handler_address("thread_child_handler", thread_child_handler); } #endif /* Entry point */ int keepalived_main(int argc, char **argv) { bool report_stopped = true; struct utsname uname_buf; char *end; /* Ensure time_now is set. We then don't have to check anywhere * else if it is set. */ set_time_now(); /* Save command line options in case need to log them later */ save_cmd_line_options(argc, argv); /* Init debugging level */ debug = 0; /* We are the parent process */ #ifndef _DEBUG_ prog_type = PROG_TYPE_PARENT; #endif /* Initialise daemon_mode */ #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif /* Set default file creation mask */ umask(022); /* Open log with default settings so we can log initially */ openlog(PACKAGE_NAME, LOG_PID, log_facility); #ifdef _MEM_CHECK_ mem_log_init(PACKAGE_NAME, "Parent process"); #endif /* Some functionality depends on kernel version, so get the version here */ if (uname(&uname_buf)) log_message(LOG_INFO, "Unable to get uname() information - error %d", errno); else { os_major = (unsigned)strtoul(uname_buf.release, &end, 10); if (*end != '.') os_major = 0; else { os_minor = (unsigned)strtoul(end + 1, &end, 10); if (*end != '.') os_major = 0; else { if (!isdigit(end[1])) os_major = 0; else os_release = (unsigned)strtoul(end + 1, &end, 10); } } if (!os_major) log_message(LOG_INFO, "Unable to parse kernel version %s", uname_buf.release); /* config_id defaults to hostname */ if (!config_id) { end = strchrnul(uname_buf.nodename, '.'); config_id = MALLOC((size_t)(end - uname_buf.nodename) + 1); strncpy(config_id, uname_buf.nodename, (size_t)(end - uname_buf.nodename)); config_id[end - uname_buf.nodename] = '\0'; } } /* * Parse command line and set debug level. * bits 0..7 reserved by main.c */ if (parse_cmdline(argc, argv)) { closelog(); if (!__test_bit(NO_SYSLOG_BIT, &debug)) openlog(PACKAGE_NAME, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , log_facility); } if (__test_bit(LOG_CONSOLE_BIT, &debug)) enable_console_log(); #ifdef GIT_COMMIT log_message(LOG_INFO, "Starting %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Starting %s", version_string); #endif /* Handle any core file requirements */ core_dump_init(); if (os_major) { if (KERNEL_VERSION(os_major, os_minor, os_release) < LINUX_VERSION_CODE) { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "WARNING - keepalived was build for newer Linux %d.%d.%d, running on %s %s %s", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff, uname_buf.sysname, uname_buf.release, uname_buf.version); } else { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "Running on %s %s %s (built for Linux %d.%d.%d)", uname_buf.sysname, uname_buf.release, uname_buf.version, (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); } } #ifndef _DEBUG_ log_command_line(0); #endif /* Check we can read the configuration file(s). NOTE: the working directory will be / if we forked, but will be the current working directory when keepalived was run if we haven't forked. This means that if any config file names are not absolute file names, the behaviour will be different depending on whether we forked or not. */ if (!check_conf_file(conf_file)) { if (__test_bit(CONFIG_TEST_BIT, &debug)) config_test_exit(); goto end; } global_data = alloc_global_data(); global_data->umask = umask_val; read_config_file(); init_global_data(global_data, NULL); #if HAVE_DECL_CLONE_NEWNET if (override_namespace) { if (global_data->network_namespace) { log_message(LOG_INFO, "Overriding config net_namespace '%s' with command line namespace '%s'", global_data->network_namespace, override_namespace); FREE(global_data->network_namespace); } global_data->network_namespace = override_namespace; override_namespace = NULL; } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug) && (global_data->instance_name #if HAVE_DECL_CLONE_NEWNET || global_data->network_namespace #endif )) { if ((syslog_ident = make_syslog_ident(PACKAGE_NAME))) { log_message(LOG_INFO, "Changing syslog ident to %s", syslog_ident); closelog(); openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0), log_facility); } else log_message(LOG_INFO, "Unable to change syslog ident"); use_pid_dir = true; open_log_file(log_file_name, NULL, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); } /* Initialise pointer to child finding function */ set_child_finder_name(find_keepalived_child_name); if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (use_pid_dir) { /* Create the directory for pid files */ create_pid_dir(); } } #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { if (global_data->network_namespace && !set_namespaces(global_data->network_namespace)) { log_message(LOG_ERR, "Unable to set network namespace %s - exiting", global_data->network_namespace); goto end; } } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (global_data->instance_name) { if (!main_pidfile && (main_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_main_pidfile = true; #ifdef _WITH_LVS_ if (!checkers_pidfile && (checkers_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR CHECKERS_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_checkers_pidfile = true; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile && (vrrp_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_vrrp_pidfile = true; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile && (bfd_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_bfd_pidfile = true; #endif } if (use_pid_dir) { if (!main_pidfile) main_pidfile = KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = KEEPALIVED_PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = KEEPALIVED_PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = KEEPALIVED_PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } else { if (!main_pidfile) main_pidfile = PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } /* Check if keepalived is already running */ if (keepalived_running(daemon_mode)) { log_message(LOG_INFO, "daemon is already running"); report_stopped = false; goto end; } } /* daemonize process */ if (!__test_bit(DONT_FORK_BIT, &debug) && xdaemon(false, false, true) > 0) { closelog(); FREE_PTR(config_id); FREE_PTR(orig_core_dump_pattern); close_std_fd(); exit(0); } #ifdef _MEM_CHECK_ enable_mem_log_termination(); #endif if (__test_bit(CONFIG_TEST_BIT, &debug)) { validate_config(); config_test_exit(); } /* write the father's pidfile */ if (!pidfile_write(main_pidfile, getpid())) goto end; /* Create the master thread */ master = thread_make_master(); /* Signal handling initialization */ signal_init(); /* Init daemon */ if (!start_keepalived()) log_message(LOG_INFO, "Warning - keepalived has no configuration to run"); initialise_debug_options(); #ifdef THREAD_DUMP register_parent_thread_addresses(); #endif /* Launch the scheduling I/O multiplexer */ launch_thread_scheduler(master); /* Finish daemon process */ stop_keepalived(); #ifdef THREAD_DUMP deregister_thread_addresses(); #endif /* * Reached when terminate signal catched. * finally return from system */ end: if (report_stopped) { #ifdef GIT_COMMIT log_message(LOG_INFO, "Stopped %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Stopped %s", version_string); #endif } #if HAVE_DECL_CLONE_NEWNET if (global_data && global_data->network_namespace) clear_namespaces(); #endif if (use_pid_dir) remove_pid_dir(); /* Restore original core_pattern if necessary */ if (orig_core_dump_pattern) update_core_dump_pattern(orig_core_dump_pattern); free_parent_mallocs_startup(false); free_parent_mallocs_exit(); free_global_data(global_data); closelog(); #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else if (syslog_ident) free(syslog_ident); #endif close_std_fd(); exit(KEEPALIVED_EXIT_OK); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_437_0
crossvul-cpp_data_bad_438_5
/* * Soft: Keepalived is a failover program for the LVS project * <www.linuxvirtualserver.org>. It monitor & manipulate * a loadbalanced server pool using multi-layer checks. * * Part: Main program structure. * * Author: Alexandre Cassen, <acassen@linux-vs.org> * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Copyright (C) 2001-2017 Alexandre Cassen, <acassen@gmail.com> */ #include "config.h" #include <stdlib.h> #include <sys/utsname.h> #include <sys/resource.h> #include <stdbool.h> #ifdef HAVE_SIGNALFD #include <sys/signalfd.h> #endif #include <errno.h> #include <signal.h> #include <fcntl.h> #include <sys/wait.h> #include <sys/stat.h> #include <unistd.h> #include <getopt.h> #include <linux/version.h> #include <ctype.h> #include "main.h" #include "global_data.h" #include "daemon.h" #include "config.h" #include "git-commit.h" #include "utils.h" #include "signals.h" #include "pidfile.h" #include "bitops.h" #include "logger.h" #include "parser.h" #include "notify.h" #include "utils.h" #ifdef _WITH_LVS_ #include "check_parser.h" #include "check_daemon.h" #endif #ifdef _WITH_VRRP_ #include "vrrp_daemon.h" #include "vrrp_parser.h" #include "vrrp_if.h" #ifdef _WITH_JSON_ #include "vrrp_json.h" #endif #endif #ifdef _WITH_BFD_ #include "bfd_daemon.h" #include "bfd_parser.h" #endif #include "global_parser.h" #if HAVE_DECL_CLONE_NEWNET #include "namespaces.h" #endif #include "scheduler.h" #include "keepalived_netlink.h" #include "git-commit.h" #if defined THREAD_DUMP || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ #include "scheduler.h" #endif #include "process.h" #ifdef _TIMER_CHECK_ #include "timer.h" #endif #ifdef _SMTP_ALERT_DEBUG_ #include "smtp.h" #endif #if defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ #include "check_http.h" #endif #ifdef _TSM_DEBUG_ #include "vrrp_scheduler.h" #endif /* musl libc doesn't define the following */ #ifndef W_EXITCODE #define W_EXITCODE(ret, sig) ((ret) << 8 | (sig)) #endif #ifndef WCOREFLAG #define WCOREFLAG ((int32_t)WCOREDUMP(0xffffffff)) #endif #define VERSION_STRING PACKAGE_NAME " v" PACKAGE_VERSION " (" GIT_DATE ")" #define COPYRIGHT_STRING "Copyright(C) 2001-" GIT_YEAR " Alexandre Cassen, <acassen@gmail.com>" #define CHILD_WAIT_SECS 5 /* global var */ const char *version_string = VERSION_STRING; /* keepalived version */ char *conf_file = KEEPALIVED_CONFIG_FILE; /* Configuration file */ int log_facility = LOG_DAEMON; /* Optional logging facilities */ bool reload; /* Set during a reload */ char *main_pidfile; /* overrule default pidfile */ static bool free_main_pidfile; #ifdef _WITH_LVS_ pid_t checkers_child; /* Healthcheckers child process ID */ char *checkers_pidfile; /* overrule default pidfile */ static bool free_checkers_pidfile; #endif #ifdef _WITH_VRRP_ pid_t vrrp_child; /* VRRP child process ID */ char *vrrp_pidfile; /* overrule default pidfile */ static bool free_vrrp_pidfile; #endif #ifdef _WITH_BFD_ pid_t bfd_child; /* BFD child process ID */ char *bfd_pidfile; /* overrule default pidfile */ static bool free_bfd_pidfile; #endif unsigned long daemon_mode; /* VRRP/CHECK/BFD subsystem selection */ #ifdef _WITH_SNMP_ bool snmp; /* Enable SNMP support */ const char *snmp_socket; /* Socket to use for SNMP agent */ #endif static char *syslog_ident; /* syslog ident if not default */ bool use_pid_dir; /* Put pid files in /var/run/keepalived or @localstatedir@/run/keepalived */ unsigned os_major; /* Kernel version */ unsigned os_minor; unsigned os_release; char *hostname; /* Initial part of hostname */ #if HAVE_DECL_CLONE_NEWNET static char *override_namespace; /* If namespace specified on command line */ #endif unsigned child_wait_time = CHILD_WAIT_SECS; /* Time to wait for children to exit */ /* Log facility table */ static struct { int facility; } LOG_FACILITY[] = { {LOG_LOCAL0}, {LOG_LOCAL1}, {LOG_LOCAL2}, {LOG_LOCAL3}, {LOG_LOCAL4}, {LOG_LOCAL5}, {LOG_LOCAL6}, {LOG_LOCAL7} }; #define LOG_FACILITY_MAX ((sizeof(LOG_FACILITY) / sizeof(LOG_FACILITY[0])) - 1) /* Control producing core dumps */ static bool set_core_dump_pattern = false; static bool create_core_dump = false; static const char *core_dump_pattern = "core"; static char *orig_core_dump_pattern = NULL; /* debug flags */ #if defined _TIMER_CHECK_ || defined _SMTP_ALERT_DEBUG_ || defined _EPOLL_DEBUG_ || defined _EPOLL_THREAD_DUMP_ || defined _REGEX_DEBUG_ || defined _WITH_REGEX_TIMERS_ || defined _TSM_DEBUG_ || defined _VRRP_FD_DEBUG_ || defined _NETLINK_TIMERS_ #define WITH_DEBUG_OPTIONS 1 #endif #ifdef _TIMER_CHECK_ static char timer_debug; #endif #ifdef _SMTP_ALERT_DEBUG_ static char smtp_debug; #endif #ifdef _EPOLL_DEBUG_ static char epoll_debug; #endif #ifdef _EPOLL_THREAD_DUMP_ static char epoll_thread_debug; #endif #ifdef _REGEX_DEBUG_ static char regex_debug; #endif #ifdef _WITH_REGEX_TIMERS_ static char regex_timers; #endif #ifdef _TSM_DEBUG_ static char tsm_debug; #endif #ifdef _VRRP_FD_DEBUG_ static char vrrp_fd_debug; #endif #ifdef _NETLINK_TIMERS_ static char netlink_timer_debug; #endif void free_parent_mallocs_startup(bool am_child) { if (am_child) { #if HAVE_DECL_CLONE_NEWNET free_dirname(); #endif #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else free(syslog_ident); #endif syslog_ident = NULL; FREE_PTR(orig_core_dump_pattern); } if (free_main_pidfile) { FREE_PTR(main_pidfile); free_main_pidfile = false; } } void free_parent_mallocs_exit(void) { #ifdef _WITH_VRRP_ if (free_vrrp_pidfile) FREE_PTR(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (free_checkers_pidfile) FREE_PTR(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (free_bfd_pidfile) FREE_PTR(bfd_pidfile); #endif FREE_PTR(config_id); } char * make_syslog_ident(const char* name) { size_t ident_len = strlen(name) + 1; char *ident; #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) ident_len += strlen(global_data->network_namespace) + 1; #endif if (global_data->instance_name) ident_len += strlen(global_data->instance_name) + 1; /* If we are writing MALLOC/FREE info to the log, we have * trouble FREEing the syslog_ident */ #ifndef _MEM_CHECK_LOG_ ident = MALLOC(ident_len); #else ident = malloc(ident_len); #endif if (!ident) return NULL; strcpy(ident, name); #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { strcat(ident, "_"); strcat(ident, global_data->network_namespace); } #endif if (global_data->instance_name) { strcat(ident, "_"); strcat(ident, global_data->instance_name); } return ident; } static char * make_pidfile_name(const char* start, const char* instance, const char* extn) { size_t len; char *name; len = strlen(start) + 1; if (instance) len += strlen(instance) + 1; if (extn) len += strlen(extn); name = MALLOC(len); if (!name) { log_message(LOG_INFO, "Unable to make pidfile name for %s", start); return NULL; } strcpy(name, start); if (instance) { strcat(name, "_"); strcat(name, instance); } if (extn) strcat(name, extn); return name; } #ifdef _WITH_VRRP_ bool running_vrrp(void) { return (__test_bit(DAEMON_VRRP, &daemon_mode) && (global_data->have_vrrp_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_LVS_ bool running_checker(void) { return (__test_bit(DAEMON_CHECKERS, &daemon_mode) && (global_data->have_checker_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif #ifdef _WITH_BFD_ bool running_bfd(void) { return (__test_bit(DAEMON_BFD, &daemon_mode) && (global_data->have_bfd_config || __test_bit(RUN_ALL_CHILDREN, &daemon_mode))); } #endif static char const * find_keepalived_child_name(pid_t pid) { #ifdef _WITH_LVS_ if (pid == checkers_child) return PROG_CHECK; #endif #ifdef _WITH_VRRP_ if (pid == vrrp_child) return PROG_VRRP; #endif #ifdef _WITH_BFD_ if (pid == bfd_child) return PROG_BFD; #endif return NULL; } static vector_t * global_init_keywords(void) { /* global definitions mapping */ init_global_keywords(true); #ifdef _WITH_VRRP_ init_vrrp_keywords(false); #endif #ifdef _WITH_LVS_ init_check_keywords(false); #endif #ifdef _WITH_BFD_ init_bfd_keywords(false); #endif return keywords; } static void read_config_file(void) { init_data(conf_file, global_init_keywords); } /* Daemon stop sequence */ void stop_keepalived(void) { #ifndef _DEBUG_ /* Just cleanup memory & exit */ thread_destroy_master(master); #ifdef _WITH_VRRP_ if (__test_bit(DAEMON_VRRP, &daemon_mode)) pidfile_rm(vrrp_pidfile); #endif #ifdef _WITH_LVS_ if (__test_bit(DAEMON_CHECKERS, &daemon_mode)) pidfile_rm(checkers_pidfile); #endif #ifdef _WITH_BFD_ if (__test_bit(DAEMON_BFD, &daemon_mode)) pidfile_rm(bfd_pidfile); #endif pidfile_rm(main_pidfile); #endif } /* Daemon init sequence */ static int start_keepalived(void) { bool have_child = false; #ifdef _WITH_BFD_ /* must be opened before vrrp and bfd start */ open_bfd_pipes(); #endif #ifdef _WITH_LVS_ /* start healthchecker child */ if (running_checker()) { start_check_child(); have_child = true; } #endif #ifdef _WITH_VRRP_ /* start vrrp child */ if (running_vrrp()) { start_vrrp_child(); have_child = true; } #endif #ifdef _WITH_BFD_ /* start bfd child */ if (running_bfd()) { start_bfd_child(); have_child = true; } #endif return have_child; } static void validate_config(void) { #ifdef _WITH_VRRP_ kernel_netlink_read_interfaces(); #endif #ifdef _WITH_LVS_ /* validate healthchecker config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_CHECKER; #endif check_validate_config(); #endif #ifdef _WITH_VRRP_ /* validate vrrp config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_VRRP; #endif vrrp_validate_config(); #endif #ifdef _WITH_BFD_ /* validate bfd config */ #ifndef _DEBUG_ prog_type = PROG_TYPE_BFD; #endif bfd_validate_config(); #endif } static void config_test_exit(void) { config_err_t config_err = get_config_status(); switch (config_err) { case CONFIG_OK: exit(KEEPALIVED_EXIT_OK); case CONFIG_FILE_NOT_FOUND: case CONFIG_BAD_IF: case CONFIG_FATAL: exit(KEEPALIVED_EXIT_CONFIG); case CONFIG_SECURITY_ERROR: exit(KEEPALIVED_EXIT_CONFIG_TEST_SECURITY); default: exit(KEEPALIVED_EXIT_CONFIG_TEST); } } #ifndef _DEBUG_ static bool reload_config(void) { bool unsupported_change = false; log_message(LOG_INFO, "Reloading ..."); /* Make sure there isn't an attempt to change the network namespace or instance name */ old_global_data = global_data; global_data = NULL; global_data = alloc_global_data(); read_config_file(); init_global_data(global_data, old_global_data); #if HAVE_DECL_CLONE_NEWNET if (!!old_global_data->network_namespace != !!global_data->network_namespace || (global_data->network_namespace && strcmp(old_global_data->network_namespace, global_data->network_namespace))) { log_message(LOG_INFO, "Cannot change network namespace at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->network_namespace); global_data->network_namespace = old_global_data->network_namespace; old_global_data->network_namespace = NULL; #endif if (!!old_global_data->instance_name != !!global_data->instance_name || (global_data->instance_name && strcmp(old_global_data->instance_name, global_data->instance_name))) { log_message(LOG_INFO, "Cannot change instance name at a reload - please restart %s", PACKAGE); unsupported_change = true; } FREE_PTR(global_data->instance_name); global_data->instance_name = old_global_data->instance_name; old_global_data->instance_name = NULL; if (unsupported_change) { /* We cannot reload the configuration, so continue with the old config */ free_global_data (global_data); global_data = old_global_data; } else free_global_data (old_global_data); return !unsupported_change; } /* SIGHUP/USR1/USR2 handler */ static void propagate_signal(__attribute__((unused)) void *v, int sig) { if (sig == SIGHUP) { if (!reload_config()) return; } /* Signal child processes */ #ifdef _WITH_VRRP_ if (vrrp_child > 0) kill(vrrp_child, sig); else if (sig == SIGHUP && running_vrrp()) start_vrrp_child(); #endif #ifdef _WITH_LVS_ if (sig == SIGHUP) { if (checkers_child > 0) kill(checkers_child, sig); else if (running_checker()) start_check_child(); } #endif #ifdef _WITH_BFD_ if (sig == SIGHUP) { if (bfd_child > 0) kill(bfd_child, sig); else if (running_bfd()) start_bfd_child(); } #endif } /* Terminate handler */ static void sigend(__attribute__((unused)) void *v, __attribute__((unused)) int sig) { int status; int ret; int wait_count = 0; struct timeval start_time, now; #ifdef HAVE_SIGNALFD struct timeval timeout = { .tv_sec = child_wait_time, .tv_usec = 0 }; int signal_fd = master->signal_fd; fd_set read_set; struct signalfd_siginfo siginfo; sigset_t sigmask; #else sigset_t old_set, child_wait; struct timespec timeout = { .tv_sec = child_wait_time, .tv_nsec = 0 }; #endif /* register the terminate thread */ thread_add_terminate_event(master); log_message(LOG_INFO, "Stopping"); #ifdef HAVE_SIGNALFD /* We only want to receive SIGCHLD now */ sigemptyset(&sigmask); sigaddset(&sigmask, SIGCHLD); signalfd(signal_fd, &sigmask, 0); FD_ZERO(&read_set); #else sigmask_func(0, NULL, &old_set); if (!sigismember(&old_set, SIGCHLD)) { sigemptyset(&child_wait); sigaddset(&child_wait, SIGCHLD); sigmask_func(SIG_BLOCK, &child_wait, NULL); } #endif #ifdef _WITH_VRRP_ if (vrrp_child > 0) { if (kill(vrrp_child, SIGTERM)) { /* ESRCH means no such process */ if (errno == ESRCH) vrrp_child = 0; } else wait_count++; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0) { if (kill(checkers_child, SIGTERM)) { if (errno == ESRCH) checkers_child = 0; } else wait_count++; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0) { if (kill(bfd_child, SIGTERM)) { if (errno == ESRCH) bfd_child = 0; } else wait_count++; } #endif gettimeofday(&start_time, NULL); while (wait_count) { #ifdef HAVE_SIGNALFD FD_SET(signal_fd, &read_set); ret = select(signal_fd + 1, &read_set, NULL, NULL, &timeout); if (ret == 0) break; if (ret == -1) { if (errno == EINTR) continue; log_message(LOG_INFO, "Terminating select returned errno %d", errno); break; } if (!FD_ISSET(signal_fd, &read_set)) { log_message(LOG_INFO, "Terminating select did not return select_fd"); continue; } if (read(signal_fd, &siginfo, sizeof(siginfo)) != sizeof(siginfo)) { log_message(LOG_INFO, "Terminating signal read did not read entire siginfo"); break; } status = siginfo.ssi_code == CLD_EXITED ? W_EXITCODE(siginfo.ssi_status, 0) : siginfo.ssi_code == CLD_KILLED ? W_EXITCODE(0, siginfo.ssi_status) : WCOREFLAG; #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == (pid_t)siginfo.ssi_pid) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #else ret = sigtimedwait(&child_wait, NULL, &timeout); if (ret == -1) { if (errno == EINTR) continue; if (errno == EAGAIN) break; } #ifdef _WITH_VRRP_ if (vrrp_child > 0 && vrrp_child == waitpid(vrrp_child, &status, WNOHANG)) { report_child_status(status, vrrp_child, PROG_VRRP); vrrp_child = 0; wait_count--; } #endif #ifdef _WITH_LVS_ if (checkers_child > 0 && checkers_child == waitpid(checkers_child, &status, WNOHANG)) { report_child_status(status, checkers_child, PROG_CHECK); checkers_child = 0; wait_count--; } #endif #ifdef _WITH_BFD_ if (bfd_child > 0 && bfd_child == waitpid(bfd_child, &status, WNOHANG)) { report_child_status(status, bfd_child, PROG_BFD); bfd_child = 0; wait_count--; } #endif #endif if (wait_count) { gettimeofday(&now, NULL); timeout.tv_sec = child_wait_time - (now.tv_sec - start_time.tv_sec); #ifdef HAVE_SIGNALFD timeout.tv_usec = (start_time.tv_usec - now.tv_usec); if (timeout.tv_usec < 0) { timeout.tv_usec += 1000000L; timeout.tv_sec--; } #else timeout.tv_nsec = (start_time.tv_usec - now.tv_usec) * 1000; if (timeout.tv_nsec < 0) { timeout.tv_nsec += 1000000000L; timeout.tv_sec--; } #endif if (timeout.tv_sec < 0) break; } } /* A child may not have terminated, so force its termination */ #ifdef _WITH_VRRP_ if (vrrp_child) { log_message(LOG_INFO, "vrrp process failed to die - forcing termination"); kill(vrrp_child, SIGKILL); } #endif #ifdef _WITH_LVS_ if (checkers_child) { log_message(LOG_INFO, "checker process failed to die - forcing termination"); kill(checkers_child, SIGKILL); } #endif #ifdef _WITH_BFD_ if (bfd_child) { log_message(LOG_INFO, "bfd process failed to die - forcing termination"); kill(bfd_child, SIGKILL); } #endif #ifndef HAVE_SIGNALFD if (!sigismember(&old_set, SIGCHLD)) sigmask_func(SIG_UNBLOCK, &child_wait, NULL); #endif } #endif /* Initialize signal handler */ static void signal_init(void) { #ifndef _DEBUG_ signal_set(SIGHUP, propagate_signal, NULL); signal_set(SIGUSR1, propagate_signal, NULL); signal_set(SIGUSR2, propagate_signal, NULL); #ifdef _WITH_JSON_ signal_set(SIGJSON, propagate_signal, NULL); #endif signal_set(SIGINT, sigend, NULL); signal_set(SIGTERM, sigend, NULL); #endif signal_ignore(SIGPIPE); } /* To create a core file when abrt is running (a RedHat distribution), * and keepalived isn't installed from an RPM package, edit the file * “/etc/abrt/abrt.conf”, and change the value of the field * “ProcessUnpackaged” to “yes”. * * Alternatively, use the -M command line option. */ static void update_core_dump_pattern(const char *pattern_str) { int fd; bool initialising = (orig_core_dump_pattern == NULL); /* CORENAME_MAX_SIZE in kernel source include/linux/binfmts.h defines * the maximum string length, * see core_pattern[CORENAME_MAX_SIZE] in * fs/coredump.c. Currently (Linux 4.10) defines it to be 128, but the * definition is not exposed to user-space. */ #define CORENAME_MAX_SIZE 128 if (initialising) orig_core_dump_pattern = MALLOC(CORENAME_MAX_SIZE); fd = open ("/proc/sys/kernel/core_pattern", O_RDWR); if (fd == -1 || (initialising && read(fd, orig_core_dump_pattern, CORENAME_MAX_SIZE - 1) == -1) || write(fd, pattern_str, strlen(pattern_str)) == -1) { log_message(LOG_INFO, "Unable to read/write core_pattern"); if (fd != -1) close(fd); FREE(orig_core_dump_pattern); return; } close(fd); if (!initialising) FREE_PTR(orig_core_dump_pattern); } static void core_dump_init(void) { struct rlimit orig_rlim, rlim; if (set_core_dump_pattern) { /* If we set the core_pattern here, we will attempt to restore it when we * exit. This will be fine if it is a child of ours that core dumps, * but if we ourself core dump, then the core_pattern will not be restored */ update_core_dump_pattern(core_dump_pattern); } if (create_core_dump) { rlim.rlim_cur = RLIM_INFINITY; rlim.rlim_max = RLIM_INFINITY; if (getrlimit(RLIMIT_CORE, &orig_rlim) == -1) log_message(LOG_INFO, "Failed to get core file size"); else if (setrlimit(RLIMIT_CORE, &rlim) == -1) log_message(LOG_INFO, "Failed to set core file size"); else set_child_rlimit(RLIMIT_CORE, &orig_rlim); } } void initialise_debug_options(void) { #if defined WITH_DEBUG_OPTIONS && !defined _DEBUG_ char mask = 0; if (prog_type == PROG_TYPE_PARENT) mask = 1 << PROG_TYPE_PARENT; #if _WITH_BFD_ else if (prog_type == PROG_TYPE_BFD) mask = 1 << PROG_TYPE_BFD; #endif #if _WITH_LVS_ else if (prog_type == PROG_TYPE_CHECKER) mask = 1 << PROG_TYPE_CHECKER; #endif #if _WITH_VRRP_ else if (prog_type == PROG_TYPE_VRRP) mask = 1 << PROG_TYPE_VRRP; #endif #ifdef _TIMER_CHECK_ do_timer_check = !!(timer_debug & mask); #endif #ifdef _SMTP_ALERT_DEBUG_ do_smtp_alert_debug = !!(smtp_debug & mask); #endif #ifdef _EPOLL_DEBUG_ do_epoll_debug = !!(epoll_debug & mask); #endif #ifdef _EPOLL_THREAD_DUMP_ do_epoll_thread_dump = !!(epoll_thread_debug & mask); #endif #ifdef _REGEX_DEBUG_ do_regex_debug = !!(regex_debug & mask); #endif #ifdef _WITH_REGEX_TIMERS_ do_regex_timers = !!(regex_timers & mask); #endif #ifdef _TSM_DEBUG_ do_tsm_debug = !!(tsm_debug & mask); #endif #ifdef _VRRP_FD_DEBUG_ do_vrrp_fd_debug = !!(vrrp_fd_debug & mask); #endif #ifdef _NETLINK_TIMERS_ do_netlink_timers = !!(netlink_timer_debug & mask); #endif #endif } #ifdef WITH_DEBUG_OPTIONS static void set_debug_options(const char *options) { char all_processes, processes; char opt; const char *opt_p = options; #ifdef _DEBUG_ all_processes = 1; #else all_processes = (1 << PROG_TYPE_PARENT); #if _WITH_BFD_ all_processes |= (1 << PROG_TYPE_BFD); #endif #if _WITH_LVS_ all_processes |= (1 << PROG_TYPE_CHECKER); #endif #if _WITH_VRRP_ all_processes |= (1 << PROG_TYPE_VRRP); #endif #endif if (!options) { #ifdef _TIMER_CHECK_ timer_debug = all_processes; #endif #ifdef _SMTP_ALERT_DEBUG_ smtp_debug = all_processes; #endif #ifdef _EPOLL_DEBUG_ epoll_debug = all_processes; #endif #ifdef _EPOLL_THREAD_DUMP_ epoll_thread_debug = all_processes; #endif #ifdef _REGEX_DEBUG_ regex_debug = all_processes; #endif #ifdef _WITH_REGEX_TIMERS_ regex_timers = all_processes; #endif #ifdef _TSM_DEBUG_ tsm_debug = all_processes; #endif #ifdef _VRRP_FD_DEBUG_ vrrp_fd_debug = all_processes; #endif #ifdef _NETLINK_TIMERS_ netlink_timer_debug = all_processes; #endif return; } opt_p = options; do { if (!isupper(*opt_p)) { fprintf(stderr, "Unknown debug option'%c' in '%s'\n", *opt_p, options); return; } opt = *opt_p++; #ifdef _DEBUG_ processes = all_processes; #else if (!*opt_p || isupper(*opt_p)) processes = all_processes; else { processes = 0; while (*opt_p && !isupper(*opt_p)) { switch (*opt_p) { case 'p': processes |= (1 << PROG_TYPE_PARENT); break; #if _WITH_BFD_ case 'b': processes |= (1 << PROG_TYPE_BFD); break; #endif #if _WITH_LVS_ case 'c': processes |= (1 << PROG_TYPE_CHECKER); break; #endif #if _WITH_VRRP_ case 'v': processes |= (1 << PROG_TYPE_VRRP); break; #endif default: fprintf(stderr, "Unknown debug process '%c' in '%s'\n", *opt_p, options); return; } opt_p++; } } #endif switch (opt) { #ifdef _TIMER_CHECK_ case 'T': timer_debug = processes; break; #endif #ifdef _SMTP_ALERT_DEBUG_ case 'M': smtp_debug = processes; break; #endif #ifdef _EPOLL_DEBUG_ case 'E': epoll_debug = processes; break; #endif #ifdef _EPOLL_THREAD_DUMP_ case 'D': epoll_thread_debug = processes; break; #endif #ifdef _REGEX_DEBUG_ case 'R': regex_debug = processes; break; #endif #ifdef _WITH_REGEX_TIMERS_ case 'X': regex_timers = processes; break; #endif #ifdef _TSM_DEBUG_ case 'S': tsm_debug = processes; break; #endif #ifdef _VRRP_FD_DEBUG_ case 'F': vrrp_fd_debug = processes; break; #endif #ifdef _NETLINK_TIMERS_ case 'N': netlink_timer_debug = processes; break; #endif default: fprintf(stderr, "Unknown debug type '%c' in '%s'\n", opt, options); return; } } while (opt_p && *opt_p); } #endif /* Usage function */ static void usage(const char *prog) { fprintf(stderr, "Usage: %s [OPTION...]\n", prog); fprintf(stderr, " -f, --use-file=FILE Use the specified configuration file\n"); #if defined _WITH_VRRP_ && defined _WITH_LVS_ fprintf(stderr, " -P, --vrrp Only run with VRRP subsystem\n"); fprintf(stderr, " -C, --check Only run with Health-checker subsystem\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -B, --no_bfd Don't run BFD subsystem\n"); #endif fprintf(stderr, " --all Force all child processes to run, even if have no configuration\n"); fprintf(stderr, " -l, --log-console Log messages to local console\n"); fprintf(stderr, " -D, --log-detail Detailed log messages\n"); fprintf(stderr, " -S, --log-facility=[0-7] Set syslog facility to LOG_LOCAL[0-7]\n"); fprintf(stderr, " -g, --log-file=FILE Also log to FILE (default /tmp/keepalived.log)\n"); fprintf(stderr, " --flush-log-file Flush log file on write\n"); fprintf(stderr, " -G, --no-syslog Don't log via syslog\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -X, --release-vips Drop VIP on transition from signal.\n"); fprintf(stderr, " -V, --dont-release-vrrp Don't remove VRRP VIPs and VROUTEs on daemon stop\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -I, --dont-release-ipvs Don't remove IPVS topology on daemon stop\n"); #endif fprintf(stderr, " -R, --dont-respawn Don't respawn child processes\n"); fprintf(stderr, " -n, --dont-fork Don't fork the daemon process\n"); fprintf(stderr, " -d, --dump-conf Dump the configuration data\n"); fprintf(stderr, " -p, --pid=FILE Use specified pidfile for parent process\n"); #ifdef _WITH_VRRP_ fprintf(stderr, " -r, --vrrp_pid=FILE Use specified pidfile for VRRP child process\n"); #endif #ifdef _WITH_LVS_ fprintf(stderr, " -c, --checkers_pid=FILE Use specified pidfile for checkers child process\n"); fprintf(stderr, " -a, --address-monitoring Report all address additions/deletions notified via netlink\n"); #endif #ifdef _WITH_BFD_ fprintf(stderr, " -b, --bfd_pid=FILE Use specified pidfile for BFD child process\n"); #endif #ifdef _WITH_SNMP_ fprintf(stderr, " -x, --snmp Enable SNMP subsystem\n"); fprintf(stderr, " -A, --snmp-agent-socket=FILE Use the specified socket for master agent\n"); #endif #if HAVE_DECL_CLONE_NEWNET fprintf(stderr, " -s, --namespace=NAME Run in network namespace NAME (overrides config)\n"); #endif fprintf(stderr, " -m, --core-dump Produce core dump if terminate abnormally\n"); fprintf(stderr, " -M, --core-dump-pattern=PATN Also set /proc/sys/kernel/core_pattern to PATN (default 'core')\n"); #ifdef _MEM_CHECK_LOG_ fprintf(stderr, " -L, --mem-check-log Log malloc/frees to syslog\n"); #endif fprintf(stderr, " -i, --config-id id Skip any configuration lines beginning '@' that don't match id\n" " or any lines beginning @^ that do match.\n" " The config-id defaults to the node name if option not used\n"); fprintf(stderr, " --signum=SIGFUNC Return signal number for STOP, RELOAD, DATA, STATS" #ifdef _WITH_JSON_ ", JSON" #endif "\n"); fprintf(stderr, " -t, --config-test[=LOG_FILE] Check the configuration for obvious errors, output to\n" " stderr by default\n"); #ifdef _WITH_PERF_ fprintf(stderr, " --perf[=PERF_TYPE] Collect perf data, PERF_TYPE=all, run(default) or end\n"); #endif #ifdef WITH_DEBUG_OPTIONS fprintf(stderr, " --debug[=...] Enable debug options. p, b, c, v specify parent, bfd, checker and vrrp processes\n"); #ifdef _TIMER_CHECK_ fprintf(stderr, " T - timer debug\n"); #endif #ifdef _SMTP_ALERT_DEBUG_ fprintf(stderr, " M - email alert debug\n"); #endif #ifdef _EPOLL_DEBUG_ fprintf(stderr, " E - epoll debug\n"); #endif #ifdef _EPOLL_THREAD_DUMP_ fprintf(stderr, " D - epoll thread dump debug\n"); #endif #ifdef _VRRP_FD_DEBUG fprintf(stderr, " F - vrrp fd dump debug\n"); #endif #ifdef _REGEX_DEBUG_ fprintf(stderr, " R - regex debug\n"); #endif #ifdef _WITH_REGEX_TIMERS_ fprintf(stderr, " X - regex timers\n"); #endif #ifdef _TSM_DEBUG_ fprintf(stderr, " S - TSM debug\n"); #endif #ifdef _NETLINK_TIMERS_ fprintf(stderr, " N - netlink timer debug\n"); #endif fprintf(stderr, " Example --debug=TpMEvcp\n"); #endif fprintf(stderr, " -v, --version Display the version number\n"); fprintf(stderr, " -h, --help Display this help message\n"); } /* Command line parser */ static bool parse_cmdline(int argc, char **argv) { int c; bool reopen_log = false; int signum; struct utsname uname_buf; int longindex; int curind; bool bad_option = false; unsigned facility; struct option long_options[] = { {"use-file", required_argument, NULL, 'f'}, #if defined _WITH_VRRP_ && defined _WITH_LVS_ {"vrrp", no_argument, NULL, 'P'}, {"check", no_argument, NULL, 'C'}, #endif #ifdef _WITH_BFD_ {"no_bfd", no_argument, NULL, 'B'}, #endif {"all", no_argument, NULL, 3 }, {"log-console", no_argument, NULL, 'l'}, {"log-detail", no_argument, NULL, 'D'}, {"log-facility", required_argument, NULL, 'S'}, {"log-file", optional_argument, NULL, 'g'}, {"flush-log-file", no_argument, NULL, 2 }, {"no-syslog", no_argument, NULL, 'G'}, #ifdef _WITH_VRRP_ {"release-vips", no_argument, NULL, 'X'}, {"dont-release-vrrp", no_argument, NULL, 'V'}, #endif #ifdef _WITH_LVS_ {"dont-release-ipvs", no_argument, NULL, 'I'}, #endif {"dont-respawn", no_argument, NULL, 'R'}, {"dont-fork", no_argument, NULL, 'n'}, {"dump-conf", no_argument, NULL, 'd'}, {"pid", required_argument, NULL, 'p'}, #ifdef _WITH_VRRP_ {"vrrp_pid", required_argument, NULL, 'r'}, #endif #ifdef _WITH_LVS_ {"checkers_pid", required_argument, NULL, 'c'}, {"address-monitoring", no_argument, NULL, 'a'}, #endif #ifdef _WITH_BFD_ {"bfd_pid", required_argument, NULL, 'b'}, #endif #ifdef _WITH_SNMP_ {"snmp", no_argument, NULL, 'x'}, {"snmp-agent-socket", required_argument, NULL, 'A'}, #endif {"core-dump", no_argument, NULL, 'm'}, {"core-dump-pattern", optional_argument, NULL, 'M'}, #ifdef _MEM_CHECK_LOG_ {"mem-check-log", no_argument, NULL, 'L'}, #endif #if HAVE_DECL_CLONE_NEWNET {"namespace", required_argument, NULL, 's'}, #endif {"config-id", required_argument, NULL, 'i'}, {"signum", required_argument, NULL, 4 }, {"config-test", optional_argument, NULL, 't'}, #ifdef _WITH_PERF_ {"perf", optional_argument, NULL, 5 }, #endif #ifdef WITH_DEBUG_OPTIONS {"debug", optional_argument, NULL, 6 }, #endif {"version", no_argument, NULL, 'v'}, {"help", no_argument, NULL, 'h'}, {NULL, 0, NULL, 0 } }; /* Unfortunately, if a short option is used, getopt_long() doesn't change the value * of longindex, so we need to ensure that before calling getopt_long(), longindex * is set to a known invalid value */ curind = optind; while (longindex = -1, (c = getopt_long(argc, argv, ":vhlndDRS:f:p:i:mM::g::Gt::" #if defined _WITH_VRRP_ && defined _WITH_LVS_ "PC" #endif #ifdef _WITH_VRRP_ "r:VX" #endif #ifdef _WITH_LVS_ "ac:I" #endif #ifdef _WITH_BFD_ "Bb:" #endif #ifdef _WITH_SNMP_ "xA:" #endif #ifdef _MEM_CHECK_LOG_ "L" #endif #if HAVE_DECL_CLONE_NEWNET "s:" #endif , long_options, &longindex)) != -1) { /* Check for an empty option argument. For example --use-file= returns * a 0 length option, which we don't want */ if (longindex >= 0 && long_options[longindex].has_arg == required_argument && optarg && !optarg[0]) { c = ':'; optarg = NULL; } switch (c) { case 'v': fprintf(stderr, "%s", version_string); #ifdef GIT_COMMIT fprintf(stderr, ", git commit %s", GIT_COMMIT); #endif fprintf(stderr, "\n\n%s\n\n", COPYRIGHT_STRING); fprintf(stderr, "Built with kernel headers for Linux %d.%d.%d\n", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); uname(&uname_buf); fprintf(stderr, "Running on %s %s %s\n\n", uname_buf.sysname, uname_buf.release, uname_buf.version); fprintf(stderr, "configure options: %s\n\n", KEEPALIVED_CONFIGURE_OPTIONS); fprintf(stderr, "Config options: %s\n\n", CONFIGURATION_OPTIONS); fprintf(stderr, "System options: %s\n", SYSTEM_OPTIONS); exit(0); break; case 'h': usage(argv[0]); exit(0); break; case 'l': __set_bit(LOG_CONSOLE_BIT, &debug); reopen_log = true; break; case 'n': __set_bit(DONT_FORK_BIT, &debug); break; case 'd': __set_bit(DUMP_CONF_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'V': __set_bit(DONT_RELEASE_VRRP_BIT, &debug); break; #endif #ifdef _WITH_LVS_ case 'I': __set_bit(DONT_RELEASE_IPVS_BIT, &debug); break; #endif case 'D': if (__test_bit(LOG_DETAIL_BIT, &debug)) __set_bit(LOG_EXTRA_DETAIL_BIT, &debug); else __set_bit(LOG_DETAIL_BIT, &debug); break; case 'R': __set_bit(DONT_RESPAWN_BIT, &debug); break; #ifdef _WITH_VRRP_ case 'X': __set_bit(RELEASE_VIPS_BIT, &debug); break; #endif case 'S': if (!read_unsigned(optarg, &facility, 0, LOG_FACILITY_MAX, false)) fprintf(stderr, "Invalid log facility '%s'\n", optarg); else { log_facility = LOG_FACILITY[facility].facility; reopen_log = true; } break; case 'g': if (optarg && optarg[0]) log_file_name = optarg; else log_file_name = "/tmp/keepalived.log"; open_log_file(log_file_name, NULL, NULL, NULL); break; case 'G': __set_bit(NO_SYSLOG_BIT, &debug); reopen_log = true; break; case 't': __set_bit(CONFIG_TEST_BIT, &debug); __set_bit(DONT_RESPAWN_BIT, &debug); __set_bit(DONT_FORK_BIT, &debug); __set_bit(NO_SYSLOG_BIT, &debug); if (optarg && optarg[0]) { int fd = open(optarg, O_WRONLY | O_APPEND | O_CREAT, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH); if (fd == -1) { fprintf(stderr, "Unable to open config-test log file %s\n", optarg); exit(EXIT_FAILURE); } dup2(fd, STDERR_FILENO); close(fd); } break; case 'f': conf_file = optarg; break; case 2: /* --flush-log-file */ set_flush_log_file(); break; #if defined _WITH_VRRP_ && defined _WITH_LVS_ case 'P': __clear_bit(DAEMON_CHECKERS, &daemon_mode); break; case 'C': __clear_bit(DAEMON_VRRP, &daemon_mode); break; #endif #ifdef _WITH_BFD_ case 'B': __clear_bit(DAEMON_BFD, &daemon_mode); break; #endif case 'p': main_pidfile = optarg; break; #ifdef _WITH_LVS_ case 'c': checkers_pidfile = optarg; break; case 'a': __set_bit(LOG_ADDRESS_CHANGES, &debug); break; #endif #ifdef _WITH_VRRP_ case 'r': vrrp_pidfile = optarg; break; #endif #ifdef _WITH_BFD_ case 'b': bfd_pidfile = optarg; break; #endif #ifdef _WITH_SNMP_ case 'x': snmp = 1; break; case 'A': snmp_socket = optarg; break; #endif case 'M': set_core_dump_pattern = true; if (optarg && optarg[0]) core_dump_pattern = optarg; /* ... falls through ... */ case 'm': create_core_dump = true; break; #ifdef _MEM_CHECK_LOG_ case 'L': __set_bit(MEM_CHECK_LOG_BIT, &debug); break; #endif #if HAVE_DECL_CLONE_NEWNET case 's': override_namespace = MALLOC(strlen(optarg) + 1); strcpy(override_namespace, optarg); break; #endif case 'i': FREE_PTR(config_id); config_id = MALLOC(strlen(optarg) + 1); strcpy(config_id, optarg); break; case 4: /* --signum */ signum = get_signum(optarg); if (signum == -1) { fprintf(stderr, "Unknown sigfunc %s\n", optarg); exit(1); } printf("%d\n", signum); exit(0); break; case 3: /* --all */ __set_bit(RUN_ALL_CHILDREN, &daemon_mode); #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif break; #ifdef _WITH_PERF_ case 5: if (optarg && optarg[0]) { if (!strcmp(optarg, "run")) perf_run = PERF_RUN; else if (!strcmp(optarg, "all")) perf_run = PERF_ALL; else if (!strcmp(optarg, "end")) perf_run = PERF_END; else log_message(LOG_INFO, "Unknown perf start point %s", optarg); } else perf_run = PERF_RUN; break; #endif #ifdef WITH_DEBUG_OPTIONS case 6: set_debug_options(optarg && optarg[0] ? optarg : NULL); break; #endif case '?': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Unknown option -%c\n", optopt); else fprintf(stderr, "Unknown option %s\n", argv[curind]); bad_option = true; break; case ':': if (optopt && argv[curind][1] != '-') fprintf(stderr, "Missing parameter for option -%c\n", optopt); else fprintf(stderr, "Missing parameter for option --%s\n", long_options[longindex].name); bad_option = true; break; default: exit(1); break; } curind = optind; } if (optind < argc) { printf("Unexpected argument(s): "); while (optind < argc) printf("%s ", argv[optind++]); printf("\n"); } if (bad_option) exit(1); return reopen_log; } #ifdef THREAD_DUMP static void register_parent_thread_addresses(void) { register_scheduler_addresses(); register_signal_thread_addresses(); #ifdef _WITH_LVS_ register_check_parent_addresses(); #endif #ifdef _WITH_VRRP_ register_vrrp_parent_addresses(); #endif #ifdef _WITH_BFD_ register_bfd_parent_addresses(); #endif #ifndef _DEBUG_ register_signal_handler_address("propagate_signal", propagate_signal); register_signal_handler_address("sigend", sigend); #endif register_signal_handler_address("thread_child_handler", thread_child_handler); } #endif /* Entry point */ int keepalived_main(int argc, char **argv) { bool report_stopped = true; struct utsname uname_buf; char *end; /* Ensure time_now is set. We then don't have to check anywhere * else if it is set. */ set_time_now(); /* Save command line options in case need to log them later */ save_cmd_line_options(argc, argv); /* Init debugging level */ debug = 0; /* We are the parent process */ #ifndef _DEBUG_ prog_type = PROG_TYPE_PARENT; #endif /* Initialise daemon_mode */ #ifdef _WITH_VRRP_ __set_bit(DAEMON_VRRP, &daemon_mode); #endif #ifdef _WITH_LVS_ __set_bit(DAEMON_CHECKERS, &daemon_mode); #endif #ifdef _WITH_BFD_ __set_bit(DAEMON_BFD, &daemon_mode); #endif /* Open log with default settings so we can log initially */ openlog(PACKAGE_NAME, LOG_PID, log_facility); #ifdef _MEM_CHECK_ mem_log_init(PACKAGE_NAME, "Parent process"); #endif /* Some functionality depends on kernel version, so get the version here */ if (uname(&uname_buf)) log_message(LOG_INFO, "Unable to get uname() information - error %d", errno); else { os_major = (unsigned)strtoul(uname_buf.release, &end, 10); if (*end != '.') os_major = 0; else { os_minor = (unsigned)strtoul(end + 1, &end, 10); if (*end != '.') os_major = 0; else { if (!isdigit(end[1])) os_major = 0; else os_release = (unsigned)strtoul(end + 1, &end, 10); } } if (!os_major) log_message(LOG_INFO, "Unable to parse kernel version %s", uname_buf.release); /* config_id defaults to hostname */ if (!config_id) { end = strchrnul(uname_buf.nodename, '.'); config_id = MALLOC((size_t)(end - uname_buf.nodename) + 1); strncpy(config_id, uname_buf.nodename, (size_t)(end - uname_buf.nodename)); config_id[end - uname_buf.nodename] = '\0'; } } /* * Parse command line and set debug level. * bits 0..7 reserved by main.c */ if (parse_cmdline(argc, argv)) { closelog(); if (!__test_bit(NO_SYSLOG_BIT, &debug)) openlog(PACKAGE_NAME, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0) , log_facility); } if (__test_bit(LOG_CONSOLE_BIT, &debug)) enable_console_log(); #ifdef GIT_COMMIT log_message(LOG_INFO, "Starting %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Starting %s", version_string); #endif /* Handle any core file requirements */ core_dump_init(); if (os_major) { if (KERNEL_VERSION(os_major, os_minor, os_release) < LINUX_VERSION_CODE) { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "WARNING - keepalived was build for newer Linux %d.%d.%d, running on %s %s %s", (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff, uname_buf.sysname, uname_buf.release, uname_buf.version); } else { /* keepalived was build for a later kernel version */ log_message(LOG_INFO, "Running on %s %s %s (built for Linux %d.%d.%d)", uname_buf.sysname, uname_buf.release, uname_buf.version, (LINUX_VERSION_CODE >> 16) & 0xff, (LINUX_VERSION_CODE >> 8) & 0xff, (LINUX_VERSION_CODE ) & 0xff); } } #ifndef _DEBUG_ log_command_line(0); #endif /* Check we can read the configuration file(s). NOTE: the working directory will be / if we forked, but will be the current working directory when keepalived was run if we haven't forked. This means that if any config file names are not absolute file names, the behaviour will be different depending on whether we forked or not. */ if (!check_conf_file(conf_file)) { if (__test_bit(CONFIG_TEST_BIT, &debug)) config_test_exit(); goto end; } global_data = alloc_global_data(); read_config_file(); init_global_data(global_data, NULL); #if HAVE_DECL_CLONE_NEWNET if (override_namespace) { if (global_data->network_namespace) { log_message(LOG_INFO, "Overriding config net_namespace '%s' with command line namespace '%s'", global_data->network_namespace, override_namespace); FREE(global_data->network_namespace); } global_data->network_namespace = override_namespace; override_namespace = NULL; } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug) && (global_data->instance_name #if HAVE_DECL_CLONE_NEWNET || global_data->network_namespace #endif )) { if ((syslog_ident = make_syslog_ident(PACKAGE_NAME))) { log_message(LOG_INFO, "Changing syslog ident to %s", syslog_ident); closelog(); openlog(syslog_ident, LOG_PID | ((__test_bit(LOG_CONSOLE_BIT, &debug)) ? LOG_CONS : 0), log_facility); } else log_message(LOG_INFO, "Unable to change syslog ident"); use_pid_dir = true; open_log_file(log_file_name, NULL, #if HAVE_DECL_CLONE_NEWNET global_data->network_namespace, #else NULL, #endif global_data->instance_name); } /* Initialise pointer to child finding function */ set_child_finder_name(find_keepalived_child_name); if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (use_pid_dir) { /* Create the directory for pid files */ create_pid_dir(); } } #if HAVE_DECL_CLONE_NEWNET if (global_data->network_namespace) { if (global_data->network_namespace && !set_namespaces(global_data->network_namespace)) { log_message(LOG_ERR, "Unable to set network namespace %s - exiting", global_data->network_namespace); goto end; } } #endif if (!__test_bit(CONFIG_TEST_BIT, &debug)) { if (global_data->instance_name) { if (!main_pidfile && (main_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_main_pidfile = true; #ifdef _WITH_LVS_ if (!checkers_pidfile && (checkers_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR CHECKERS_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_checkers_pidfile = true; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile && (vrrp_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_vrrp_pidfile = true; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile && (bfd_pidfile = make_pidfile_name(KEEPALIVED_PID_DIR VRRP_PID_FILE, global_data->instance_name, PID_EXTENSION))) free_bfd_pidfile = true; #endif } if (use_pid_dir) { if (!main_pidfile) main_pidfile = KEEPALIVED_PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = KEEPALIVED_PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = KEEPALIVED_PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = KEEPALIVED_PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } else { if (!main_pidfile) main_pidfile = PID_DIR KEEPALIVED_PID_FILE PID_EXTENSION; #ifdef _WITH_LVS_ if (!checkers_pidfile) checkers_pidfile = PID_DIR CHECKERS_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_VRRP_ if (!vrrp_pidfile) vrrp_pidfile = PID_DIR VRRP_PID_FILE PID_EXTENSION; #endif #ifdef _WITH_BFD_ if (!bfd_pidfile) bfd_pidfile = PID_DIR BFD_PID_FILE PID_EXTENSION; #endif } /* Check if keepalived is already running */ if (keepalived_running(daemon_mode)) { log_message(LOG_INFO, "daemon is already running"); report_stopped = false; goto end; } } /* daemonize process */ if (!__test_bit(DONT_FORK_BIT, &debug) && xdaemon(false, false, true) > 0) { closelog(); FREE_PTR(config_id); FREE_PTR(orig_core_dump_pattern); close_std_fd(); exit(0); } /* Set file creation mask */ umask(0); #ifdef _MEM_CHECK_ enable_mem_log_termination(); #endif if (__test_bit(CONFIG_TEST_BIT, &debug)) { validate_config(); config_test_exit(); } /* write the father's pidfile */ if (!pidfile_write(main_pidfile, getpid())) goto end; /* Create the master thread */ master = thread_make_master(); /* Signal handling initialization */ signal_init(); /* Init daemon */ if (!start_keepalived()) log_message(LOG_INFO, "Warning - keepalived has no configuration to run"); initialise_debug_options(); #ifdef THREAD_DUMP register_parent_thread_addresses(); #endif /* Launch the scheduling I/O multiplexer */ launch_thread_scheduler(master); /* Finish daemon process */ stop_keepalived(); #ifdef THREAD_DUMP deregister_thread_addresses(); #endif /* * Reached when terminate signal catched. * finally return from system */ end: if (report_stopped) { #ifdef GIT_COMMIT log_message(LOG_INFO, "Stopped %s, git commit %s", version_string, GIT_COMMIT); #else log_message(LOG_INFO, "Stopped %s", version_string); #endif } #if HAVE_DECL_CLONE_NEWNET if (global_data && global_data->network_namespace) clear_namespaces(); #endif if (use_pid_dir) remove_pid_dir(); /* Restore original core_pattern if necessary */ if (orig_core_dump_pattern) update_core_dump_pattern(orig_core_dump_pattern); free_parent_mallocs_startup(false); free_parent_mallocs_exit(); free_global_data(global_data); closelog(); #ifndef _MEM_CHECK_LOG_ FREE_PTR(syslog_ident); #else if (syslog_ident) free(syslog_ident); #endif close_std_fd(); exit(KEEPALIVED_EXIT_OK); }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_438_5
crossvul-cpp_data_good_1790_0
/* * Point-to-Point Tunneling Protocol for Linux * * Authors: Dmitry Kozlov <xeb@mail.ru> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * */ #include <linux/string.h> #include <linux/module.h> #include <linux/kernel.h> #include <linux/slab.h> #include <linux/errno.h> #include <linux/netdevice.h> #include <linux/net.h> #include <linux/skbuff.h> #include <linux/vmalloc.h> #include <linux/init.h> #include <linux/ppp_channel.h> #include <linux/ppp_defs.h> #include <linux/if_pppox.h> #include <linux/ppp-ioctl.h> #include <linux/notifier.h> #include <linux/file.h> #include <linux/in.h> #include <linux/ip.h> #include <linux/rcupdate.h> #include <linux/spinlock.h> #include <net/sock.h> #include <net/protocol.h> #include <net/ip.h> #include <net/icmp.h> #include <net/route.h> #include <net/gre.h> #include <linux/uaccess.h> #define PPTP_DRIVER_VERSION "0.8.5" #define MAX_CALLID 65535 static DECLARE_BITMAP(callid_bitmap, MAX_CALLID + 1); static struct pppox_sock __rcu **callid_sock; static DEFINE_SPINLOCK(chan_lock); static struct proto pptp_sk_proto __read_mostly; static const struct ppp_channel_ops pptp_chan_ops; static const struct proto_ops pptp_ops; #define PPP_LCP_ECHOREQ 0x09 #define PPP_LCP_ECHOREP 0x0A #define SC_RCV_BITS (SC_RCV_B7_1|SC_RCV_B7_0|SC_RCV_ODDP|SC_RCV_EVNP) #define MISSING_WINDOW 20 #define WRAPPED(curseq, lastseq)\ ((((curseq) & 0xffffff00) == 0) &&\ (((lastseq) & 0xffffff00) == 0xffffff00)) #define PPTP_GRE_PROTO 0x880B #define PPTP_GRE_VER 0x1 #define PPTP_GRE_FLAG_C 0x80 #define PPTP_GRE_FLAG_R 0x40 #define PPTP_GRE_FLAG_K 0x20 #define PPTP_GRE_FLAG_S 0x10 #define PPTP_GRE_FLAG_A 0x80 #define PPTP_GRE_IS_C(f) ((f)&PPTP_GRE_FLAG_C) #define PPTP_GRE_IS_R(f) ((f)&PPTP_GRE_FLAG_R) #define PPTP_GRE_IS_K(f) ((f)&PPTP_GRE_FLAG_K) #define PPTP_GRE_IS_S(f) ((f)&PPTP_GRE_FLAG_S) #define PPTP_GRE_IS_A(f) ((f)&PPTP_GRE_FLAG_A) #define PPTP_HEADER_OVERHEAD (2+sizeof(struct pptp_gre_header)) struct pptp_gre_header { u8 flags; u8 ver; __be16 protocol; __be16 payload_len; __be16 call_id; __be32 seq; __be32 ack; } __packed; static struct pppox_sock *lookup_chan(u16 call_id, __be32 s_addr) { struct pppox_sock *sock; struct pptp_opt *opt; rcu_read_lock(); sock = rcu_dereference(callid_sock[call_id]); if (sock) { opt = &sock->proto.pptp; if (opt->dst_addr.sin_addr.s_addr != s_addr) sock = NULL; else sock_hold(sk_pppox(sock)); } rcu_read_unlock(); return sock; } static int lookup_chan_dst(u16 call_id, __be32 d_addr) { struct pppox_sock *sock; struct pptp_opt *opt; int i; rcu_read_lock(); i = 1; for_each_set_bit_from(i, callid_bitmap, MAX_CALLID) { sock = rcu_dereference(callid_sock[i]); if (!sock) continue; opt = &sock->proto.pptp; if (opt->dst_addr.call_id == call_id && opt->dst_addr.sin_addr.s_addr == d_addr) break; } rcu_read_unlock(); return i < MAX_CALLID; } static int add_chan(struct pppox_sock *sock) { static int call_id; spin_lock(&chan_lock); if (!sock->proto.pptp.src_addr.call_id) { call_id = find_next_zero_bit(callid_bitmap, MAX_CALLID, call_id + 1); if (call_id == MAX_CALLID) { call_id = find_next_zero_bit(callid_bitmap, MAX_CALLID, 1); if (call_id == MAX_CALLID) goto out_err; } sock->proto.pptp.src_addr.call_id = call_id; } else if (test_bit(sock->proto.pptp.src_addr.call_id, callid_bitmap)) goto out_err; set_bit(sock->proto.pptp.src_addr.call_id, callid_bitmap); rcu_assign_pointer(callid_sock[sock->proto.pptp.src_addr.call_id], sock); spin_unlock(&chan_lock); return 0; out_err: spin_unlock(&chan_lock); return -1; } static void del_chan(struct pppox_sock *sock) { spin_lock(&chan_lock); clear_bit(sock->proto.pptp.src_addr.call_id, callid_bitmap); RCU_INIT_POINTER(callid_sock[sock->proto.pptp.src_addr.call_id], NULL); spin_unlock(&chan_lock); synchronize_rcu(); } static int pptp_xmit(struct ppp_channel *chan, struct sk_buff *skb) { struct sock *sk = (struct sock *) chan->private; struct pppox_sock *po = pppox_sk(sk); struct net *net = sock_net(sk); struct pptp_opt *opt = &po->proto.pptp; struct pptp_gre_header *hdr; unsigned int header_len = sizeof(*hdr); struct flowi4 fl4; int islcp; int len; unsigned char *data; __u32 seq_recv; struct rtable *rt; struct net_device *tdev; struct iphdr *iph; int max_headroom; if (sk_pppox(po)->sk_state & PPPOX_DEAD) goto tx_error; rt = ip_route_output_ports(net, &fl4, NULL, opt->dst_addr.sin_addr.s_addr, opt->src_addr.sin_addr.s_addr, 0, 0, IPPROTO_GRE, RT_TOS(0), 0); if (IS_ERR(rt)) goto tx_error; tdev = rt->dst.dev; max_headroom = LL_RESERVED_SPACE(tdev) + sizeof(*iph) + sizeof(*hdr) + 2; if (skb_headroom(skb) < max_headroom || skb_cloned(skb) || skb_shared(skb)) { struct sk_buff *new_skb = skb_realloc_headroom(skb, max_headroom); if (!new_skb) { ip_rt_put(rt); goto tx_error; } if (skb->sk) skb_set_owner_w(new_skb, skb->sk); consume_skb(skb); skb = new_skb; } data = skb->data; islcp = ((data[0] << 8) + data[1]) == PPP_LCP && 1 <= data[2] && data[2] <= 7; /* compress protocol field */ if ((opt->ppp_flags & SC_COMP_PROT) && data[0] == 0 && !islcp) skb_pull(skb, 1); /* Put in the address/control bytes if necessary */ if ((opt->ppp_flags & SC_COMP_AC) == 0 || islcp) { data = skb_push(skb, 2); data[0] = PPP_ALLSTATIONS; data[1] = PPP_UI; } len = skb->len; seq_recv = opt->seq_recv; if (opt->ack_sent == seq_recv) header_len -= sizeof(hdr->ack); /* Push down and install GRE header */ skb_push(skb, header_len); hdr = (struct pptp_gre_header *)(skb->data); hdr->flags = PPTP_GRE_FLAG_K; hdr->ver = PPTP_GRE_VER; hdr->protocol = htons(PPTP_GRE_PROTO); hdr->call_id = htons(opt->dst_addr.call_id); hdr->flags |= PPTP_GRE_FLAG_S; hdr->seq = htonl(++opt->seq_sent); if (opt->ack_sent != seq_recv) { /* send ack with this message */ hdr->ver |= PPTP_GRE_FLAG_A; hdr->ack = htonl(seq_recv); opt->ack_sent = seq_recv; } hdr->payload_len = htons(len); /* Push down and install the IP header. */ skb_reset_transport_header(skb); skb_push(skb, sizeof(*iph)); skb_reset_network_header(skb); memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt)); IPCB(skb)->flags &= ~(IPSKB_XFRM_TUNNEL_SIZE | IPSKB_XFRM_TRANSFORMED | IPSKB_REROUTED); iph = ip_hdr(skb); iph->version = 4; iph->ihl = sizeof(struct iphdr) >> 2; if (ip_dont_fragment(sk, &rt->dst)) iph->frag_off = htons(IP_DF); else iph->frag_off = 0; iph->protocol = IPPROTO_GRE; iph->tos = 0; iph->daddr = fl4.daddr; iph->saddr = fl4.saddr; iph->ttl = ip4_dst_hoplimit(&rt->dst); iph->tot_len = htons(skb->len); skb_dst_drop(skb); skb_dst_set(skb, &rt->dst); nf_reset(skb); skb->ip_summed = CHECKSUM_NONE; ip_select_ident(net, skb, NULL); ip_send_check(iph); ip_local_out(net, skb->sk, skb); return 1; tx_error: kfree_skb(skb); return 1; } static int pptp_rcv_core(struct sock *sk, struct sk_buff *skb) { struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; int headersize, payload_len, seq; __u8 *payload; struct pptp_gre_header *header; if (!(sk->sk_state & PPPOX_CONNECTED)) { if (sock_queue_rcv_skb(sk, skb)) goto drop; return NET_RX_SUCCESS; } header = (struct pptp_gre_header *)(skb->data); headersize = sizeof(*header); /* test if acknowledgement present */ if (PPTP_GRE_IS_A(header->ver)) { __u32 ack; if (!pskb_may_pull(skb, headersize)) goto drop; header = (struct pptp_gre_header *)(skb->data); /* ack in different place if S = 0 */ ack = PPTP_GRE_IS_S(header->flags) ? header->ack : header->seq; ack = ntohl(ack); if (ack > opt->ack_recv) opt->ack_recv = ack; /* also handle sequence number wrap-around */ if (WRAPPED(ack, opt->ack_recv)) opt->ack_recv = ack; } else { headersize -= sizeof(header->ack); } /* test if payload present */ if (!PPTP_GRE_IS_S(header->flags)) goto drop; payload_len = ntohs(header->payload_len); seq = ntohl(header->seq); /* check for incomplete packet (length smaller than expected) */ if (!pskb_may_pull(skb, headersize + payload_len)) goto drop; payload = skb->data + headersize; /* check for expected sequence number */ if (seq < opt->seq_recv + 1 || WRAPPED(opt->seq_recv, seq)) { if ((payload[0] == PPP_ALLSTATIONS) && (payload[1] == PPP_UI) && (PPP_PROTOCOL(payload) == PPP_LCP) && ((payload[4] == PPP_LCP_ECHOREQ) || (payload[4] == PPP_LCP_ECHOREP))) goto allow_packet; } else { opt->seq_recv = seq; allow_packet: skb_pull(skb, headersize); if (payload[0] == PPP_ALLSTATIONS && payload[1] == PPP_UI) { /* chop off address/control */ if (skb->len < 3) goto drop; skb_pull(skb, 2); } if ((*skb->data) & 1) { /* protocol is compressed */ skb_push(skb, 1)[0] = 0; } skb->ip_summed = CHECKSUM_NONE; skb_set_network_header(skb, skb->head-skb->data); ppp_input(&po->chan, skb); return NET_RX_SUCCESS; } drop: kfree_skb(skb); return NET_RX_DROP; } static int pptp_rcv(struct sk_buff *skb) { struct pppox_sock *po; struct pptp_gre_header *header; struct iphdr *iph; if (skb->pkt_type != PACKET_HOST) goto drop; if (!pskb_may_pull(skb, 12)) goto drop; iph = ip_hdr(skb); header = (struct pptp_gre_header *)skb->data; if (ntohs(header->protocol) != PPTP_GRE_PROTO || /* PPTP-GRE protocol for PPTP */ PPTP_GRE_IS_C(header->flags) || /* flag C should be clear */ PPTP_GRE_IS_R(header->flags) || /* flag R should be clear */ !PPTP_GRE_IS_K(header->flags) || /* flag K should be set */ (header->flags&0xF) != 0) /* routing and recursion ctrl = 0 */ /* if invalid, discard this packet */ goto drop; po = lookup_chan(htons(header->call_id), iph->saddr); if (po) { skb_dst_drop(skb); nf_reset(skb); return sk_receive_skb(sk_pppox(po), skb, 0); } drop: kfree_skb(skb); return NET_RX_DROP; } static int pptp_bind(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; int error = 0; if (sockaddr_len < sizeof(struct sockaddr_pppox)) return -EINVAL; lock_sock(sk); opt->src_addr = sp->sa_addr.pptp; if (add_chan(po)) error = -EBUSY; release_sock(sk); return error; } static int pptp_connect(struct socket *sock, struct sockaddr *uservaddr, int sockaddr_len, int flags) { struct sock *sk = sock->sk; struct sockaddr_pppox *sp = (struct sockaddr_pppox *) uservaddr; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; struct rtable *rt; struct flowi4 fl4; int error = 0; if (sockaddr_len < sizeof(struct sockaddr_pppox)) return -EINVAL; if (sp->sa_protocol != PX_PROTO_PPTP) return -EINVAL; if (lookup_chan_dst(sp->sa_addr.pptp.call_id, sp->sa_addr.pptp.sin_addr.s_addr)) return -EALREADY; lock_sock(sk); /* Check for already bound sockets */ if (sk->sk_state & PPPOX_CONNECTED) { error = -EBUSY; goto end; } /* Check for already disconnected sockets, on attempts to disconnect */ if (sk->sk_state & PPPOX_DEAD) { error = -EALREADY; goto end; } if (!opt->src_addr.sin_addr.s_addr || !sp->sa_addr.pptp.sin_addr.s_addr) { error = -EINVAL; goto end; } po->chan.private = sk; po->chan.ops = &pptp_chan_ops; rt = ip_route_output_ports(sock_net(sk), &fl4, sk, opt->dst_addr.sin_addr.s_addr, opt->src_addr.sin_addr.s_addr, 0, 0, IPPROTO_GRE, RT_CONN_FLAGS(sk), 0); if (IS_ERR(rt)) { error = -EHOSTUNREACH; goto end; } sk_setup_caps(sk, &rt->dst); po->chan.mtu = dst_mtu(&rt->dst); if (!po->chan.mtu) po->chan.mtu = PPP_MRU; ip_rt_put(rt); po->chan.mtu -= PPTP_HEADER_OVERHEAD; po->chan.hdrlen = 2 + sizeof(struct pptp_gre_header); error = ppp_register_channel(&po->chan); if (error) { pr_err("PPTP: failed to register PPP channel (%d)\n", error); goto end; } opt->dst_addr = sp->sa_addr.pptp; sk->sk_state = PPPOX_CONNECTED; end: release_sock(sk); return error; } static int pptp_getname(struct socket *sock, struct sockaddr *uaddr, int *usockaddr_len, int peer) { int len = sizeof(struct sockaddr_pppox); struct sockaddr_pppox sp; memset(&sp.sa_addr, 0, sizeof(sp.sa_addr)); sp.sa_family = AF_PPPOX; sp.sa_protocol = PX_PROTO_PPTP; sp.sa_addr.pptp = pppox_sk(sock->sk)->proto.pptp.src_addr; memcpy(uaddr, &sp, len); *usockaddr_len = len; return 0; } static int pptp_release(struct socket *sock) { struct sock *sk = sock->sk; struct pppox_sock *po; struct pptp_opt *opt; int error = 0; if (!sk) return 0; lock_sock(sk); if (sock_flag(sk, SOCK_DEAD)) { release_sock(sk); return -EBADF; } po = pppox_sk(sk); opt = &po->proto.pptp; del_chan(po); pppox_unbind_sock(sk); sk->sk_state = PPPOX_DEAD; sock_orphan(sk); sock->sk = NULL; release_sock(sk); sock_put(sk); return error; } static void pptp_sock_destruct(struct sock *sk) { if (!(sk->sk_state & PPPOX_DEAD)) { del_chan(pppox_sk(sk)); pppox_unbind_sock(sk); } skb_queue_purge(&sk->sk_receive_queue); } static int pptp_create(struct net *net, struct socket *sock, int kern) { int error = -ENOMEM; struct sock *sk; struct pppox_sock *po; struct pptp_opt *opt; sk = sk_alloc(net, PF_PPPOX, GFP_KERNEL, &pptp_sk_proto, kern); if (!sk) goto out; sock_init_data(sock, sk); sock->state = SS_UNCONNECTED; sock->ops = &pptp_ops; sk->sk_backlog_rcv = pptp_rcv_core; sk->sk_state = PPPOX_NONE; sk->sk_type = SOCK_STREAM; sk->sk_family = PF_PPPOX; sk->sk_protocol = PX_PROTO_PPTP; sk->sk_destruct = pptp_sock_destruct; po = pppox_sk(sk); opt = &po->proto.pptp; opt->seq_sent = 0; opt->seq_recv = 0xffffffff; opt->ack_recv = 0; opt->ack_sent = 0xffffffff; error = 0; out: return error; } static int pptp_ppp_ioctl(struct ppp_channel *chan, unsigned int cmd, unsigned long arg) { struct sock *sk = (struct sock *) chan->private; struct pppox_sock *po = pppox_sk(sk); struct pptp_opt *opt = &po->proto.pptp; void __user *argp = (void __user *)arg; int __user *p = argp; int err, val; err = -EFAULT; switch (cmd) { case PPPIOCGFLAGS: val = opt->ppp_flags; if (put_user(val, p)) break; err = 0; break; case PPPIOCSFLAGS: if (get_user(val, p)) break; opt->ppp_flags = val & ~SC_RCV_BITS; err = 0; break; default: err = -ENOTTY; } return err; } static const struct ppp_channel_ops pptp_chan_ops = { .start_xmit = pptp_xmit, .ioctl = pptp_ppp_ioctl, }; static struct proto pptp_sk_proto __read_mostly = { .name = "PPTP", .owner = THIS_MODULE, .obj_size = sizeof(struct pppox_sock), }; static const struct proto_ops pptp_ops = { .family = AF_PPPOX, .owner = THIS_MODULE, .release = pptp_release, .bind = pptp_bind, .connect = pptp_connect, .socketpair = sock_no_socketpair, .accept = sock_no_accept, .getname = pptp_getname, .poll = sock_no_poll, .listen = sock_no_listen, .shutdown = sock_no_shutdown, .setsockopt = sock_no_setsockopt, .getsockopt = sock_no_getsockopt, .sendmsg = sock_no_sendmsg, .recvmsg = sock_no_recvmsg, .mmap = sock_no_mmap, .ioctl = pppox_ioctl, }; static const struct pppox_proto pppox_pptp_proto = { .create = pptp_create, .owner = THIS_MODULE, }; static const struct gre_protocol gre_pptp_protocol = { .handler = pptp_rcv, }; static int __init pptp_init_module(void) { int err = 0; pr_info("PPTP driver version " PPTP_DRIVER_VERSION "\n"); callid_sock = vzalloc((MAX_CALLID + 1) * sizeof(void *)); if (!callid_sock) return -ENOMEM; err = gre_add_protocol(&gre_pptp_protocol, GREPROTO_PPTP); if (err) { pr_err("PPTP: can't add gre protocol\n"); goto out_mem_free; } err = proto_register(&pptp_sk_proto, 0); if (err) { pr_err("PPTP: can't register sk_proto\n"); goto out_gre_del_protocol; } err = register_pppox_proto(PX_PROTO_PPTP, &pppox_pptp_proto); if (err) { pr_err("PPTP: can't register pppox_proto\n"); goto out_unregister_sk_proto; } return 0; out_unregister_sk_proto: proto_unregister(&pptp_sk_proto); out_gre_del_protocol: gre_del_protocol(&gre_pptp_protocol, GREPROTO_PPTP); out_mem_free: vfree(callid_sock); return err; } static void __exit pptp_exit_module(void) { unregister_pppox_proto(PX_PROTO_PPTP); proto_unregister(&pptp_sk_proto); gre_del_protocol(&gre_pptp_protocol, GREPROTO_PPTP); vfree(callid_sock); } module_init(pptp_init_module); module_exit(pptp_exit_module); MODULE_DESCRIPTION("Point-to-Point Tunneling Protocol"); MODULE_AUTHOR("D. Kozlov (xeb@mail.ru)"); MODULE_LICENSE("GPL");
./CrossVul/dataset_final_sorted/CWE-200/c/good_1790_0
crossvul-cpp_data_good_2075_0
/* * Media device * * Copyright (C) 2010 Nokia Corporation * * Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com> * Sakari Ailus <sakari.ailus@iki.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/compat.h> #include <linux/export.h> #include <linux/ioctl.h> #include <linux/media.h> #include <linux/types.h> #include <media/media-device.h> #include <media/media-devnode.h> #include <media/media-entity.h> /* ----------------------------------------------------------------------------- * Userspace API */ static int media_device_open(struct file *filp) { return 0; } static int media_device_close(struct file *filp) { return 0; } static int media_device_get_info(struct media_device *dev, struct media_device_info __user *__info) { struct media_device_info info; memset(&info, 0, sizeof(info)); strlcpy(info.driver, dev->dev->driver->name, sizeof(info.driver)); strlcpy(info.model, dev->model, sizeof(info.model)); strlcpy(info.serial, dev->serial, sizeof(info.serial)); strlcpy(info.bus_info, dev->bus_info, sizeof(info.bus_info)); info.media_version = MEDIA_API_VERSION; info.hw_revision = dev->hw_revision; info.driver_version = dev->driver_version; if (copy_to_user(__info, &info, sizeof(*__info))) return -EFAULT; return 0; } static struct media_entity *find_entity(struct media_device *mdev, u32 id) { struct media_entity *entity; int next = id & MEDIA_ENT_ID_FLAG_NEXT; id &= ~MEDIA_ENT_ID_FLAG_NEXT; spin_lock(&mdev->lock); media_device_for_each_entity(entity, mdev) { if ((entity->id == id && !next) || (entity->id > id && next)) { spin_unlock(&mdev->lock); return entity; } } spin_unlock(&mdev->lock); return NULL; } static long media_device_enum_entities(struct media_device *mdev, struct media_entity_desc __user *uent) { struct media_entity *ent; struct media_entity_desc u_ent; memset(&u_ent, 0, sizeof(u_ent)); if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id))) return -EFAULT; ent = find_entity(mdev, u_ent.id); if (ent == NULL) return -EINVAL; u_ent.id = ent->id; if (ent->name) { strncpy(u_ent.name, ent->name, sizeof(u_ent.name)); u_ent.name[sizeof(u_ent.name) - 1] = '\0'; } else { memset(u_ent.name, 0, sizeof(u_ent.name)); } u_ent.type = ent->type; u_ent.revision = ent->revision; u_ent.flags = ent->flags; u_ent.group_id = ent->group_id; u_ent.pads = ent->num_pads; u_ent.links = ent->num_links - ent->num_backlinks; memcpy(&u_ent.raw, &ent->info, sizeof(ent->info)); if (copy_to_user(uent, &u_ent, sizeof(u_ent))) return -EFAULT; return 0; } static void media_device_kpad_to_upad(const struct media_pad *kpad, struct media_pad_desc *upad) { upad->entity = kpad->entity->id; upad->index = kpad->index; upad->flags = kpad->flags; } static long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; memset(&pad, 0, sizeof(pad)); media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; memset(&link, 0, sizeof(link)); media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; } static long media_device_enum_links(struct media_device *mdev, struct media_links_enum __user *ulinks) { struct media_links_enum links; int rval; if (copy_from_user(&links, ulinks, sizeof(links))) return -EFAULT; rval = __media_device_enum_links(mdev, &links); if (rval < 0) return rval; if (copy_to_user(ulinks, &links, sizeof(*ulinks))) return -EFAULT; return 0; } static long media_device_setup_link(struct media_device *mdev, struct media_link_desc __user *_ulink) { struct media_link *link = NULL; struct media_link_desc ulink; struct media_entity *source; struct media_entity *sink; int ret; if (copy_from_user(&ulink, _ulink, sizeof(ulink))) return -EFAULT; /* Find the source and sink entities and link. */ source = find_entity(mdev, ulink.source.entity); sink = find_entity(mdev, ulink.sink.entity); if (source == NULL || sink == NULL) return -EINVAL; if (ulink.source.index >= source->num_pads || ulink.sink.index >= sink->num_pads) return -EINVAL; link = media_entity_find_link(&source->pads[ulink.source.index], &sink->pads[ulink.sink.index]); if (link == NULL) return -EINVAL; /* Setup the link on both entities. */ ret = __media_entity_setup_link(link, ulink.flags); if (copy_to_user(_ulink, &ulink, sizeof(ulink))) return -EFAULT; return ret; } static long media_device_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: ret = media_device_get_info(dev, (struct media_device_info __user *)arg); break; case MEDIA_IOC_ENUM_ENTITIES: ret = media_device_enum_entities(dev, (struct media_entity_desc __user *)arg); break; case MEDIA_IOC_ENUM_LINKS: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links(dev, (struct media_links_enum __user *)arg); mutex_unlock(&dev->graph_mutex); break; case MEDIA_IOC_SETUP_LINK: mutex_lock(&dev->graph_mutex); ret = media_device_setup_link(dev, (struct media_link_desc __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #ifdef CONFIG_COMPAT struct media_links_enum32 { __u32 entity; compat_uptr_t pads; /* struct media_pad_desc * */ compat_uptr_t links; /* struct media_link_desc * */ __u32 reserved[4]; }; static long media_device_enum_links32(struct media_device *mdev, struct media_links_enum32 __user *ulinks) { struct media_links_enum links; compat_uptr_t pads_ptr, links_ptr; memset(&links, 0, sizeof(links)); if (get_user(links.entity, &ulinks->entity) || get_user(pads_ptr, &ulinks->pads) || get_user(links_ptr, &ulinks->links)) return -EFAULT; links.pads = compat_ptr(pads_ptr); links.links = compat_ptr(links_ptr); return __media_device_enum_links(mdev, &links); } #define MEDIA_IOC_ENUM_LINKS32 _IOWR('|', 0x02, struct media_links_enum32) static long media_device_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: case MEDIA_IOC_ENUM_ENTITIES: case MEDIA_IOC_SETUP_LINK: return media_device_ioctl(filp, cmd, arg); case MEDIA_IOC_ENUM_LINKS32: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links32(dev, (struct media_links_enum32 __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #endif /* CONFIG_COMPAT */ static const struct media_file_operations media_device_fops = { .owner = THIS_MODULE, .open = media_device_open, .ioctl = media_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = media_device_compat_ioctl, #endif /* CONFIG_COMPAT */ .release = media_device_close, }; /* ----------------------------------------------------------------------------- * sysfs */ static ssize_t show_model(struct device *cd, struct device_attribute *attr, char *buf) { struct media_device *mdev = to_media_device(to_media_devnode(cd)); return sprintf(buf, "%.*s\n", (int)sizeof(mdev->model), mdev->model); } static DEVICE_ATTR(model, S_IRUGO, show_model, NULL); /* ----------------------------------------------------------------------------- * Registration/unregistration */ static void media_device_release(struct media_devnode *mdev) { } /** * media_device_register - register a media device * @mdev: The media device * * The caller is responsible for initializing the media device before * registration. The following fields must be set: * * - dev must point to the parent device * - model must be filled with the device model name */ int __must_check media_device_register(struct media_device *mdev) { int ret; if (WARN_ON(mdev->dev == NULL || mdev->model[0] == 0)) return -EINVAL; mdev->entity_id = 1; INIT_LIST_HEAD(&mdev->entities); spin_lock_init(&mdev->lock); mutex_init(&mdev->graph_mutex); /* Register the device node. */ mdev->devnode.fops = &media_device_fops; mdev->devnode.parent = mdev->dev; mdev->devnode.release = media_device_release; ret = media_devnode_register(&mdev->devnode); if (ret < 0) return ret; ret = device_create_file(&mdev->devnode.dev, &dev_attr_model); if (ret < 0) { media_devnode_unregister(&mdev->devnode); return ret; } return 0; } EXPORT_SYMBOL_GPL(media_device_register); /** * media_device_unregister - unregister a media device * @mdev: The media device * */ void media_device_unregister(struct media_device *mdev) { struct media_entity *entity; struct media_entity *next; list_for_each_entry_safe(entity, next, &mdev->entities, list) media_device_unregister_entity(entity); device_remove_file(&mdev->devnode.dev, &dev_attr_model); media_devnode_unregister(&mdev->devnode); } EXPORT_SYMBOL_GPL(media_device_unregister); /** * media_device_register_entity - Register an entity with a media device * @mdev: The media device * @entity: The entity */ int __must_check media_device_register_entity(struct media_device *mdev, struct media_entity *entity) { /* Warn if we apparently re-register an entity */ WARN_ON(entity->parent != NULL); entity->parent = mdev; spin_lock(&mdev->lock); if (entity->id == 0) entity->id = mdev->entity_id++; else mdev->entity_id = max(entity->id + 1, mdev->entity_id); list_add_tail(&entity->list, &mdev->entities); spin_unlock(&mdev->lock); return 0; } EXPORT_SYMBOL_GPL(media_device_register_entity); /** * media_device_unregister_entity - Unregister an entity * @entity: The entity * * If the entity has never been registered this function will return * immediately. */ void media_device_unregister_entity(struct media_entity *entity) { struct media_device *mdev = entity->parent; if (mdev == NULL) return; spin_lock(&mdev->lock); list_del(&entity->list); spin_unlock(&mdev->lock); entity->parent = NULL; } EXPORT_SYMBOL_GPL(media_device_unregister_entity);
./CrossVul/dataset_final_sorted/CWE-200/c/good_2075_0
crossvul-cpp_data_bad_5688_0
/* * IUCV protocol stack for Linux on zSeries * * Copyright IBM Corp. 2006, 2009 * * Author(s): Jennifer Hunt <jenhunt@us.ibm.com> * Hendrik Brueckner <brueckner@linux.vnet.ibm.com> * PM functions: * Ursula Braun <ursula.braun@de.ibm.com> */ #define KMSG_COMPONENT "af_iucv" #define pr_fmt(fmt) KMSG_COMPONENT ": " fmt #include <linux/module.h> #include <linux/types.h> #include <linux/list.h> #include <linux/errno.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/slab.h> #include <linux/skbuff.h> #include <linux/init.h> #include <linux/poll.h> #include <net/sock.h> #include <asm/ebcdic.h> #include <asm/cpcmd.h> #include <linux/kmod.h> #include <net/iucv/af_iucv.h> #define VERSION "1.2" static char iucv_userid[80]; static const struct proto_ops iucv_sock_ops; static struct proto iucv_proto = { .name = "AF_IUCV", .owner = THIS_MODULE, .obj_size = sizeof(struct iucv_sock), }; static struct iucv_interface *pr_iucv; /* special AF_IUCV IPRM messages */ static const u8 iprm_shutdown[8] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}; #define TRGCLS_SIZE (sizeof(((struct iucv_message *)0)->class)) /* macros to set/get socket control buffer at correct offset */ #define CB_TAG(skb) ((skb)->cb) /* iucv message tag */ #define CB_TAG_LEN (sizeof(((struct iucv_message *) 0)->tag)) #define CB_TRGCLS(skb) ((skb)->cb + CB_TAG_LEN) /* iucv msg target class */ #define CB_TRGCLS_LEN (TRGCLS_SIZE) #define __iucv_sock_wait(sk, condition, timeo, ret) \ do { \ DEFINE_WAIT(__wait); \ long __timeo = timeo; \ ret = 0; \ prepare_to_wait(sk_sleep(sk), &__wait, TASK_INTERRUPTIBLE); \ while (!(condition)) { \ if (!__timeo) { \ ret = -EAGAIN; \ break; \ } \ if (signal_pending(current)) { \ ret = sock_intr_errno(__timeo); \ break; \ } \ release_sock(sk); \ __timeo = schedule_timeout(__timeo); \ lock_sock(sk); \ ret = sock_error(sk); \ if (ret) \ break; \ } \ finish_wait(sk_sleep(sk), &__wait); \ } while (0) #define iucv_sock_wait(sk, condition, timeo) \ ({ \ int __ret = 0; \ if (!(condition)) \ __iucv_sock_wait(sk, condition, timeo, __ret); \ __ret; \ }) static void iucv_sock_kill(struct sock *sk); static void iucv_sock_close(struct sock *sk); static void iucv_sever_path(struct sock *, int); static int afiucv_hs_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev); static int afiucv_hs_send(struct iucv_message *imsg, struct sock *sock, struct sk_buff *skb, u8 flags); static void afiucv_hs_callback_txnotify(struct sk_buff *, enum iucv_tx_notify); /* Call Back functions */ static void iucv_callback_rx(struct iucv_path *, struct iucv_message *); static void iucv_callback_txdone(struct iucv_path *, struct iucv_message *); static void iucv_callback_connack(struct iucv_path *, u8 ipuser[16]); static int iucv_callback_connreq(struct iucv_path *, u8 ipvmid[8], u8 ipuser[16]); static void iucv_callback_connrej(struct iucv_path *, u8 ipuser[16]); static void iucv_callback_shutdown(struct iucv_path *, u8 ipuser[16]); static struct iucv_sock_list iucv_sk_list = { .lock = __RW_LOCK_UNLOCKED(iucv_sk_list.lock), .autobind_name = ATOMIC_INIT(0) }; static struct iucv_handler af_iucv_handler = { .path_pending = iucv_callback_connreq, .path_complete = iucv_callback_connack, .path_severed = iucv_callback_connrej, .message_pending = iucv_callback_rx, .message_complete = iucv_callback_txdone, .path_quiesced = iucv_callback_shutdown, }; static inline void high_nmcpy(unsigned char *dst, char *src) { memcpy(dst, src, 8); } static inline void low_nmcpy(unsigned char *dst, char *src) { memcpy(&dst[8], src, 8); } static int afiucv_pm_prepare(struct device *dev) { #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_prepare\n"); #endif return 0; } static void afiucv_pm_complete(struct device *dev) { #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_complete\n"); #endif } /** * afiucv_pm_freeze() - Freeze PM callback * @dev: AFIUCV dummy device * * Sever all established IUCV communication pathes */ static int afiucv_pm_freeze(struct device *dev) { struct iucv_sock *iucv; struct sock *sk; int err = 0; #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_freeze\n"); #endif read_lock(&iucv_sk_list.lock); sk_for_each(sk, &iucv_sk_list.head) { iucv = iucv_sk(sk); switch (sk->sk_state) { case IUCV_DISCONN: case IUCV_CLOSING: case IUCV_CONNECTED: iucv_sever_path(sk, 0); break; case IUCV_OPEN: case IUCV_BOUND: case IUCV_LISTEN: case IUCV_CLOSED: default: break; } skb_queue_purge(&iucv->send_skb_q); skb_queue_purge(&iucv->backlog_skb_q); } read_unlock(&iucv_sk_list.lock); return err; } /** * afiucv_pm_restore_thaw() - Thaw and restore PM callback * @dev: AFIUCV dummy device * * socket clean up after freeze */ static int afiucv_pm_restore_thaw(struct device *dev) { struct sock *sk; #ifdef CONFIG_PM_DEBUG printk(KERN_WARNING "afiucv_pm_restore_thaw\n"); #endif read_lock(&iucv_sk_list.lock); sk_for_each(sk, &iucv_sk_list.head) { switch (sk->sk_state) { case IUCV_CONNECTED: sk->sk_err = EPIPE; sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); break; case IUCV_DISCONN: case IUCV_CLOSING: case IUCV_LISTEN: case IUCV_BOUND: case IUCV_OPEN: default: break; } } read_unlock(&iucv_sk_list.lock); return 0; } static const struct dev_pm_ops afiucv_pm_ops = { .prepare = afiucv_pm_prepare, .complete = afiucv_pm_complete, .freeze = afiucv_pm_freeze, .thaw = afiucv_pm_restore_thaw, .restore = afiucv_pm_restore_thaw, }; static struct device_driver af_iucv_driver = { .owner = THIS_MODULE, .name = "afiucv", .bus = NULL, .pm = &afiucv_pm_ops, }; /* dummy device used as trigger for PM functions */ static struct device *af_iucv_dev; /** * iucv_msg_length() - Returns the length of an iucv message. * @msg: Pointer to struct iucv_message, MUST NOT be NULL * * The function returns the length of the specified iucv message @msg of data * stored in a buffer and of data stored in the parameter list (PRMDATA). * * For IUCV_IPRMDATA, AF_IUCV uses the following convention to transport socket * data: * PRMDATA[0..6] socket data (max 7 bytes); * PRMDATA[7] socket data length value (len is 0xff - PRMDATA[7]) * * The socket data length is computed by subtracting the socket data length * value from 0xFF. * If the socket data len is greater 7, then PRMDATA can be used for special * notifications (see iucv_sock_shutdown); and further, * if the socket data len is > 7, the function returns 8. * * Use this function to allocate socket buffers to store iucv message data. */ static inline size_t iucv_msg_length(struct iucv_message *msg) { size_t datalen; if (msg->flags & IUCV_IPRMDATA) { datalen = 0xff - msg->rmmsg[7]; return (datalen < 8) ? datalen : 8; } return msg->length; } /** * iucv_sock_in_state() - check for specific states * @sk: sock structure * @state: first iucv sk state * @state: second iucv sk state * * Returns true if the socket in either in the first or second state. */ static int iucv_sock_in_state(struct sock *sk, int state, int state2) { return (sk->sk_state == state || sk->sk_state == state2); } /** * iucv_below_msglim() - function to check if messages can be sent * @sk: sock structure * * Returns true if the send queue length is lower than the message limit. * Always returns true if the socket is not connected (no iucv path for * checking the message limit). */ static inline int iucv_below_msglim(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); if (sk->sk_state != IUCV_CONNECTED) return 1; if (iucv->transport == AF_IUCV_TRANS_IUCV) return (skb_queue_len(&iucv->send_skb_q) < iucv->path->msglim); else return ((atomic_read(&iucv->msg_sent) < iucv->msglimit_peer) && (atomic_read(&iucv->pendings) <= 0)); } /** * iucv_sock_wake_msglim() - Wake up thread waiting on msg limit */ static void iucv_sock_wake_msglim(struct sock *sk) { struct socket_wq *wq; rcu_read_lock(); wq = rcu_dereference(sk->sk_wq); if (wq_has_sleeper(wq)) wake_up_interruptible_all(&wq->wait); sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT); rcu_read_unlock(); } /** * afiucv_hs_send() - send a message through HiperSockets transport */ static int afiucv_hs_send(struct iucv_message *imsg, struct sock *sock, struct sk_buff *skb, u8 flags) { struct iucv_sock *iucv = iucv_sk(sock); struct af_iucv_trans_hdr *phs_hdr; struct sk_buff *nskb; int err, confirm_recv = 0; memset(skb->head, 0, ETH_HLEN); phs_hdr = (struct af_iucv_trans_hdr *)skb_push(skb, sizeof(struct af_iucv_trans_hdr)); skb_reset_mac_header(skb); skb_reset_network_header(skb); skb_push(skb, ETH_HLEN); skb_reset_mac_header(skb); memset(phs_hdr, 0, sizeof(struct af_iucv_trans_hdr)); phs_hdr->magic = ETH_P_AF_IUCV; phs_hdr->version = 1; phs_hdr->flags = flags; if (flags == AF_IUCV_FLAG_SYN) phs_hdr->window = iucv->msglimit; else if ((flags == AF_IUCV_FLAG_WIN) || !flags) { confirm_recv = atomic_read(&iucv->msg_recv); phs_hdr->window = confirm_recv; if (confirm_recv) phs_hdr->flags = phs_hdr->flags | AF_IUCV_FLAG_WIN; } memcpy(phs_hdr->destUserID, iucv->dst_user_id, 8); memcpy(phs_hdr->destAppName, iucv->dst_name, 8); memcpy(phs_hdr->srcUserID, iucv->src_user_id, 8); memcpy(phs_hdr->srcAppName, iucv->src_name, 8); ASCEBC(phs_hdr->destUserID, sizeof(phs_hdr->destUserID)); ASCEBC(phs_hdr->destAppName, sizeof(phs_hdr->destAppName)); ASCEBC(phs_hdr->srcUserID, sizeof(phs_hdr->srcUserID)); ASCEBC(phs_hdr->srcAppName, sizeof(phs_hdr->srcAppName)); if (imsg) memcpy(&phs_hdr->iucv_hdr, imsg, sizeof(struct iucv_message)); skb->dev = iucv->hs_dev; if (!skb->dev) return -ENODEV; if (!(skb->dev->flags & IFF_UP) || !netif_carrier_ok(skb->dev)) return -ENETDOWN; if (skb->len > skb->dev->mtu) { if (sock->sk_type == SOCK_SEQPACKET) return -EMSGSIZE; else skb_trim(skb, skb->dev->mtu); } skb->protocol = ETH_P_AF_IUCV; nskb = skb_clone(skb, GFP_ATOMIC); if (!nskb) return -ENOMEM; skb_queue_tail(&iucv->send_skb_q, nskb); err = dev_queue_xmit(skb); if (net_xmit_eval(err)) { skb_unlink(nskb, &iucv->send_skb_q); kfree_skb(nskb); } else { atomic_sub(confirm_recv, &iucv->msg_recv); WARN_ON(atomic_read(&iucv->msg_recv) < 0); } return net_xmit_eval(err); } static struct sock *__iucv_get_sock_by_name(char *nm) { struct sock *sk; sk_for_each(sk, &iucv_sk_list.head) if (!memcmp(&iucv_sk(sk)->src_name, nm, 8)) return sk; return NULL; } static void iucv_sock_destruct(struct sock *sk) { skb_queue_purge(&sk->sk_receive_queue); skb_queue_purge(&sk->sk_error_queue); sk_mem_reclaim(sk); if (!sock_flag(sk, SOCK_DEAD)) { pr_err("Attempt to release alive iucv socket %p\n", sk); return; } WARN_ON(atomic_read(&sk->sk_rmem_alloc)); WARN_ON(atomic_read(&sk->sk_wmem_alloc)); WARN_ON(sk->sk_wmem_queued); WARN_ON(sk->sk_forward_alloc); } /* Cleanup Listen */ static void iucv_sock_cleanup_listen(struct sock *parent) { struct sock *sk; /* Close non-accepted connections */ while ((sk = iucv_accept_dequeue(parent, NULL))) { iucv_sock_close(sk); iucv_sock_kill(sk); } parent->sk_state = IUCV_CLOSED; } /* Kill socket (only if zapped and orphaned) */ static void iucv_sock_kill(struct sock *sk) { if (!sock_flag(sk, SOCK_ZAPPED) || sk->sk_socket) return; iucv_sock_unlink(&iucv_sk_list, sk); sock_set_flag(sk, SOCK_DEAD); sock_put(sk); } /* Terminate an IUCV path */ static void iucv_sever_path(struct sock *sk, int with_user_data) { unsigned char user_data[16]; struct iucv_sock *iucv = iucv_sk(sk); struct iucv_path *path = iucv->path; if (iucv->path) { iucv->path = NULL; if (with_user_data) { low_nmcpy(user_data, iucv->src_name); high_nmcpy(user_data, iucv->dst_name); ASCEBC(user_data, sizeof(user_data)); pr_iucv->path_sever(path, user_data); } else pr_iucv->path_sever(path, NULL); iucv_path_free(path); } } /* Send FIN through an IUCV socket for HIPER transport */ static int iucv_send_ctrl(struct sock *sk, u8 flags) { int err = 0; int blen; struct sk_buff *skb; blen = sizeof(struct af_iucv_trans_hdr) + ETH_HLEN; skb = sock_alloc_send_skb(sk, blen, 1, &err); if (skb) { skb_reserve(skb, blen); err = afiucv_hs_send(NULL, sk, skb, flags); } return err; } /* Close an IUCV socket */ static void iucv_sock_close(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); unsigned long timeo; int err = 0; lock_sock(sk); switch (sk->sk_state) { case IUCV_LISTEN: iucv_sock_cleanup_listen(sk); break; case IUCV_CONNECTED: if (iucv->transport == AF_IUCV_TRANS_HIPER) { err = iucv_send_ctrl(sk, AF_IUCV_FLAG_FIN); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } case IUCV_DISCONN: /* fall through */ sk->sk_state = IUCV_CLOSING; sk->sk_state_change(sk); if (!err && !skb_queue_empty(&iucv->send_skb_q)) { if (sock_flag(sk, SOCK_LINGER) && sk->sk_lingertime) timeo = sk->sk_lingertime; else timeo = IUCV_DISCONN_TIMEOUT; iucv_sock_wait(sk, iucv_sock_in_state(sk, IUCV_CLOSED, 0), timeo); } case IUCV_CLOSING: /* fall through */ sk->sk_state = IUCV_CLOSED; sk->sk_state_change(sk); sk->sk_err = ECONNRESET; sk->sk_state_change(sk); skb_queue_purge(&iucv->send_skb_q); skb_queue_purge(&iucv->backlog_skb_q); default: /* fall through */ iucv_sever_path(sk, 1); } if (iucv->hs_dev) { dev_put(iucv->hs_dev); iucv->hs_dev = NULL; sk->sk_bound_dev_if = 0; } /* mark socket for deletion by iucv_sock_kill() */ sock_set_flag(sk, SOCK_ZAPPED); release_sock(sk); } static void iucv_sock_init(struct sock *sk, struct sock *parent) { if (parent) sk->sk_type = parent->sk_type; } static struct sock *iucv_sock_alloc(struct socket *sock, int proto, gfp_t prio) { struct sock *sk; struct iucv_sock *iucv; sk = sk_alloc(&init_net, PF_IUCV, prio, &iucv_proto); if (!sk) return NULL; iucv = iucv_sk(sk); sock_init_data(sock, sk); INIT_LIST_HEAD(&iucv->accept_q); spin_lock_init(&iucv->accept_q_lock); skb_queue_head_init(&iucv->send_skb_q); INIT_LIST_HEAD(&iucv->message_q.list); spin_lock_init(&iucv->message_q.lock); skb_queue_head_init(&iucv->backlog_skb_q); iucv->send_tag = 0; atomic_set(&iucv->pendings, 0); iucv->flags = 0; iucv->msglimit = 0; atomic_set(&iucv->msg_sent, 0); atomic_set(&iucv->msg_recv, 0); iucv->path = NULL; iucv->sk_txnotify = afiucv_hs_callback_txnotify; memset(&iucv->src_user_id , 0, 32); if (pr_iucv) iucv->transport = AF_IUCV_TRANS_IUCV; else iucv->transport = AF_IUCV_TRANS_HIPER; sk->sk_destruct = iucv_sock_destruct; sk->sk_sndtimeo = IUCV_CONN_TIMEOUT; sk->sk_allocation = GFP_DMA; sock_reset_flag(sk, SOCK_ZAPPED); sk->sk_protocol = proto; sk->sk_state = IUCV_OPEN; iucv_sock_link(&iucv_sk_list, sk); return sk; } /* Create an IUCV socket */ static int iucv_sock_create(struct net *net, struct socket *sock, int protocol, int kern) { struct sock *sk; if (protocol && protocol != PF_IUCV) return -EPROTONOSUPPORT; sock->state = SS_UNCONNECTED; switch (sock->type) { case SOCK_STREAM: sock->ops = &iucv_sock_ops; break; case SOCK_SEQPACKET: /* currently, proto ops can handle both sk types */ sock->ops = &iucv_sock_ops; break; default: return -ESOCKTNOSUPPORT; } sk = iucv_sock_alloc(sock, protocol, GFP_KERNEL); if (!sk) return -ENOMEM; iucv_sock_init(sk, NULL); return 0; } void iucv_sock_link(struct iucv_sock_list *l, struct sock *sk) { write_lock_bh(&l->lock); sk_add_node(sk, &l->head); write_unlock_bh(&l->lock); } void iucv_sock_unlink(struct iucv_sock_list *l, struct sock *sk) { write_lock_bh(&l->lock); sk_del_node_init(sk); write_unlock_bh(&l->lock); } void iucv_accept_enqueue(struct sock *parent, struct sock *sk) { unsigned long flags; struct iucv_sock *par = iucv_sk(parent); sock_hold(sk); spin_lock_irqsave(&par->accept_q_lock, flags); list_add_tail(&iucv_sk(sk)->accept_q, &par->accept_q); spin_unlock_irqrestore(&par->accept_q_lock, flags); iucv_sk(sk)->parent = parent; sk_acceptq_added(parent); } void iucv_accept_unlink(struct sock *sk) { unsigned long flags; struct iucv_sock *par = iucv_sk(iucv_sk(sk)->parent); spin_lock_irqsave(&par->accept_q_lock, flags); list_del_init(&iucv_sk(sk)->accept_q); spin_unlock_irqrestore(&par->accept_q_lock, flags); sk_acceptq_removed(iucv_sk(sk)->parent); iucv_sk(sk)->parent = NULL; sock_put(sk); } struct sock *iucv_accept_dequeue(struct sock *parent, struct socket *newsock) { struct iucv_sock *isk, *n; struct sock *sk; list_for_each_entry_safe(isk, n, &iucv_sk(parent)->accept_q, accept_q) { sk = (struct sock *) isk; lock_sock(sk); if (sk->sk_state == IUCV_CLOSED) { iucv_accept_unlink(sk); release_sock(sk); continue; } if (sk->sk_state == IUCV_CONNECTED || sk->sk_state == IUCV_DISCONN || !newsock) { iucv_accept_unlink(sk); if (newsock) sock_graft(sk, newsock); release_sock(sk); return sk; } release_sock(sk); } return NULL; } /* Bind an unbound socket */ static int iucv_sock_bind(struct socket *sock, struct sockaddr *addr, int addr_len) { struct sockaddr_iucv *sa = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv; int err = 0; struct net_device *dev; char uid[9]; /* Verify the input sockaddr */ if (!addr || addr->sa_family != AF_IUCV) return -EINVAL; lock_sock(sk); if (sk->sk_state != IUCV_OPEN) { err = -EBADFD; goto done; } write_lock_bh(&iucv_sk_list.lock); iucv = iucv_sk(sk); if (__iucv_get_sock_by_name(sa->siucv_name)) { err = -EADDRINUSE; goto done_unlock; } if (iucv->path) goto done_unlock; /* Bind the socket */ if (pr_iucv) if (!memcmp(sa->siucv_user_id, iucv_userid, 8)) goto vm_bind; /* VM IUCV transport */ /* try hiper transport */ memcpy(uid, sa->siucv_user_id, sizeof(uid)); ASCEBC(uid, 8); rcu_read_lock(); for_each_netdev_rcu(&init_net, dev) { if (!memcmp(dev->perm_addr, uid, 8)) { memcpy(iucv->src_name, sa->siucv_name, 8); memcpy(iucv->src_user_id, sa->siucv_user_id, 8); sk->sk_bound_dev_if = dev->ifindex; iucv->hs_dev = dev; dev_hold(dev); sk->sk_state = IUCV_BOUND; iucv->transport = AF_IUCV_TRANS_HIPER; if (!iucv->msglimit) iucv->msglimit = IUCV_HIPER_MSGLIM_DEFAULT; rcu_read_unlock(); goto done_unlock; } } rcu_read_unlock(); vm_bind: if (pr_iucv) { /* use local userid for backward compat */ memcpy(iucv->src_name, sa->siucv_name, 8); memcpy(iucv->src_user_id, iucv_userid, 8); sk->sk_state = IUCV_BOUND; iucv->transport = AF_IUCV_TRANS_IUCV; if (!iucv->msglimit) iucv->msglimit = IUCV_QUEUELEN_DEFAULT; goto done_unlock; } /* found no dev to bind */ err = -ENODEV; done_unlock: /* Release the socket list lock */ write_unlock_bh(&iucv_sk_list.lock); done: release_sock(sk); return err; } /* Automatically bind an unbound socket */ static int iucv_sock_autobind(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); char name[12]; int err = 0; if (unlikely(!pr_iucv)) return -EPROTO; memcpy(iucv->src_user_id, iucv_userid, 8); write_lock_bh(&iucv_sk_list.lock); sprintf(name, "%08x", atomic_inc_return(&iucv_sk_list.autobind_name)); while (__iucv_get_sock_by_name(name)) { sprintf(name, "%08x", atomic_inc_return(&iucv_sk_list.autobind_name)); } write_unlock_bh(&iucv_sk_list.lock); memcpy(&iucv->src_name, name, 8); if (!iucv->msglimit) iucv->msglimit = IUCV_QUEUELEN_DEFAULT; return err; } static int afiucv_path_connect(struct socket *sock, struct sockaddr *addr) { struct sockaddr_iucv *sa = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); unsigned char user_data[16]; int err; high_nmcpy(user_data, sa->siucv_name); low_nmcpy(user_data, iucv->src_name); ASCEBC(user_data, sizeof(user_data)); /* Create path. */ iucv->path = iucv_path_alloc(iucv->msglimit, IUCV_IPRMDATA, GFP_KERNEL); if (!iucv->path) { err = -ENOMEM; goto done; } err = pr_iucv->path_connect(iucv->path, &af_iucv_handler, sa->siucv_user_id, NULL, user_data, sk); if (err) { iucv_path_free(iucv->path); iucv->path = NULL; switch (err) { case 0x0b: /* Target communicator is not logged on */ err = -ENETUNREACH; break; case 0x0d: /* Max connections for this guest exceeded */ case 0x0e: /* Max connections for target guest exceeded */ err = -EAGAIN; break; case 0x0f: /* Missing IUCV authorization */ err = -EACCES; break; default: err = -ECONNREFUSED; break; } } done: return err; } /* Connect an unconnected socket */ static int iucv_sock_connect(struct socket *sock, struct sockaddr *addr, int alen, int flags) { struct sockaddr_iucv *sa = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); int err; if (addr->sa_family != AF_IUCV || alen < sizeof(struct sockaddr_iucv)) return -EINVAL; if (sk->sk_state != IUCV_OPEN && sk->sk_state != IUCV_BOUND) return -EBADFD; if (sk->sk_state == IUCV_OPEN && iucv->transport == AF_IUCV_TRANS_HIPER) return -EBADFD; /* explicit bind required */ if (sk->sk_type != SOCK_STREAM && sk->sk_type != SOCK_SEQPACKET) return -EINVAL; if (sk->sk_state == IUCV_OPEN) { err = iucv_sock_autobind(sk); if (unlikely(err)) return err; } lock_sock(sk); /* Set the destination information */ memcpy(iucv->dst_user_id, sa->siucv_user_id, 8); memcpy(iucv->dst_name, sa->siucv_name, 8); if (iucv->transport == AF_IUCV_TRANS_HIPER) err = iucv_send_ctrl(sock->sk, AF_IUCV_FLAG_SYN); else err = afiucv_path_connect(sock, addr); if (err) goto done; if (sk->sk_state != IUCV_CONNECTED) err = iucv_sock_wait(sk, iucv_sock_in_state(sk, IUCV_CONNECTED, IUCV_DISCONN), sock_sndtimeo(sk, flags & O_NONBLOCK)); if (sk->sk_state == IUCV_DISCONN || sk->sk_state == IUCV_CLOSED) err = -ECONNREFUSED; if (err && iucv->transport == AF_IUCV_TRANS_IUCV) iucv_sever_path(sk, 0); done: release_sock(sk); return err; } /* Move a socket into listening state. */ static int iucv_sock_listen(struct socket *sock, int backlog) { struct sock *sk = sock->sk; int err; lock_sock(sk); err = -EINVAL; if (sk->sk_state != IUCV_BOUND) goto done; if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET) goto done; sk->sk_max_ack_backlog = backlog; sk->sk_ack_backlog = 0; sk->sk_state = IUCV_LISTEN; err = 0; done: release_sock(sk); return err; } /* Accept a pending connection */ static int iucv_sock_accept(struct socket *sock, struct socket *newsock, int flags) { DECLARE_WAITQUEUE(wait, current); struct sock *sk = sock->sk, *nsk; long timeo; int err = 0; lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != IUCV_LISTEN) { err = -EBADFD; goto done; } timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK); /* Wait for an incoming connection */ add_wait_queue_exclusive(sk_sleep(sk), &wait); while (!(nsk = iucv_accept_dequeue(sk, newsock))) { set_current_state(TASK_INTERRUPTIBLE); if (!timeo) { err = -EAGAIN; break; } release_sock(sk); timeo = schedule_timeout(timeo); lock_sock_nested(sk, SINGLE_DEPTH_NESTING); if (sk->sk_state != IUCV_LISTEN) { err = -EBADFD; break; } if (signal_pending(current)) { err = sock_intr_errno(timeo); break; } } set_current_state(TASK_RUNNING); remove_wait_queue(sk_sleep(sk), &wait); if (err) goto done; newsock->state = SS_CONNECTED; done: release_sock(sk); return err; } static int iucv_sock_getname(struct socket *sock, struct sockaddr *addr, int *len, int peer) { struct sockaddr_iucv *siucv = (struct sockaddr_iucv *) addr; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); addr->sa_family = AF_IUCV; *len = sizeof(struct sockaddr_iucv); if (peer) { memcpy(siucv->siucv_user_id, iucv->dst_user_id, 8); memcpy(siucv->siucv_name, iucv->dst_name, 8); } else { memcpy(siucv->siucv_user_id, iucv->src_user_id, 8); memcpy(siucv->siucv_name, iucv->src_name, 8); } memset(&siucv->siucv_port, 0, sizeof(siucv->siucv_port)); memset(&siucv->siucv_addr, 0, sizeof(siucv->siucv_addr)); memset(&siucv->siucv_nodeid, 0, sizeof(siucv->siucv_nodeid)); return 0; } /** * iucv_send_iprm() - Send socket data in parameter list of an iucv message. * @path: IUCV path * @msg: Pointer to a struct iucv_message * @skb: The socket data to send, skb->len MUST BE <= 7 * * Send the socket data in the parameter list in the iucv message * (IUCV_IPRMDATA). The socket data is stored at index 0 to 6 in the parameter * list and the socket data len at index 7 (last byte). * See also iucv_msg_length(). * * Returns the error code from the iucv_message_send() call. */ static int iucv_send_iprm(struct iucv_path *path, struct iucv_message *msg, struct sk_buff *skb) { u8 prmdata[8]; memcpy(prmdata, (void *) skb->data, skb->len); prmdata[7] = 0xff - (u8) skb->len; return pr_iucv->message_send(path, msg, IUCV_IPRMDATA, 0, (void *) prmdata, 8); } static int iucv_sock_sendmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); struct sk_buff *skb; struct iucv_message txmsg; struct cmsghdr *cmsg; int cmsg_done; long timeo; char user_id[9]; char appl_id[9]; int err; int noblock = msg->msg_flags & MSG_DONTWAIT; err = sock_error(sk); if (err) return err; if (msg->msg_flags & MSG_OOB) return -EOPNOTSUPP; /* SOCK_SEQPACKET: we do not support segmented records */ if (sk->sk_type == SOCK_SEQPACKET && !(msg->msg_flags & MSG_EOR)) return -EOPNOTSUPP; lock_sock(sk); if (sk->sk_shutdown & SEND_SHUTDOWN) { err = -EPIPE; goto out; } /* Return if the socket is not in connected state */ if (sk->sk_state != IUCV_CONNECTED) { err = -ENOTCONN; goto out; } /* initialize defaults */ cmsg_done = 0; /* check for duplicate headers */ txmsg.class = 0; /* iterate over control messages */ for (cmsg = CMSG_FIRSTHDR(msg); cmsg; cmsg = CMSG_NXTHDR(msg, cmsg)) { if (!CMSG_OK(msg, cmsg)) { err = -EINVAL; goto out; } if (cmsg->cmsg_level != SOL_IUCV) continue; if (cmsg->cmsg_type & cmsg_done) { err = -EINVAL; goto out; } cmsg_done |= cmsg->cmsg_type; switch (cmsg->cmsg_type) { case SCM_IUCV_TRGCLS: if (cmsg->cmsg_len != CMSG_LEN(TRGCLS_SIZE)) { err = -EINVAL; goto out; } /* set iucv message target class */ memcpy(&txmsg.class, (void *) CMSG_DATA(cmsg), TRGCLS_SIZE); break; default: err = -EINVAL; goto out; break; } } /* allocate one skb for each iucv message: * this is fine for SOCK_SEQPACKET (unless we want to support * segmented records using the MSG_EOR flag), but * for SOCK_STREAM we might want to improve it in future */ if (iucv->transport == AF_IUCV_TRANS_HIPER) skb = sock_alloc_send_skb(sk, len + sizeof(struct af_iucv_trans_hdr) + ETH_HLEN, noblock, &err); else skb = sock_alloc_send_skb(sk, len, noblock, &err); if (!skb) { err = -ENOMEM; goto out; } if (iucv->transport == AF_IUCV_TRANS_HIPER) skb_reserve(skb, sizeof(struct af_iucv_trans_hdr) + ETH_HLEN); if (memcpy_fromiovec(skb_put(skb, len), msg->msg_iov, len)) { err = -EFAULT; goto fail; } /* wait if outstanding messages for iucv path has reached */ timeo = sock_sndtimeo(sk, noblock); err = iucv_sock_wait(sk, iucv_below_msglim(sk), timeo); if (err) goto fail; /* return -ECONNRESET if the socket is no longer connected */ if (sk->sk_state != IUCV_CONNECTED) { err = -ECONNRESET; goto fail; } /* increment and save iucv message tag for msg_completion cbk */ txmsg.tag = iucv->send_tag++; memcpy(CB_TAG(skb), &txmsg.tag, CB_TAG_LEN); if (iucv->transport == AF_IUCV_TRANS_HIPER) { atomic_inc(&iucv->msg_sent); err = afiucv_hs_send(&txmsg, sk, skb, 0); if (err) { atomic_dec(&iucv->msg_sent); goto fail; } goto release; } skb_queue_tail(&iucv->send_skb_q, skb); if (((iucv->path->flags & IUCV_IPRMDATA) & iucv->flags) && skb->len <= 7) { err = iucv_send_iprm(iucv->path, &txmsg, skb); /* on success: there is no message_complete callback * for an IPRMDATA msg; remove skb from send queue */ if (err == 0) { skb_unlink(skb, &iucv->send_skb_q); kfree_skb(skb); } /* this error should never happen since the * IUCV_IPRMDATA path flag is set... sever path */ if (err == 0x15) { pr_iucv->path_sever(iucv->path, NULL); skb_unlink(skb, &iucv->send_skb_q); err = -EPIPE; goto fail; } } else err = pr_iucv->message_send(iucv->path, &txmsg, 0, 0, (void *) skb->data, skb->len); if (err) { if (err == 3) { user_id[8] = 0; memcpy(user_id, iucv->dst_user_id, 8); appl_id[8] = 0; memcpy(appl_id, iucv->dst_name, 8); pr_err("Application %s on z/VM guest %s" " exceeds message limit\n", appl_id, user_id); err = -EAGAIN; } else err = -EPIPE; skb_unlink(skb, &iucv->send_skb_q); goto fail; } release: release_sock(sk); return len; fail: kfree_skb(skb); out: release_sock(sk); return err; } /* iucv_fragment_skb() - Fragment a single IUCV message into multiple skb's * * Locking: must be called with message_q.lock held */ static int iucv_fragment_skb(struct sock *sk, struct sk_buff *skb, int len) { int dataleft, size, copied = 0; struct sk_buff *nskb; dataleft = len; while (dataleft) { if (dataleft >= sk->sk_rcvbuf / 4) size = sk->sk_rcvbuf / 4; else size = dataleft; nskb = alloc_skb(size, GFP_ATOMIC | GFP_DMA); if (!nskb) return -ENOMEM; /* copy target class to control buffer of new skb */ memcpy(CB_TRGCLS(nskb), CB_TRGCLS(skb), CB_TRGCLS_LEN); /* copy data fragment */ memcpy(nskb->data, skb->data + copied, size); copied += size; dataleft -= size; skb_reset_transport_header(nskb); skb_reset_network_header(nskb); nskb->len = size; skb_queue_tail(&iucv_sk(sk)->backlog_skb_q, nskb); } return 0; } /* iucv_process_message() - Receive a single outstanding IUCV message * * Locking: must be called with message_q.lock held */ static void iucv_process_message(struct sock *sk, struct sk_buff *skb, struct iucv_path *path, struct iucv_message *msg) { int rc; unsigned int len; len = iucv_msg_length(msg); /* store msg target class in the second 4 bytes of skb ctrl buffer */ /* Note: the first 4 bytes are reserved for msg tag */ memcpy(CB_TRGCLS(skb), &msg->class, CB_TRGCLS_LEN); /* check for special IPRM messages (e.g. iucv_sock_shutdown) */ if ((msg->flags & IUCV_IPRMDATA) && len > 7) { if (memcmp(msg->rmmsg, iprm_shutdown, 8) == 0) { skb->data = NULL; skb->len = 0; } } else { rc = pr_iucv->message_receive(path, msg, msg->flags & IUCV_IPRMDATA, skb->data, len, NULL); if (rc) { kfree_skb(skb); return; } /* we need to fragment iucv messages for SOCK_STREAM only; * for SOCK_SEQPACKET, it is only relevant if we support * record segmentation using MSG_EOR (see also recvmsg()) */ if (sk->sk_type == SOCK_STREAM && skb->truesize >= sk->sk_rcvbuf / 4) { rc = iucv_fragment_skb(sk, skb, len); kfree_skb(skb); skb = NULL; if (rc) { pr_iucv->path_sever(path, NULL); return; } skb = skb_dequeue(&iucv_sk(sk)->backlog_skb_q); } else { skb_reset_transport_header(skb); skb_reset_network_header(skb); skb->len = len; } } if (sock_queue_rcv_skb(sk, skb)) skb_queue_head(&iucv_sk(sk)->backlog_skb_q, skb); } /* iucv_process_message_q() - Process outstanding IUCV messages * * Locking: must be called with message_q.lock held */ static void iucv_process_message_q(struct sock *sk) { struct iucv_sock *iucv = iucv_sk(sk); struct sk_buff *skb; struct sock_msg_q *p, *n; list_for_each_entry_safe(p, n, &iucv->message_q.list, list) { skb = alloc_skb(iucv_msg_length(&p->msg), GFP_ATOMIC | GFP_DMA); if (!skb) break; iucv_process_message(sk, skb, p->path, &p->msg); list_del(&p->list); kfree(p); if (!skb_queue_empty(&iucv->backlog_skb_q)) break; } } static int iucv_sock_recvmsg(struct kiocb *iocb, struct socket *sock, struct msghdr *msg, size_t len, int flags) { int noblock = flags & MSG_DONTWAIT; struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); unsigned int copied, rlen; struct sk_buff *skb, *rskb, *cskb; int err = 0; if ((sk->sk_state == IUCV_DISCONN) && skb_queue_empty(&iucv->backlog_skb_q) && skb_queue_empty(&sk->sk_receive_queue) && list_empty(&iucv->message_q.list)) return 0; if (flags & (MSG_OOB)) return -EOPNOTSUPP; /* receive/dequeue next skb: * the function understands MSG_PEEK and, thus, does not dequeue skb */ skb = skb_recv_datagram(sk, flags, noblock, &err); if (!skb) { if (sk->sk_shutdown & RCV_SHUTDOWN) return 0; return err; } rlen = skb->len; /* real length of skb */ copied = min_t(unsigned int, rlen, len); if (!rlen) sk->sk_shutdown = sk->sk_shutdown | RCV_SHUTDOWN; cskb = skb; if (skb_copy_datagram_iovec(cskb, 0, msg->msg_iov, copied)) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return -EFAULT; } /* SOCK_SEQPACKET: set MSG_TRUNC if recv buf size is too small */ if (sk->sk_type == SOCK_SEQPACKET) { if (copied < rlen) msg->msg_flags |= MSG_TRUNC; /* each iucv message contains a complete record */ msg->msg_flags |= MSG_EOR; } /* create control message to store iucv msg target class: * get the trgcls from the control buffer of the skb due to * fragmentation of original iucv message. */ err = put_cmsg(msg, SOL_IUCV, SCM_IUCV_TRGCLS, CB_TRGCLS_LEN, CB_TRGCLS(skb)); if (err) { if (!(flags & MSG_PEEK)) skb_queue_head(&sk->sk_receive_queue, skb); return err; } /* Mark read part of skb as used */ if (!(flags & MSG_PEEK)) { /* SOCK_STREAM: re-queue skb if it contains unreceived data */ if (sk->sk_type == SOCK_STREAM) { skb_pull(skb, copied); if (skb->len) { skb_queue_head(&sk->sk_receive_queue, skb); goto done; } } kfree_skb(skb); if (iucv->transport == AF_IUCV_TRANS_HIPER) { atomic_inc(&iucv->msg_recv); if (atomic_read(&iucv->msg_recv) > iucv->msglimit) { WARN_ON(1); iucv_sock_close(sk); return -EFAULT; } } /* Queue backlog skbs */ spin_lock_bh(&iucv->message_q.lock); rskb = skb_dequeue(&iucv->backlog_skb_q); while (rskb) { if (sock_queue_rcv_skb(sk, rskb)) { skb_queue_head(&iucv->backlog_skb_q, rskb); break; } else { rskb = skb_dequeue(&iucv->backlog_skb_q); } } if (skb_queue_empty(&iucv->backlog_skb_q)) { if (!list_empty(&iucv->message_q.list)) iucv_process_message_q(sk); if (atomic_read(&iucv->msg_recv) >= iucv->msglimit / 2) { err = iucv_send_ctrl(sk, AF_IUCV_FLAG_WIN); if (err) { sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } } } spin_unlock_bh(&iucv->message_q.lock); } done: /* SOCK_SEQPACKET: return real length if MSG_TRUNC is set */ if (sk->sk_type == SOCK_SEQPACKET && (flags & MSG_TRUNC)) copied = rlen; return copied; } static inline unsigned int iucv_accept_poll(struct sock *parent) { struct iucv_sock *isk, *n; struct sock *sk; list_for_each_entry_safe(isk, n, &iucv_sk(parent)->accept_q, accept_q) { sk = (struct sock *) isk; if (sk->sk_state == IUCV_CONNECTED) return POLLIN | POLLRDNORM; } return 0; } unsigned int iucv_sock_poll(struct file *file, struct socket *sock, poll_table *wait) { struct sock *sk = sock->sk; unsigned int mask = 0; sock_poll_wait(file, sk_sleep(sk), wait); if (sk->sk_state == IUCV_LISTEN) return iucv_accept_poll(sk); if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) mask |= POLLERR; if (sk->sk_shutdown & RCV_SHUTDOWN) mask |= POLLRDHUP; if (sk->sk_shutdown == SHUTDOWN_MASK) mask |= POLLHUP; if (!skb_queue_empty(&sk->sk_receive_queue) || (sk->sk_shutdown & RCV_SHUTDOWN)) mask |= POLLIN | POLLRDNORM; if (sk->sk_state == IUCV_CLOSED) mask |= POLLHUP; if (sk->sk_state == IUCV_DISCONN) mask |= POLLIN; if (sock_writeable(sk) && iucv_below_msglim(sk)) mask |= POLLOUT | POLLWRNORM | POLLWRBAND; else set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags); return mask; } static int iucv_sock_shutdown(struct socket *sock, int how) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); struct iucv_message txmsg; int err = 0; how++; if ((how & ~SHUTDOWN_MASK) || !how) return -EINVAL; lock_sock(sk); switch (sk->sk_state) { case IUCV_LISTEN: case IUCV_DISCONN: case IUCV_CLOSING: case IUCV_CLOSED: err = -ENOTCONN; goto fail; default: break; } if (how == SEND_SHUTDOWN || how == SHUTDOWN_MASK) { if (iucv->transport == AF_IUCV_TRANS_IUCV) { txmsg.class = 0; txmsg.tag = 0; err = pr_iucv->message_send(iucv->path, &txmsg, IUCV_IPRMDATA, 0, (void *) iprm_shutdown, 8); if (err) { switch (err) { case 1: err = -ENOTCONN; break; case 2: err = -ECONNRESET; break; default: err = -ENOTCONN; break; } } } else iucv_send_ctrl(sk, AF_IUCV_FLAG_SHT); } sk->sk_shutdown |= how; if (how == RCV_SHUTDOWN || how == SHUTDOWN_MASK) { if (iucv->transport == AF_IUCV_TRANS_IUCV) { err = pr_iucv->path_quiesce(iucv->path, NULL); if (err) err = -ENOTCONN; /* skb_queue_purge(&sk->sk_receive_queue); */ } skb_queue_purge(&sk->sk_receive_queue); } /* Wake up anyone sleeping in poll */ sk->sk_state_change(sk); fail: release_sock(sk); return err; } static int iucv_sock_release(struct socket *sock) { struct sock *sk = sock->sk; int err = 0; if (!sk) return 0; iucv_sock_close(sk); sock_orphan(sk); iucv_sock_kill(sk); return err; } /* getsockopt and setsockopt */ static int iucv_sock_setsockopt(struct socket *sock, int level, int optname, char __user *optval, unsigned int optlen) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); int val; int rc; if (level != SOL_IUCV) return -ENOPROTOOPT; if (optlen < sizeof(int)) return -EINVAL; if (get_user(val, (int __user *) optval)) return -EFAULT; rc = 0; lock_sock(sk); switch (optname) { case SO_IPRMDATA_MSG: if (val) iucv->flags |= IUCV_IPRMDATA; else iucv->flags &= ~IUCV_IPRMDATA; break; case SO_MSGLIMIT: switch (sk->sk_state) { case IUCV_OPEN: case IUCV_BOUND: if (val < 1 || val > (u16)(~0)) rc = -EINVAL; else iucv->msglimit = val; break; default: rc = -EINVAL; break; } break; default: rc = -ENOPROTOOPT; break; } release_sock(sk); return rc; } static int iucv_sock_getsockopt(struct socket *sock, int level, int optname, char __user *optval, int __user *optlen) { struct sock *sk = sock->sk; struct iucv_sock *iucv = iucv_sk(sk); unsigned int val; int len; if (level != SOL_IUCV) return -ENOPROTOOPT; if (get_user(len, optlen)) return -EFAULT; if (len < 0) return -EINVAL; len = min_t(unsigned int, len, sizeof(int)); switch (optname) { case SO_IPRMDATA_MSG: val = (iucv->flags & IUCV_IPRMDATA) ? 1 : 0; break; case SO_MSGLIMIT: lock_sock(sk); val = (iucv->path != NULL) ? iucv->path->msglim /* connected */ : iucv->msglimit; /* default */ release_sock(sk); break; case SO_MSGSIZE: if (sk->sk_state == IUCV_OPEN) return -EBADFD; val = (iucv->hs_dev) ? iucv->hs_dev->mtu - sizeof(struct af_iucv_trans_hdr) - ETH_HLEN : 0x7fffffff; break; default: return -ENOPROTOOPT; } if (put_user(len, optlen)) return -EFAULT; if (copy_to_user(optval, &val, len)) return -EFAULT; return 0; } /* Callback wrappers - called from iucv base support */ static int iucv_callback_connreq(struct iucv_path *path, u8 ipvmid[8], u8 ipuser[16]) { unsigned char user_data[16]; unsigned char nuser_data[16]; unsigned char src_name[8]; struct sock *sk, *nsk; struct iucv_sock *iucv, *niucv; int err; memcpy(src_name, ipuser, 8); EBCASC(src_name, 8); /* Find out if this path belongs to af_iucv. */ read_lock(&iucv_sk_list.lock); iucv = NULL; sk = NULL; sk_for_each(sk, &iucv_sk_list.head) if (sk->sk_state == IUCV_LISTEN && !memcmp(&iucv_sk(sk)->src_name, src_name, 8)) { /* * Found a listening socket with * src_name == ipuser[0-7]. */ iucv = iucv_sk(sk); break; } read_unlock(&iucv_sk_list.lock); if (!iucv) /* No socket found, not one of our paths. */ return -EINVAL; bh_lock_sock(sk); /* Check if parent socket is listening */ low_nmcpy(user_data, iucv->src_name); high_nmcpy(user_data, iucv->dst_name); ASCEBC(user_data, sizeof(user_data)); if (sk->sk_state != IUCV_LISTEN) { err = pr_iucv->path_sever(path, user_data); iucv_path_free(path); goto fail; } /* Check for backlog size */ if (sk_acceptq_is_full(sk)) { err = pr_iucv->path_sever(path, user_data); iucv_path_free(path); goto fail; } /* Create the new socket */ nsk = iucv_sock_alloc(NULL, sk->sk_type, GFP_ATOMIC); if (!nsk) { err = pr_iucv->path_sever(path, user_data); iucv_path_free(path); goto fail; } niucv = iucv_sk(nsk); iucv_sock_init(nsk, sk); /* Set the new iucv_sock */ memcpy(niucv->dst_name, ipuser + 8, 8); EBCASC(niucv->dst_name, 8); memcpy(niucv->dst_user_id, ipvmid, 8); memcpy(niucv->src_name, iucv->src_name, 8); memcpy(niucv->src_user_id, iucv->src_user_id, 8); niucv->path = path; /* Call iucv_accept */ high_nmcpy(nuser_data, ipuser + 8); memcpy(nuser_data + 8, niucv->src_name, 8); ASCEBC(nuser_data + 8, 8); /* set message limit for path based on msglimit of accepting socket */ niucv->msglimit = iucv->msglimit; path->msglim = iucv->msglimit; err = pr_iucv->path_accept(path, &af_iucv_handler, nuser_data, nsk); if (err) { iucv_sever_path(nsk, 1); iucv_sock_kill(nsk); goto fail; } iucv_accept_enqueue(sk, nsk); /* Wake up accept */ nsk->sk_state = IUCV_CONNECTED; sk->sk_data_ready(sk, 1); err = 0; fail: bh_unlock_sock(sk); return 0; } static void iucv_callback_connack(struct iucv_path *path, u8 ipuser[16]) { struct sock *sk = path->private; sk->sk_state = IUCV_CONNECTED; sk->sk_state_change(sk); } static void iucv_callback_rx(struct iucv_path *path, struct iucv_message *msg) { struct sock *sk = path->private; struct iucv_sock *iucv = iucv_sk(sk); struct sk_buff *skb; struct sock_msg_q *save_msg; int len; if (sk->sk_shutdown & RCV_SHUTDOWN) { pr_iucv->message_reject(path, msg); return; } spin_lock(&iucv->message_q.lock); if (!list_empty(&iucv->message_q.list) || !skb_queue_empty(&iucv->backlog_skb_q)) goto save_message; len = atomic_read(&sk->sk_rmem_alloc); len += SKB_TRUESIZE(iucv_msg_length(msg)); if (len > sk->sk_rcvbuf) goto save_message; skb = alloc_skb(iucv_msg_length(msg), GFP_ATOMIC | GFP_DMA); if (!skb) goto save_message; iucv_process_message(sk, skb, path, msg); goto out_unlock; save_message: save_msg = kzalloc(sizeof(struct sock_msg_q), GFP_ATOMIC | GFP_DMA); if (!save_msg) goto out_unlock; save_msg->path = path; save_msg->msg = *msg; list_add_tail(&save_msg->list, &iucv->message_q.list); out_unlock: spin_unlock(&iucv->message_q.lock); } static void iucv_callback_txdone(struct iucv_path *path, struct iucv_message *msg) { struct sock *sk = path->private; struct sk_buff *this = NULL; struct sk_buff_head *list = &iucv_sk(sk)->send_skb_q; struct sk_buff *list_skb = list->next; unsigned long flags; bh_lock_sock(sk); if (!skb_queue_empty(list)) { spin_lock_irqsave(&list->lock, flags); while (list_skb != (struct sk_buff *)list) { if (!memcmp(&msg->tag, CB_TAG(list_skb), CB_TAG_LEN)) { this = list_skb; break; } list_skb = list_skb->next; } if (this) __skb_unlink(this, list); spin_unlock_irqrestore(&list->lock, flags); if (this) { kfree_skb(this); /* wake up any process waiting for sending */ iucv_sock_wake_msglim(sk); } } if (sk->sk_state == IUCV_CLOSING) { if (skb_queue_empty(&iucv_sk(sk)->send_skb_q)) { sk->sk_state = IUCV_CLOSED; sk->sk_state_change(sk); } } bh_unlock_sock(sk); } static void iucv_callback_connrej(struct iucv_path *path, u8 ipuser[16]) { struct sock *sk = path->private; if (sk->sk_state == IUCV_CLOSED) return; bh_lock_sock(sk); iucv_sever_path(sk, 1); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); bh_unlock_sock(sk); } /* called if the other communication side shuts down its RECV direction; * in turn, the callback sets SEND_SHUTDOWN to disable sending of data. */ static void iucv_callback_shutdown(struct iucv_path *path, u8 ipuser[16]) { struct sock *sk = path->private; bh_lock_sock(sk); if (sk->sk_state != IUCV_CLOSED) { sk->sk_shutdown |= SEND_SHUTDOWN; sk->sk_state_change(sk); } bh_unlock_sock(sk); } /***************** HiperSockets transport callbacks ********************/ static void afiucv_swap_src_dest(struct sk_buff *skb) { struct af_iucv_trans_hdr *trans_hdr = (struct af_iucv_trans_hdr *)skb->data; char tmpID[8]; char tmpName[8]; ASCEBC(trans_hdr->destUserID, sizeof(trans_hdr->destUserID)); ASCEBC(trans_hdr->destAppName, sizeof(trans_hdr->destAppName)); ASCEBC(trans_hdr->srcUserID, sizeof(trans_hdr->srcUserID)); ASCEBC(trans_hdr->srcAppName, sizeof(trans_hdr->srcAppName)); memcpy(tmpID, trans_hdr->srcUserID, 8); memcpy(tmpName, trans_hdr->srcAppName, 8); memcpy(trans_hdr->srcUserID, trans_hdr->destUserID, 8); memcpy(trans_hdr->srcAppName, trans_hdr->destAppName, 8); memcpy(trans_hdr->destUserID, tmpID, 8); memcpy(trans_hdr->destAppName, tmpName, 8); skb_push(skb, ETH_HLEN); memset(skb->data, 0, ETH_HLEN); } /** * afiucv_hs_callback_syn - react on received SYN **/ static int afiucv_hs_callback_syn(struct sock *sk, struct sk_buff *skb) { struct sock *nsk; struct iucv_sock *iucv, *niucv; struct af_iucv_trans_hdr *trans_hdr; int err; iucv = iucv_sk(sk); trans_hdr = (struct af_iucv_trans_hdr *)skb->data; if (!iucv) { /* no sock - connection refused */ afiucv_swap_src_dest(skb); trans_hdr->flags = AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_FIN; err = dev_queue_xmit(skb); goto out; } nsk = iucv_sock_alloc(NULL, sk->sk_type, GFP_ATOMIC); bh_lock_sock(sk); if ((sk->sk_state != IUCV_LISTEN) || sk_acceptq_is_full(sk) || !nsk) { /* error on server socket - connection refused */ if (nsk) sk_free(nsk); afiucv_swap_src_dest(skb); trans_hdr->flags = AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_FIN; err = dev_queue_xmit(skb); bh_unlock_sock(sk); goto out; } niucv = iucv_sk(nsk); iucv_sock_init(nsk, sk); niucv->transport = AF_IUCV_TRANS_HIPER; niucv->msglimit = iucv->msglimit; if (!trans_hdr->window) niucv->msglimit_peer = IUCV_HIPER_MSGLIM_DEFAULT; else niucv->msglimit_peer = trans_hdr->window; memcpy(niucv->dst_name, trans_hdr->srcAppName, 8); memcpy(niucv->dst_user_id, trans_hdr->srcUserID, 8); memcpy(niucv->src_name, iucv->src_name, 8); memcpy(niucv->src_user_id, iucv->src_user_id, 8); nsk->sk_bound_dev_if = sk->sk_bound_dev_if; niucv->hs_dev = iucv->hs_dev; dev_hold(niucv->hs_dev); afiucv_swap_src_dest(skb); trans_hdr->flags = AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_ACK; trans_hdr->window = niucv->msglimit; /* if receiver acks the xmit connection is established */ err = dev_queue_xmit(skb); if (!err) { iucv_accept_enqueue(sk, nsk); nsk->sk_state = IUCV_CONNECTED; sk->sk_data_ready(sk, 1); } else iucv_sock_kill(nsk); bh_unlock_sock(sk); out: return NET_RX_SUCCESS; } /** * afiucv_hs_callback_synack() - react on received SYN-ACK **/ static int afiucv_hs_callback_synack(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); struct af_iucv_trans_hdr *trans_hdr = (struct af_iucv_trans_hdr *)skb->data; if (!iucv) goto out; if (sk->sk_state != IUCV_BOUND) goto out; bh_lock_sock(sk); iucv->msglimit_peer = trans_hdr->window; sk->sk_state = IUCV_CONNECTED; sk->sk_state_change(sk); bh_unlock_sock(sk); out: kfree_skb(skb); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_synfin() - react on received SYN_FIN **/ static int afiucv_hs_callback_synfin(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); if (!iucv) goto out; if (sk->sk_state != IUCV_BOUND) goto out; bh_lock_sock(sk); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); bh_unlock_sock(sk); out: kfree_skb(skb); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_fin() - react on received FIN **/ static int afiucv_hs_callback_fin(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); /* other end of connection closed */ if (!iucv) goto out; bh_lock_sock(sk); if (sk->sk_state == IUCV_CONNECTED) { sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } bh_unlock_sock(sk); out: kfree_skb(skb); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_win() - react on received WIN **/ static int afiucv_hs_callback_win(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); struct af_iucv_trans_hdr *trans_hdr = (struct af_iucv_trans_hdr *)skb->data; if (!iucv) return NET_RX_SUCCESS; if (sk->sk_state != IUCV_CONNECTED) return NET_RX_SUCCESS; atomic_sub(trans_hdr->window, &iucv->msg_sent); iucv_sock_wake_msglim(sk); return NET_RX_SUCCESS; } /** * afiucv_hs_callback_rx() - react on received data **/ static int afiucv_hs_callback_rx(struct sock *sk, struct sk_buff *skb) { struct iucv_sock *iucv = iucv_sk(sk); if (!iucv) { kfree_skb(skb); return NET_RX_SUCCESS; } if (sk->sk_state != IUCV_CONNECTED) { kfree_skb(skb); return NET_RX_SUCCESS; } if (sk->sk_shutdown & RCV_SHUTDOWN) { kfree_skb(skb); return NET_RX_SUCCESS; } /* write stuff from iucv_msg to skb cb */ if (skb->len < sizeof(struct af_iucv_trans_hdr)) { kfree_skb(skb); return NET_RX_SUCCESS; } skb_pull(skb, sizeof(struct af_iucv_trans_hdr)); skb_reset_transport_header(skb); skb_reset_network_header(skb); spin_lock(&iucv->message_q.lock); if (skb_queue_empty(&iucv->backlog_skb_q)) { if (sock_queue_rcv_skb(sk, skb)) { /* handle rcv queue full */ skb_queue_tail(&iucv->backlog_skb_q, skb); } } else skb_queue_tail(&iucv_sk(sk)->backlog_skb_q, skb); spin_unlock(&iucv->message_q.lock); return NET_RX_SUCCESS; } /** * afiucv_hs_rcv() - base function for arriving data through HiperSockets * transport * called from netif RX softirq **/ static int afiucv_hs_rcv(struct sk_buff *skb, struct net_device *dev, struct packet_type *pt, struct net_device *orig_dev) { struct sock *sk; struct iucv_sock *iucv; struct af_iucv_trans_hdr *trans_hdr; char nullstring[8]; int err = 0; skb_pull(skb, ETH_HLEN); trans_hdr = (struct af_iucv_trans_hdr *)skb->data; EBCASC(trans_hdr->destAppName, sizeof(trans_hdr->destAppName)); EBCASC(trans_hdr->destUserID, sizeof(trans_hdr->destUserID)); EBCASC(trans_hdr->srcAppName, sizeof(trans_hdr->srcAppName)); EBCASC(trans_hdr->srcUserID, sizeof(trans_hdr->srcUserID)); memset(nullstring, 0, sizeof(nullstring)); iucv = NULL; sk = NULL; read_lock(&iucv_sk_list.lock); sk_for_each(sk, &iucv_sk_list.head) { if (trans_hdr->flags == AF_IUCV_FLAG_SYN) { if ((!memcmp(&iucv_sk(sk)->src_name, trans_hdr->destAppName, 8)) && (!memcmp(&iucv_sk(sk)->src_user_id, trans_hdr->destUserID, 8)) && (!memcmp(&iucv_sk(sk)->dst_name, nullstring, 8)) && (!memcmp(&iucv_sk(sk)->dst_user_id, nullstring, 8))) { iucv = iucv_sk(sk); break; } } else { if ((!memcmp(&iucv_sk(sk)->src_name, trans_hdr->destAppName, 8)) && (!memcmp(&iucv_sk(sk)->src_user_id, trans_hdr->destUserID, 8)) && (!memcmp(&iucv_sk(sk)->dst_name, trans_hdr->srcAppName, 8)) && (!memcmp(&iucv_sk(sk)->dst_user_id, trans_hdr->srcUserID, 8))) { iucv = iucv_sk(sk); break; } } } read_unlock(&iucv_sk_list.lock); if (!iucv) sk = NULL; /* no sock how should we send with no sock 1) send without sock no send rc checking? 2) introduce default sock to handle this cases SYN -> send SYN|ACK in good case, send SYN|FIN in bad case data -> send FIN SYN|ACK, SYN|FIN, FIN -> no action? */ switch (trans_hdr->flags) { case AF_IUCV_FLAG_SYN: /* connect request */ err = afiucv_hs_callback_syn(sk, skb); break; case (AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_ACK): /* connect request confirmed */ err = afiucv_hs_callback_synack(sk, skb); break; case (AF_IUCV_FLAG_SYN | AF_IUCV_FLAG_FIN): /* connect request refused */ err = afiucv_hs_callback_synfin(sk, skb); break; case (AF_IUCV_FLAG_FIN): /* close request */ err = afiucv_hs_callback_fin(sk, skb); break; case (AF_IUCV_FLAG_WIN): err = afiucv_hs_callback_win(sk, skb); if (skb->len == sizeof(struct af_iucv_trans_hdr)) { kfree_skb(skb); break; } /* fall through and receive non-zero length data */ case (AF_IUCV_FLAG_SHT): /* shutdown request */ /* fall through and receive zero length data */ case 0: /* plain data frame */ memcpy(CB_TRGCLS(skb), &trans_hdr->iucv_hdr.class, CB_TRGCLS_LEN); err = afiucv_hs_callback_rx(sk, skb); break; default: ; } return err; } /** * afiucv_hs_callback_txnotify() - handle send notifcations from HiperSockets * transport **/ static void afiucv_hs_callback_txnotify(struct sk_buff *skb, enum iucv_tx_notify n) { struct sock *isk = skb->sk; struct sock *sk = NULL; struct iucv_sock *iucv = NULL; struct sk_buff_head *list; struct sk_buff *list_skb; struct sk_buff *nskb; unsigned long flags; read_lock_irqsave(&iucv_sk_list.lock, flags); sk_for_each(sk, &iucv_sk_list.head) if (sk == isk) { iucv = iucv_sk(sk); break; } read_unlock_irqrestore(&iucv_sk_list.lock, flags); if (!iucv || sock_flag(sk, SOCK_ZAPPED)) return; list = &iucv->send_skb_q; spin_lock_irqsave(&list->lock, flags); if (skb_queue_empty(list)) goto out_unlock; list_skb = list->next; nskb = list_skb->next; while (list_skb != (struct sk_buff *)list) { if (skb_shinfo(list_skb) == skb_shinfo(skb)) { switch (n) { case TX_NOTIFY_OK: __skb_unlink(list_skb, list); kfree_skb(list_skb); iucv_sock_wake_msglim(sk); break; case TX_NOTIFY_PENDING: atomic_inc(&iucv->pendings); break; case TX_NOTIFY_DELAYED_OK: __skb_unlink(list_skb, list); atomic_dec(&iucv->pendings); if (atomic_read(&iucv->pendings) <= 0) iucv_sock_wake_msglim(sk); kfree_skb(list_skb); break; case TX_NOTIFY_UNREACHABLE: case TX_NOTIFY_DELAYED_UNREACHABLE: case TX_NOTIFY_TPQFULL: /* not yet used */ case TX_NOTIFY_GENERALERROR: case TX_NOTIFY_DELAYED_GENERALERROR: __skb_unlink(list_skb, list); kfree_skb(list_skb); if (sk->sk_state == IUCV_CONNECTED) { sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } break; } break; } list_skb = nskb; nskb = nskb->next; } out_unlock: spin_unlock_irqrestore(&list->lock, flags); if (sk->sk_state == IUCV_CLOSING) { if (skb_queue_empty(&iucv_sk(sk)->send_skb_q)) { sk->sk_state = IUCV_CLOSED; sk->sk_state_change(sk); } } } /* * afiucv_netdev_event: handle netdev notifier chain events */ static int afiucv_netdev_event(struct notifier_block *this, unsigned long event, void *ptr) { struct net_device *event_dev = (struct net_device *)ptr; struct sock *sk; struct iucv_sock *iucv; switch (event) { case NETDEV_REBOOT: case NETDEV_GOING_DOWN: sk_for_each(sk, &iucv_sk_list.head) { iucv = iucv_sk(sk); if ((iucv->hs_dev == event_dev) && (sk->sk_state == IUCV_CONNECTED)) { if (event == NETDEV_GOING_DOWN) iucv_send_ctrl(sk, AF_IUCV_FLAG_FIN); sk->sk_state = IUCV_DISCONN; sk->sk_state_change(sk); } } break; case NETDEV_DOWN: case NETDEV_UNREGISTER: default: break; } return NOTIFY_DONE; } static struct notifier_block afiucv_netdev_notifier = { .notifier_call = afiucv_netdev_event, }; static const struct proto_ops iucv_sock_ops = { .family = PF_IUCV, .owner = THIS_MODULE, .release = iucv_sock_release, .bind = iucv_sock_bind, .connect = iucv_sock_connect, .listen = iucv_sock_listen, .accept = iucv_sock_accept, .getname = iucv_sock_getname, .sendmsg = iucv_sock_sendmsg, .recvmsg = iucv_sock_recvmsg, .poll = iucv_sock_poll, .ioctl = sock_no_ioctl, .mmap = sock_no_mmap, .socketpair = sock_no_socketpair, .shutdown = iucv_sock_shutdown, .setsockopt = iucv_sock_setsockopt, .getsockopt = iucv_sock_getsockopt, }; static const struct net_proto_family iucv_sock_family_ops = { .family = AF_IUCV, .owner = THIS_MODULE, .create = iucv_sock_create, }; static struct packet_type iucv_packet_type = { .type = cpu_to_be16(ETH_P_AF_IUCV), .func = afiucv_hs_rcv, }; static int afiucv_iucv_init(void) { int err; err = pr_iucv->iucv_register(&af_iucv_handler, 0); if (err) goto out; /* establish dummy device */ af_iucv_driver.bus = pr_iucv->bus; err = driver_register(&af_iucv_driver); if (err) goto out_iucv; af_iucv_dev = kzalloc(sizeof(struct device), GFP_KERNEL); if (!af_iucv_dev) { err = -ENOMEM; goto out_driver; } dev_set_name(af_iucv_dev, "af_iucv"); af_iucv_dev->bus = pr_iucv->bus; af_iucv_dev->parent = pr_iucv->root; af_iucv_dev->release = (void (*)(struct device *))kfree; af_iucv_dev->driver = &af_iucv_driver; err = device_register(af_iucv_dev); if (err) goto out_driver; return 0; out_driver: driver_unregister(&af_iucv_driver); out_iucv: pr_iucv->iucv_unregister(&af_iucv_handler, 0); out: return err; } static int __init afiucv_init(void) { int err; if (MACHINE_IS_VM) { cpcmd("QUERY USERID", iucv_userid, sizeof(iucv_userid), &err); if (unlikely(err)) { WARN_ON(err); err = -EPROTONOSUPPORT; goto out; } pr_iucv = try_then_request_module(symbol_get(iucv_if), "iucv"); if (!pr_iucv) { printk(KERN_WARNING "iucv_if lookup failed\n"); memset(&iucv_userid, 0, sizeof(iucv_userid)); } } else { memset(&iucv_userid, 0, sizeof(iucv_userid)); pr_iucv = NULL; } err = proto_register(&iucv_proto, 0); if (err) goto out; err = sock_register(&iucv_sock_family_ops); if (err) goto out_proto; if (pr_iucv) { err = afiucv_iucv_init(); if (err) goto out_sock; } else register_netdevice_notifier(&afiucv_netdev_notifier); dev_add_pack(&iucv_packet_type); return 0; out_sock: sock_unregister(PF_IUCV); out_proto: proto_unregister(&iucv_proto); out: if (pr_iucv) symbol_put(iucv_if); return err; } static void __exit afiucv_exit(void) { if (pr_iucv) { device_unregister(af_iucv_dev); driver_unregister(&af_iucv_driver); pr_iucv->iucv_unregister(&af_iucv_handler, 0); symbol_put(iucv_if); } else unregister_netdevice_notifier(&afiucv_netdev_notifier); dev_remove_pack(&iucv_packet_type); sock_unregister(PF_IUCV); proto_unregister(&iucv_proto); } module_init(afiucv_init); module_exit(afiucv_exit); MODULE_AUTHOR("Jennifer Hunt <jenhunt@us.ibm.com>"); MODULE_DESCRIPTION("IUCV Sockets ver " VERSION); MODULE_VERSION(VERSION); MODULE_LICENSE("GPL"); MODULE_ALIAS_NETPROTO(PF_IUCV);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_5688_0
crossvul-cpp_data_good_2425_0
/* * Media device * * Copyright (C) 2010 Nokia Corporation * * Contacts: Laurent Pinchart <laurent.pinchart@ideasonboard.com> * Sakari Ailus <sakari.ailus@iki.fi> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include <linux/compat.h> #include <linux/export.h> #include <linux/ioctl.h> #include <linux/media.h> #include <linux/types.h> #include <media/media-device.h> #include <media/media-devnode.h> #include <media/media-entity.h> /* ----------------------------------------------------------------------------- * Userspace API */ static int media_device_open(struct file *filp) { return 0; } static int media_device_close(struct file *filp) { return 0; } static int media_device_get_info(struct media_device *dev, struct media_device_info __user *__info) { struct media_device_info info; memset(&info, 0, sizeof(info)); strlcpy(info.driver, dev->dev->driver->name, sizeof(info.driver)); strlcpy(info.model, dev->model, sizeof(info.model)); strlcpy(info.serial, dev->serial, sizeof(info.serial)); strlcpy(info.bus_info, dev->bus_info, sizeof(info.bus_info)); info.media_version = MEDIA_API_VERSION; info.hw_revision = dev->hw_revision; info.driver_version = dev->driver_version; if (copy_to_user(__info, &info, sizeof(*__info))) return -EFAULT; return 0; } static struct media_entity *find_entity(struct media_device *mdev, u32 id) { struct media_entity *entity; int next = id & MEDIA_ENT_ID_FLAG_NEXT; id &= ~MEDIA_ENT_ID_FLAG_NEXT; spin_lock(&mdev->lock); media_device_for_each_entity(entity, mdev) { if ((entity->id == id && !next) || (entity->id > id && next)) { spin_unlock(&mdev->lock); return entity; } } spin_unlock(&mdev->lock); return NULL; } static long media_device_enum_entities(struct media_device *mdev, struct media_entity_desc __user *uent) { struct media_entity *ent; struct media_entity_desc u_ent; if (copy_from_user(&u_ent.id, &uent->id, sizeof(u_ent.id))) return -EFAULT; ent = find_entity(mdev, u_ent.id); if (ent == NULL) return -EINVAL; u_ent.id = ent->id; if (ent->name) { strncpy(u_ent.name, ent->name, sizeof(u_ent.name)); u_ent.name[sizeof(u_ent.name) - 1] = '\0'; } else { memset(u_ent.name, 0, sizeof(u_ent.name)); } u_ent.type = ent->type; u_ent.revision = ent->revision; u_ent.flags = ent->flags; u_ent.group_id = ent->group_id; u_ent.pads = ent->num_pads; u_ent.links = ent->num_links - ent->num_backlinks; memcpy(&u_ent.raw, &ent->info, sizeof(ent->info)); if (copy_to_user(uent, &u_ent, sizeof(u_ent))) return -EFAULT; return 0; } static void media_device_kpad_to_upad(const struct media_pad *kpad, struct media_pad_desc *upad) { upad->entity = kpad->entity->id; upad->index = kpad->index; upad->flags = kpad->flags; } static long __media_device_enum_links(struct media_device *mdev, struct media_links_enum *links) { struct media_entity *entity; entity = find_entity(mdev, links->entity); if (entity == NULL) return -EINVAL; if (links->pads) { unsigned int p; for (p = 0; p < entity->num_pads; p++) { struct media_pad_desc pad; memset(&pad, 0, sizeof(pad)); media_device_kpad_to_upad(&entity->pads[p], &pad); if (copy_to_user(&links->pads[p], &pad, sizeof(pad))) return -EFAULT; } } if (links->links) { struct media_link_desc __user *ulink; unsigned int l; for (l = 0, ulink = links->links; l < entity->num_links; l++) { struct media_link_desc link; /* Ignore backlinks. */ if (entity->links[l].source->entity != entity) continue; memset(&link, 0, sizeof(link)); media_device_kpad_to_upad(entity->links[l].source, &link.source); media_device_kpad_to_upad(entity->links[l].sink, &link.sink); link.flags = entity->links[l].flags; if (copy_to_user(ulink, &link, sizeof(*ulink))) return -EFAULT; ulink++; } } return 0; } static long media_device_enum_links(struct media_device *mdev, struct media_links_enum __user *ulinks) { struct media_links_enum links; int rval; if (copy_from_user(&links, ulinks, sizeof(links))) return -EFAULT; rval = __media_device_enum_links(mdev, &links); if (rval < 0) return rval; if (copy_to_user(ulinks, &links, sizeof(*ulinks))) return -EFAULT; return 0; } static long media_device_setup_link(struct media_device *mdev, struct media_link_desc __user *_ulink) { struct media_link *link = NULL; struct media_link_desc ulink; struct media_entity *source; struct media_entity *sink; int ret; if (copy_from_user(&ulink, _ulink, sizeof(ulink))) return -EFAULT; /* Find the source and sink entities and link. */ source = find_entity(mdev, ulink.source.entity); sink = find_entity(mdev, ulink.sink.entity); if (source == NULL || sink == NULL) return -EINVAL; if (ulink.source.index >= source->num_pads || ulink.sink.index >= sink->num_pads) return -EINVAL; link = media_entity_find_link(&source->pads[ulink.source.index], &sink->pads[ulink.sink.index]); if (link == NULL) return -EINVAL; /* Setup the link on both entities. */ ret = __media_entity_setup_link(link, ulink.flags); if (copy_to_user(_ulink, &ulink, sizeof(ulink))) return -EFAULT; return ret; } static long media_device_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: ret = media_device_get_info(dev, (struct media_device_info __user *)arg); break; case MEDIA_IOC_ENUM_ENTITIES: ret = media_device_enum_entities(dev, (struct media_entity_desc __user *)arg); break; case MEDIA_IOC_ENUM_LINKS: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links(dev, (struct media_links_enum __user *)arg); mutex_unlock(&dev->graph_mutex); break; case MEDIA_IOC_SETUP_LINK: mutex_lock(&dev->graph_mutex); ret = media_device_setup_link(dev, (struct media_link_desc __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #ifdef CONFIG_COMPAT struct media_links_enum32 { __u32 entity; compat_uptr_t pads; /* struct media_pad_desc * */ compat_uptr_t links; /* struct media_link_desc * */ __u32 reserved[4]; }; static long media_device_enum_links32(struct media_device *mdev, struct media_links_enum32 __user *ulinks) { struct media_links_enum links; compat_uptr_t pads_ptr, links_ptr; memset(&links, 0, sizeof(links)); if (get_user(links.entity, &ulinks->entity) || get_user(pads_ptr, &ulinks->pads) || get_user(links_ptr, &ulinks->links)) return -EFAULT; links.pads = compat_ptr(pads_ptr); links.links = compat_ptr(links_ptr); return __media_device_enum_links(mdev, &links); } #define MEDIA_IOC_ENUM_LINKS32 _IOWR('|', 0x02, struct media_links_enum32) static long media_device_compat_ioctl(struct file *filp, unsigned int cmd, unsigned long arg) { struct media_devnode *devnode = media_devnode_data(filp); struct media_device *dev = to_media_device(devnode); long ret; switch (cmd) { case MEDIA_IOC_DEVICE_INFO: case MEDIA_IOC_ENUM_ENTITIES: case MEDIA_IOC_SETUP_LINK: return media_device_ioctl(filp, cmd, arg); case MEDIA_IOC_ENUM_LINKS32: mutex_lock(&dev->graph_mutex); ret = media_device_enum_links32(dev, (struct media_links_enum32 __user *)arg); mutex_unlock(&dev->graph_mutex); break; default: ret = -ENOIOCTLCMD; } return ret; } #endif /* CONFIG_COMPAT */ static const struct media_file_operations media_device_fops = { .owner = THIS_MODULE, .open = media_device_open, .ioctl = media_device_ioctl, #ifdef CONFIG_COMPAT .compat_ioctl = media_device_compat_ioctl, #endif /* CONFIG_COMPAT */ .release = media_device_close, }; /* ----------------------------------------------------------------------------- * sysfs */ static ssize_t show_model(struct device *cd, struct device_attribute *attr, char *buf) { struct media_device *mdev = to_media_device(to_media_devnode(cd)); return sprintf(buf, "%.*s\n", (int)sizeof(mdev->model), mdev->model); } static DEVICE_ATTR(model, S_IRUGO, show_model, NULL); /* ----------------------------------------------------------------------------- * Registration/unregistration */ static void media_device_release(struct media_devnode *mdev) { } /** * media_device_register - register a media device * @mdev: The media device * * The caller is responsible for initializing the media device before * registration. The following fields must be set: * * - dev must point to the parent device * - model must be filled with the device model name */ int __must_check media_device_register(struct media_device *mdev) { int ret; if (WARN_ON(mdev->dev == NULL || mdev->model[0] == 0)) return -EINVAL; mdev->entity_id = 1; INIT_LIST_HEAD(&mdev->entities); spin_lock_init(&mdev->lock); mutex_init(&mdev->graph_mutex); /* Register the device node. */ mdev->devnode.fops = &media_device_fops; mdev->devnode.parent = mdev->dev; mdev->devnode.release = media_device_release; ret = media_devnode_register(&mdev->devnode); if (ret < 0) return ret; ret = device_create_file(&mdev->devnode.dev, &dev_attr_model); if (ret < 0) { media_devnode_unregister(&mdev->devnode); return ret; } return 0; } EXPORT_SYMBOL_GPL(media_device_register); /** * media_device_unregister - unregister a media device * @mdev: The media device * */ void media_device_unregister(struct media_device *mdev) { struct media_entity *entity; struct media_entity *next; list_for_each_entry_safe(entity, next, &mdev->entities, list) media_device_unregister_entity(entity); device_remove_file(&mdev->devnode.dev, &dev_attr_model); media_devnode_unregister(&mdev->devnode); } EXPORT_SYMBOL_GPL(media_device_unregister); /** * media_device_register_entity - Register an entity with a media device * @mdev: The media device * @entity: The entity */ int __must_check media_device_register_entity(struct media_device *mdev, struct media_entity *entity) { /* Warn if we apparently re-register an entity */ WARN_ON(entity->parent != NULL); entity->parent = mdev; spin_lock(&mdev->lock); if (entity->id == 0) entity->id = mdev->entity_id++; else mdev->entity_id = max(entity->id + 1, mdev->entity_id); list_add_tail(&entity->list, &mdev->entities); spin_unlock(&mdev->lock); return 0; } EXPORT_SYMBOL_GPL(media_device_register_entity); /** * media_device_unregister_entity - Unregister an entity * @entity: The entity * * If the entity has never been registered this function will return * immediately. */ void media_device_unregister_entity(struct media_entity *entity) { struct media_device *mdev = entity->parent; if (mdev == NULL) return; spin_lock(&mdev->lock); list_del(&entity->list); spin_unlock(&mdev->lock); entity->parent = NULL; } EXPORT_SYMBOL_GPL(media_device_unregister_entity);
./CrossVul/dataset_final_sorted/CWE-200/c/good_2425_0
crossvul-cpp_data_bad_1841_0
/* * SWIOTLB-based DMA API implementation * * Copyright (C) 2012 ARM Ltd. * Author: Catalin Marinas <catalin.marinas@arm.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <linux/gfp.h> #include <linux/export.h> #include <linux/slab.h> #include <linux/genalloc.h> #include <linux/dma-mapping.h> #include <linux/dma-contiguous.h> #include <linux/vmalloc.h> #include <linux/swiotlb.h> #include <asm/cacheflush.h> struct dma_map_ops *dma_ops; EXPORT_SYMBOL(dma_ops); static pgprot_t __get_dma_pgprot(struct dma_attrs *attrs, pgprot_t prot, bool coherent) { if (!coherent || dma_get_attr(DMA_ATTR_WRITE_COMBINE, attrs)) return pgprot_writecombine(prot); return prot; } static struct gen_pool *atomic_pool; #define DEFAULT_DMA_COHERENT_POOL_SIZE SZ_256K static size_t atomic_pool_size = DEFAULT_DMA_COHERENT_POOL_SIZE; static int __init early_coherent_pool(char *p) { atomic_pool_size = memparse(p, &p); return 0; } early_param("coherent_pool", early_coherent_pool); static void *__alloc_from_pool(size_t size, struct page **ret_page, gfp_t flags) { unsigned long val; void *ptr = NULL; if (!atomic_pool) { WARN(1, "coherent pool not initialised!\n"); return NULL; } val = gen_pool_alloc(atomic_pool, size); if (val) { phys_addr_t phys = gen_pool_virt_to_phys(atomic_pool, val); *ret_page = phys_to_page(phys); ptr = (void *)val; if (flags & __GFP_ZERO) memset(ptr, 0, size); } return ptr; } static bool __in_atomic_pool(void *start, size_t size) { return addr_in_gen_pool(atomic_pool, (unsigned long)start, size); } static int __free_from_pool(void *start, size_t size) { if (!__in_atomic_pool(start, size)) return 0; gen_pool_free(atomic_pool, (unsigned long)start, size); return 1; } static void *__dma_alloc_coherent(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flags, struct dma_attrs *attrs) { if (dev == NULL) { WARN_ONCE(1, "Use an actual device structure for DMA allocation\n"); return NULL; } if (IS_ENABLED(CONFIG_ZONE_DMA) && dev->coherent_dma_mask <= DMA_BIT_MASK(32)) flags |= GFP_DMA; if (IS_ENABLED(CONFIG_DMA_CMA) && (flags & __GFP_WAIT)) { struct page *page; void *addr; size = PAGE_ALIGN(size); page = dma_alloc_from_contiguous(dev, size >> PAGE_SHIFT, get_order(size)); if (!page) return NULL; *dma_handle = phys_to_dma(dev, page_to_phys(page)); addr = page_address(page); if (flags & __GFP_ZERO) memset(addr, 0, size); return addr; } else { return swiotlb_alloc_coherent(dev, size, dma_handle, flags); } } static void __dma_free_coherent(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle, struct dma_attrs *attrs) { bool freed; phys_addr_t paddr = dma_to_phys(dev, dma_handle); if (dev == NULL) { WARN_ONCE(1, "Use an actual device structure for DMA allocation\n"); return; } freed = dma_release_from_contiguous(dev, phys_to_page(paddr), size >> PAGE_SHIFT); if (!freed) swiotlb_free_coherent(dev, size, vaddr, dma_handle); } static void *__dma_alloc(struct device *dev, size_t size, dma_addr_t *dma_handle, gfp_t flags, struct dma_attrs *attrs) { struct page *page; void *ptr, *coherent_ptr; bool coherent = is_device_dma_coherent(dev); size = PAGE_ALIGN(size); if (!coherent && !(flags & __GFP_WAIT)) { struct page *page = NULL; void *addr = __alloc_from_pool(size, &page, flags); if (addr) *dma_handle = phys_to_dma(dev, page_to_phys(page)); return addr; } ptr = __dma_alloc_coherent(dev, size, dma_handle, flags, attrs); if (!ptr) goto no_mem; /* no need for non-cacheable mapping if coherent */ if (coherent) return ptr; /* remove any dirty cache lines on the kernel alias */ __dma_flush_range(ptr, ptr + size); /* create a coherent mapping */ page = virt_to_page(ptr); coherent_ptr = dma_common_contiguous_remap(page, size, VM_USERMAP, __get_dma_pgprot(attrs, __pgprot(PROT_NORMAL_NC), false), NULL); if (!coherent_ptr) goto no_map; return coherent_ptr; no_map: __dma_free_coherent(dev, size, ptr, *dma_handle, attrs); no_mem: *dma_handle = DMA_ERROR_CODE; return NULL; } static void __dma_free(struct device *dev, size_t size, void *vaddr, dma_addr_t dma_handle, struct dma_attrs *attrs) { void *swiotlb_addr = phys_to_virt(dma_to_phys(dev, dma_handle)); if (!is_device_dma_coherent(dev)) { if (__free_from_pool(vaddr, size)) return; vunmap(vaddr); } __dma_free_coherent(dev, size, swiotlb_addr, dma_handle, attrs); } static dma_addr_t __swiotlb_map_page(struct device *dev, struct page *page, unsigned long offset, size_t size, enum dma_data_direction dir, struct dma_attrs *attrs) { dma_addr_t dev_addr; dev_addr = swiotlb_map_page(dev, page, offset, size, dir, attrs); if (!is_device_dma_coherent(dev)) __dma_map_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); return dev_addr; } static void __swiotlb_unmap_page(struct device *dev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir, struct dma_attrs *attrs) { if (!is_device_dma_coherent(dev)) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); swiotlb_unmap_page(dev, dev_addr, size, dir, attrs); } static int __swiotlb_map_sg_attrs(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir, struct dma_attrs *attrs) { struct scatterlist *sg; int i, ret; ret = swiotlb_map_sg_attrs(dev, sgl, nelems, dir, attrs); if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, ret, i) __dma_map_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); return ret; } static void __swiotlb_unmap_sg_attrs(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir, struct dma_attrs *attrs) { struct scatterlist *sg; int i; if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, nelems, i) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); swiotlb_unmap_sg_attrs(dev, sgl, nelems, dir, attrs); } static void __swiotlb_sync_single_for_cpu(struct device *dev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir) { if (!is_device_dma_coherent(dev)) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); swiotlb_sync_single_for_cpu(dev, dev_addr, size, dir); } static void __swiotlb_sync_single_for_device(struct device *dev, dma_addr_t dev_addr, size_t size, enum dma_data_direction dir) { swiotlb_sync_single_for_device(dev, dev_addr, size, dir); if (!is_device_dma_coherent(dev)) __dma_map_area(phys_to_virt(dma_to_phys(dev, dev_addr)), size, dir); } static void __swiotlb_sync_sg_for_cpu(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir) { struct scatterlist *sg; int i; if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, nelems, i) __dma_unmap_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); swiotlb_sync_sg_for_cpu(dev, sgl, nelems, dir); } static void __swiotlb_sync_sg_for_device(struct device *dev, struct scatterlist *sgl, int nelems, enum dma_data_direction dir) { struct scatterlist *sg; int i; swiotlb_sync_sg_for_device(dev, sgl, nelems, dir); if (!is_device_dma_coherent(dev)) for_each_sg(sgl, sg, nelems, i) __dma_map_area(phys_to_virt(dma_to_phys(dev, sg->dma_address)), sg->length, dir); } /* vma->vm_page_prot must be set appropriately before calling this function */ static int __dma_common_mmap(struct device *dev, struct vm_area_struct *vma, void *cpu_addr, dma_addr_t dma_addr, size_t size) { int ret = -ENXIO; unsigned long nr_vma_pages = (vma->vm_end - vma->vm_start) >> PAGE_SHIFT; unsigned long nr_pages = PAGE_ALIGN(size) >> PAGE_SHIFT; unsigned long pfn = dma_to_phys(dev, dma_addr) >> PAGE_SHIFT; unsigned long off = vma->vm_pgoff; if (dma_mmap_from_coherent(dev, vma, cpu_addr, size, &ret)) return ret; if (off < nr_pages && nr_vma_pages <= (nr_pages - off)) { ret = remap_pfn_range(vma, vma->vm_start, pfn + off, vma->vm_end - vma->vm_start, vma->vm_page_prot); } return ret; } static int __swiotlb_mmap(struct device *dev, struct vm_area_struct *vma, void *cpu_addr, dma_addr_t dma_addr, size_t size, struct dma_attrs *attrs) { vma->vm_page_prot = __get_dma_pgprot(attrs, vma->vm_page_prot, is_device_dma_coherent(dev)); return __dma_common_mmap(dev, vma, cpu_addr, dma_addr, size); } static struct dma_map_ops swiotlb_dma_ops = { .alloc = __dma_alloc, .free = __dma_free, .mmap = __swiotlb_mmap, .map_page = __swiotlb_map_page, .unmap_page = __swiotlb_unmap_page, .map_sg = __swiotlb_map_sg_attrs, .unmap_sg = __swiotlb_unmap_sg_attrs, .sync_single_for_cpu = __swiotlb_sync_single_for_cpu, .sync_single_for_device = __swiotlb_sync_single_for_device, .sync_sg_for_cpu = __swiotlb_sync_sg_for_cpu, .sync_sg_for_device = __swiotlb_sync_sg_for_device, .dma_supported = swiotlb_dma_supported, .mapping_error = swiotlb_dma_mapping_error, }; static int __init atomic_pool_init(void) { pgprot_t prot = __pgprot(PROT_NORMAL_NC); unsigned long nr_pages = atomic_pool_size >> PAGE_SHIFT; struct page *page; void *addr; unsigned int pool_size_order = get_order(atomic_pool_size); if (dev_get_cma_area(NULL)) page = dma_alloc_from_contiguous(NULL, nr_pages, pool_size_order); else page = alloc_pages(GFP_DMA, pool_size_order); if (page) { int ret; void *page_addr = page_address(page); memset(page_addr, 0, atomic_pool_size); __dma_flush_range(page_addr, page_addr + atomic_pool_size); atomic_pool = gen_pool_create(PAGE_SHIFT, -1); if (!atomic_pool) goto free_page; addr = dma_common_contiguous_remap(page, atomic_pool_size, VM_USERMAP, prot, atomic_pool_init); if (!addr) goto destroy_genpool; ret = gen_pool_add_virt(atomic_pool, (unsigned long)addr, page_to_phys(page), atomic_pool_size, -1); if (ret) goto remove_mapping; gen_pool_set_algo(atomic_pool, gen_pool_first_fit_order_align, (void *)PAGE_SHIFT); pr_info("DMA: preallocated %zu KiB pool for atomic allocations\n", atomic_pool_size / 1024); return 0; } goto out; remove_mapping: dma_common_free_remap(addr, atomic_pool_size, VM_USERMAP); destroy_genpool: gen_pool_destroy(atomic_pool); atomic_pool = NULL; free_page: if (!dma_release_from_contiguous(NULL, page, nr_pages)) __free_pages(page, pool_size_order); out: pr_err("DMA: failed to allocate %zu KiB pool for atomic coherent allocation\n", atomic_pool_size / 1024); return -ENOMEM; } static int __init arm64_dma_init(void) { int ret; dma_ops = &swiotlb_dma_ops; ret = atomic_pool_init(); return ret; } arch_initcall(arm64_dma_init); #define PREALLOC_DMA_DEBUG_ENTRIES 4096 static int __init dma_debug_do_init(void) { dma_debug_init(PREALLOC_DMA_DEBUG_ENTRIES); return 0; } fs_initcall(dma_debug_do_init);
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1841_0
crossvul-cpp_data_bad_1508_0
/* Copyright (C) 2010 ABRT team This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "libabrt.h" /* Maximal length of backtrace. */ #define MAX_BACKTRACE_SIZE (1024*1024) /* Amount of data received from one client for a message before reporting error. */ #define MAX_MESSAGE_SIZE (4*MAX_BACKTRACE_SIZE) /* Maximal number of characters read from socket at once. */ #define INPUT_BUFFER_SIZE (8*1024) /* We exit after this many seconds */ #define TIMEOUT 10 /* Unix socket in ABRT daemon for creating new dump directories. Why to use socket for creating dump dirs? Security. When a Python script throws unexpected exception, ABRT handler catches it, running as a part of that broken Python application. The application is running with certain SELinux privileges, for example it can not execute other programs, or to create files in /var/cache or anything else required to properly fill a problem directory. Adding these privileges to every application would weaken the security. The most suitable solution is for the Python application to open a socket where ABRT daemon is listening, write all relevant data to that socket, and close it. ABRT daemon handles the rest. ** Protocol Initializing new dump: open /var/run/abrt.socket Providing dump data (hook writes to the socket): MANDATORY ITEMS: -> "PID=" number 0 - PID_MAX (/proc/sys/kernel/pid_max) \0 -> "EXECUTABLE=" string \0 -> "BACKTRACE=" string \0 -> "ANALYZER=" string \0 -> "BASENAME=" string (no slashes) \0 -> "REASON=" string \0 You can send more messages using the same KEY=value format. */ static unsigned total_bytes_read = 0; static uid_t client_uid = (uid_t)-1L; static bool dir_is_in_dump_location(const char *dump_dir_name) { unsigned len = strlen(g_settings_dump_location); if (strncmp(dump_dir_name, g_settings_dump_location, len) == 0 && dump_dir_name[len] == '/' /* must not contain "/." anywhere (IOW: disallow ".." component) */ && !strstr(dump_dir_name + len, "/.") ) { return 1; } return 0; } /* Remove dump dir */ static int delete_path(const char *dump_dir_name) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dump_dir_name)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dump_dir_name, g_settings_dump_location); return 400; /* Bad Request */ } if (!dump_dir_accessible_by_uid(dump_dir_name, client_uid)) { if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dump_dir_name); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dump_dir_name, (long)client_uid); return 403; /* Forbidden */ } delete_dump_dir(dump_dir_name); return 0; /* success */ } static pid_t spawn_event_handler_child(const char *dump_dir_name, const char *event_name, int *fdp) { char *args[7]; args[0] = (char *) LIBEXEC_DIR"/abrt-handle-event"; /* Do not forward ASK_* messages to parent*/ args[1] = (char *) "-i"; args[2] = (char *) "-e"; args[3] = (char *) event_name; args[4] = (char *) "--"; args[5] = (char *) dump_dir_name; args[6] = NULL; int pipeout[2]; int flags = EXECFLG_INPUT_NUL | EXECFLG_OUTPUT | EXECFLG_QUIET | EXECFLG_ERR2OUT; VERB1 flags &= ~EXECFLG_QUIET; char *env_vec[2]; /* Intercept ASK_* messages in Client API -> don't wait for user response */ env_vec[0] = xstrdup("REPORT_CLIENT_NONINTERACTIVE=1"); env_vec[1] = NULL; pid_t child = fork_execv_on_steroids(flags, args, pipeout, env_vec, /*dir:*/ NULL, /*uid(unused):*/ 0); if (fdp) *fdp = pipeout[0]; return child; } static int run_post_create(const char *dirname) { /* If doesn't start with "g_settings_dump_location/"... */ if (!dir_is_in_dump_location(dirname)) { /* Then refuse to operate on it (someone is attacking us??) */ error_msg("Bad problem directory name '%s', should start with: '%s'", dirname, g_settings_dump_location); return 400; /* Bad Request */ } if (!dump_dir_accessible_by_uid(dirname, client_uid)) { if (errno == ENOTDIR) { error_msg("Path '%s' isn't problem directory", dirname); return 404; /* Not Found */ } error_msg("Problem directory '%s' can't be accessed by user with uid %ld", dirname, (long)client_uid); return 403; /* Forbidden */ } int child_stdout_fd; int child_pid = spawn_event_handler_child(dirname, "post-create", &child_stdout_fd); char *dup_of_dir = NULL; struct strbuf *cmd_output = strbuf_new(); bool child_is_post_create = 1; /* else it is a notify child */ read_child_output: //log("Reading from event fd %d", child_stdout_fd); /* Read streamed data and split lines */ for (;;) { char buf[250]; /* usually we get one line, no need to have big buf */ errno = 0; int r = safe_read(child_stdout_fd, buf, sizeof(buf) - 1); if (r <= 0) break; buf[r] = '\0'; /* split lines in the current buffer */ char *raw = buf; char *newline; while ((newline = strchr(raw, '\n')) != NULL) { *newline = '\0'; strbuf_append_str(cmd_output, raw); char *msg = cmd_output->buf; /* Hmm, DUP_OF_DIR: ends up in syslog. move log() into 'else'? */ log("%s", msg); if (child_is_post_create && prefixcmp(msg, "DUP_OF_DIR: ") == 0 ) { free(dup_of_dir); dup_of_dir = xstrdup(msg + strlen("DUP_OF_DIR: ")); } strbuf_clear(cmd_output); /* jump to next line */ raw = newline + 1; } /* beginning of next line. the line continues by next read */ strbuf_append_str(cmd_output, raw); } /* EOF/error */ /* Wait for child to actually exit, collect status */ int status = 0; if (safe_waitpid(child_pid, &status, 0) <= 0) /* should not happen */ perror_msg("waitpid(%d)", child_pid); /* If it was a "notify[-dup]" event, then we're done */ if (!child_is_post_create) goto ret; /* exit 0 means "this is a good, non-dup dir" */ /* exit with 1 + "DUP_OF_DIR: dir" string => dup */ if (status != 0) { if (WIFSIGNALED(status)) { log("'post-create' on '%s' killed by signal %d", dirname, WTERMSIG(status)); goto delete_bad_dir; } /* else: it is WIFEXITED(status) */ if (!dup_of_dir) { log("'post-create' on '%s' exited with %d", dirname, WEXITSTATUS(status)); goto delete_bad_dir; } } const char *work_dir = (dup_of_dir ? dup_of_dir : dirname); /* Load problem_data (from the *first dir* if this one is a dup) */ struct dump_dir *dd = dd_opendir(work_dir, /*flags:*/ 0); if (!dd) /* dd_opendir already emitted error msg */ goto delete_bad_dir; /* Update count */ char *count_str = dd_load_text_ext(dd, FILENAME_COUNT, DD_FAIL_QUIETLY_ENOENT); unsigned long count = strtoul(count_str, NULL, 10); /* Don't increase crash count if we are working with newly uploaded * directory (remote crash) which already has its crash count set. */ if ((status != 0 && dup_of_dir) || count == 0) { count++; char new_count_str[sizeof(long)*3 + 2]; sprintf(new_count_str, "%lu", count); dd_save_text(dd, FILENAME_COUNT, new_count_str); /* This condition can be simplified to either * (status * != 0 && * dup_of_dir) or (count == 1). But the * chosen form is much more reliable and safe. We must not call * dd_opendir() to locked dd otherwise we go into a deadlock. */ if (strcmp(dd->dd_dirname, dirname) != 0) { /* Update the last occurrence file by the time file of the new problem */ struct dump_dir *new_dd = dd_opendir(dirname, DD_OPEN_READONLY); char *last_ocr = NULL; if (new_dd) { /* TIME must exists in a valid dump directory but we don't want to die * due to broken duplicated dump directory */ last_ocr = dd_load_text_ext(new_dd, FILENAME_TIME, DD_LOAD_TEXT_RETURN_NULL_ON_FAILURE | DD_FAIL_QUIETLY_ENOENT); dd_close(new_dd); } else { /* dd_opendir() already produced a message with good information about failure */ error_msg("Can't read the last occurrence file from the new dump directory."); } if (!last_ocr) { /* the new dump directory may lie in the dump location for some time */ log("Using current time for the last occurrence file which may be incorrect."); time_t t = time(NULL); last_ocr = xasprintf("%lu", (long)t); } dd_save_text(dd, FILENAME_LAST_OCCURRENCE, last_ocr); free(last_ocr); } } /* Reset mode/uig/gid to correct values for all files created by event run */ dd_sanitize_mode_and_owner(dd); dd_close(dd); if (!dup_of_dir) log_notice("New problem directory %s, processing", work_dir); else { log_warning("Deleting problem directory %s (dup of %s)", strrchr(dirname, '/') + 1, strrchr(dup_of_dir, '/') + 1); delete_dump_dir(dirname); } /* Run "notify[-dup]" event */ int fd; child_pid = spawn_event_handler_child( work_dir, (dup_of_dir ? "notify-dup" : "notify"), &fd ); //log("Started notify, fd %d -> %d", fd, child_stdout_fd); xmove_fd(fd, child_stdout_fd); child_is_post_create = 0; strbuf_clear(cmd_output); free(dup_of_dir); dup_of_dir = NULL; goto read_child_output; delete_bad_dir: log_warning("Deleting problem directory '%s'", dirname); delete_dump_dir(dirname); ret: strbuf_free(cmd_output); free(dup_of_dir); close(child_stdout_fd); return 0; } /* Create a new problem directory from client session. * Caller must ensure that all fields in struct client * are properly filled. */ static int create_problem_dir(GHashTable *problem_info, unsigned pid) { /* Exit if free space is less than 1/4 of MaxCrashReportsSize */ if (g_settings_nMaxCrashReportsSize > 0) { if (low_free_space(g_settings_nMaxCrashReportsSize, g_settings_dump_location)) exit(1); } /* Create temp directory with the problem data. * This directory is renamed to final directory name after * all files have been stored into it. */ gchar *dir_basename = g_hash_table_lookup(problem_info, "basename"); if (!dir_basename) dir_basename = g_hash_table_lookup(problem_info, FILENAME_TYPE); char *path = xasprintf("%s/%s-%s-%u.new", g_settings_dump_location, dir_basename, iso_date_string(NULL), pid); /* This item is useless, don't save it */ g_hash_table_remove(problem_info, "basename"); /* No need to check the path length, as all variables used are limited, * and dd_create() fails if the path is too long. */ struct dump_dir *dd = dd_create(path, client_uid, DEFAULT_DUMP_DIR_MODE); if (!dd) { error_msg_and_die("Error creating problem directory '%s'", path); } dd_create_basic_files(dd, client_uid, NULL); dd_save_text(dd, FILENAME_ABRT_VERSION, VERSION); gpointer gpkey = g_hash_table_lookup(problem_info, FILENAME_CMDLINE); if (!gpkey) { /* Obtain and save the command line. */ char *cmdline = get_cmdline(pid); if (cmdline) { dd_save_text(dd, FILENAME_CMDLINE, cmdline); free(cmdline); } } /* Store id of the user whose application crashed. */ char uid_str[sizeof(long) * 3 + 2]; sprintf(uid_str, "%lu", (long)client_uid); dd_save_text(dd, FILENAME_UID, uid_str); GHashTableIter iter; gpointer gpvalue; g_hash_table_iter_init(&iter, problem_info); while (g_hash_table_iter_next(&iter, &gpkey, &gpvalue)) { dd_save_text(dd, (gchar *) gpkey, (gchar *) gpvalue); } dd_close(dd); /* Not needing it anymore */ g_hash_table_destroy(problem_info); /* Move the completely created problem directory * to final directory. */ char *newpath = xstrndup(path, strlen(path) - strlen(".new")); if (rename(path, newpath) == 0) strcpy(path, newpath); free(newpath); log_notice("Saved problem directory of pid %u to '%s'", pid, path); /* We let the peer know that problem dir was created successfully * _before_ we run potentially long-running post-create. */ printf("HTTP/1.1 201 Created\r\n\r\n"); fflush(NULL); close(STDOUT_FILENO); xdup2(STDERR_FILENO, STDOUT_FILENO); /* paranoia: don't leave stdout fd closed */ /* Trim old problem directories if necessary */ if (g_settings_nMaxCrashReportsSize > 0) { trim_problem_dirs(g_settings_dump_location, g_settings_nMaxCrashReportsSize * (double)(1024*1024), path); } run_post_create(path); /* free(path); */ exit(0); } /* Checks if a string contains only printable characters. */ static gboolean printable_str(const char *str) { do { if ((unsigned char)(*str) < ' ' || *str == 0x7f) return FALSE; str++; } while (*str); return TRUE; } static gboolean is_correct_filename(const char *value) { return printable_str(value) && !strchr(value, '/') && !strchr(value, '.'); } static gboolean key_value_ok(gchar *key, gchar *value) { char *i; /* check key, it has to be valid filename and will end up in the * bugzilla */ for (i = key; *i != 0; i++) { if (!isalpha(*i) && (*i != '-') && (*i != '_') && (*i != ' ')) return FALSE; } /* check value of 'basename', it has to be valid non-hidden directory * name */ if (strcmp(key, "basename") == 0 || strcmp(key, FILENAME_TYPE) == 0 ) { if (!is_correct_filename(value)) { error_msg("Value of '%s' ('%s') is not a valid directory name", key, value); return FALSE; } } return TRUE; } /* Handles a message received from client over socket. */ static void process_message(GHashTable *problem_info, char *message) { gchar *key, *value; value = strchr(message, '='); if (value) { key = g_ascii_strdown(message, value - message); /* result is malloced */ //TODO: is it ok? it uses g_malloc, not malloc! value++; if (key_value_ok(key, value)) { if (strcmp(key, FILENAME_UID) == 0) { error_msg("Ignoring value of %s, will be determined later", FILENAME_UID); } else { g_hash_table_insert(problem_info, key, xstrdup(value)); /* Compat, delete when FILENAME_ANALYZER is replaced by FILENAME_TYPE: */ if (strcmp(key, FILENAME_TYPE) == 0) g_hash_table_insert(problem_info, xstrdup(FILENAME_ANALYZER), xstrdup(value)); /* Prevent freeing key later: */ key = NULL; } } else { /* should use error_msg_and_die() here? */ error_msg("Invalid key or value format: %s", message); } free(key); } else { /* should use error_msg_and_die() here? */ error_msg("Invalid message format: '%s'", message); } } static void die_if_data_is_missing(GHashTable *problem_info) { gboolean missing_data = FALSE; gchar **pstring; static const gchar *const needed[] = { FILENAME_TYPE, FILENAME_REASON, /* FILENAME_BACKTRACE, - ECC errors have no such elements */ /* FILENAME_EXECUTABLE, */ NULL }; for (pstring = (gchar**) needed; *pstring; pstring++) { if (!g_hash_table_lookup(problem_info, *pstring)) { error_msg("Element '%s' is missing", *pstring); missing_data = TRUE; } } if (missing_data) error_msg_and_die("Some data is missing, aborting"); } /* * Takes hash table, looks for key FILENAME_PID and tries to convert its value * to int. */ unsigned convert_pid(GHashTable *problem_info) { long ret; gchar *pid_str = (gchar *) g_hash_table_lookup(problem_info, FILENAME_PID); char *err_pos; if (!pid_str) error_msg_and_die("PID data is missing, aborting"); errno = 0; ret = strtol(pid_str, &err_pos, 10); if (errno || pid_str == err_pos || *err_pos != '\0' || ret > UINT_MAX || ret < 1) error_msg_and_die("Malformed or out-of-range PID number: '%s'", pid_str); return (unsigned) ret; } static int perform_http_xact(void) { /* use free instead of g_free so that we can use xstr* functions from * libreport/lib/xfuncs.c */ GHashTable *problem_info = g_hash_table_new_full(g_str_hash, g_str_equal, free, free); /* Read header */ char *body_start = NULL; char *messagebuf_data = NULL; unsigned messagebuf_len = 0; /* Loop until EOF/error/timeout/end_of_header */ while (1) { messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE); char *p = messagebuf_data + messagebuf_len; int rd = read(STDIN_FILENO, p, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); /* Check whether we see end of header */ /* Note: we support both [\r]\n\r\n and \n\n */ char *past_end = messagebuf_data + messagebuf_len; if (p > messagebuf_data+1) p -= 2; /* start search from two last bytes in last read - they might be '\n\r' */ while (p < past_end) { p = memchr(p, '\n', past_end - p); if (!p) break; p++; if (p >= past_end) break; if (*p == '\n' || (*p == '\r' && p+1 < past_end && p[1] == '\n') ) { body_start = p + 1 + (*p == '\r'); *p = '\0'; goto found_end_of_header; } } } /* while (read) */ found_end_of_header: ; log_debug("Request: %s", messagebuf_data); /* Sanitize and analyze header. * Header now is in messagebuf_data, NUL terminated string, * with last empty line deleted (by placement of NUL). * \r\n are not (yet) converted to \n, multi-line headers also * not converted. */ /* First line must be "op<space>[http://host]/path<space>HTTP/n.n". * <space> is exactly one space char. */ if (prefixcmp(messagebuf_data, "DELETE ") == 0) { messagebuf_data += strlen("DELETE "); char *space = strchr(messagebuf_data, ' '); if (!space || prefixcmp(space+1, "HTTP/") != 0) return 400; /* Bad Request */ *space = '\0'; //decode_url(messagebuf_data); %20 => ' ' alarm(0); return delete_path(messagebuf_data); } /* We erroneously used "PUT /" to create new problems. * POST is the correct request in this case: * "PUT /" implies creation or replace of resource named "/"! * Delete PUT in 2014. */ if (prefixcmp(messagebuf_data, "PUT ") != 0 && prefixcmp(messagebuf_data, "POST ") != 0 ) { return 400; /* Bad Request */ } enum { CREATION_NOTIFICATION, CREATION_REQUEST, }; int url_type; char *url = skip_non_whitespace(messagebuf_data) + 1; /* skip "POST " */ if (prefixcmp(url, "/creation_notification ") == 0) url_type = CREATION_NOTIFICATION; else if (prefixcmp(url, "/ ") == 0) url_type = CREATION_REQUEST; else return 400; /* Bad Request */ /* Read body */ if (!body_start) { log_warning("Premature EOF detected, exiting"); return 400; /* Bad Request */ } messagebuf_len -= (body_start - messagebuf_data); memmove(messagebuf_data, body_start, messagebuf_len); log_debug("Body so far: %u bytes, '%s'", messagebuf_len, messagebuf_data); /* Loop until EOF/error/timeout */ while (1) { if (url_type == CREATION_REQUEST) { while (1) { unsigned len = strnlen(messagebuf_data, messagebuf_len); if (len >= messagebuf_len) break; /* messagebuf has at least one NUL - process the line */ process_message(problem_info, messagebuf_data); messagebuf_len -= (len + 1); memmove(messagebuf_data, messagebuf_data + len + 1, messagebuf_len); } } messagebuf_data = xrealloc(messagebuf_data, messagebuf_len + INPUT_BUFFER_SIZE + 1); int rd = read(STDIN_FILENO, messagebuf_data + messagebuf_len, INPUT_BUFFER_SIZE); if (rd < 0) { if (errno == EINTR) /* SIGALRM? */ error_msg_and_die("Timed out"); perror_msg_and_die("read"); } if (rd == 0) break; log_debug("Received %u bytes of data", rd); messagebuf_len += rd; total_bytes_read += rd; if (total_bytes_read > MAX_MESSAGE_SIZE) error_msg_and_die("Message is too long, aborting"); } /* Body received, EOF was seen. Don't let alarm to interrupt after this. */ alarm(0); if (url_type == CREATION_NOTIFICATION) { messagebuf_data[messagebuf_len] = '\0'; return run_post_create(messagebuf_data); } /* Save problem dir */ int ret = 0; unsigned pid = convert_pid(problem_info); die_if_data_is_missing(problem_info); char *executable = g_hash_table_lookup(problem_info, FILENAME_EXECUTABLE); if (executable) { char *last_file = concat_path_file(g_settings_dump_location, "last-via-server"); int repeating_crash = check_recent_crash_file(last_file, executable); free(last_file); if (repeating_crash) /* Only pretend that we saved it */ goto out; /* ret is 0: "success" */ } #if 0 //TODO: /* At least it should generate local problem identifier UUID */ problem_data_add_basics(problem_info); //...the problem being that problem_info here is not a problem_data_t! #endif create_problem_dir(problem_info, pid); /* does not return */ out: g_hash_table_destroy(problem_info); return ret; /* Used as HTTP response code */ } static void dummy_handler(int sig_unused) {} int main(int argc, char **argv) { /* I18n */ setlocale(LC_ALL, ""); #if ENABLE_NLS bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); #endif abrt_init(argv); /* Can't keep these strings/structs static: _() doesn't support that */ const char *program_usage_string = _( "& [options]" ); enum { OPT_v = 1 << 0, OPT_u = 1 << 1, OPT_s = 1 << 2, OPT_p = 1 << 3, }; /* Keep enum above and order of options below in sync! */ struct options program_options[] = { OPT__VERBOSE(&g_verbose), OPT_INTEGER('u', NULL, &client_uid, _("Use NUM as client uid")), OPT_BOOL( 's', NULL, NULL , _("Log to syslog")), OPT_BOOL( 'p', NULL, NULL , _("Add program names to log")), OPT_END() }; unsigned opts = parse_opts(argc, argv, program_options, program_usage_string); export_abrt_envvars(opts & OPT_p); msg_prefix = xasprintf("%s[%u]", g_progname, getpid()); if (opts & OPT_s) { logmode = LOGMODE_JOURNAL; } /* Set up timeout handling */ /* Part 1 - need this to make SIGALRM interrupt syscalls * (as opposed to restarting them): I want read syscall to be interrupted */ struct sigaction sa; /* sa.sa_flags.SA_RESTART bit is clear: make signal interrupt syscalls */ memset(&sa, 0, sizeof(sa)); sa.sa_handler = dummy_handler; /* pity, SIG_DFL won't do */ sigaction(SIGALRM, &sa, NULL); /* Part 2 - set the timeout per se */ alarm(TIMEOUT); if (client_uid == (uid_t)-1L) { /* Get uid of the connected client */ struct ucred cr; socklen_t crlen = sizeof(cr); if (0 != getsockopt(STDIN_FILENO, SOL_SOCKET, SO_PEERCRED, &cr, &crlen)) perror_msg_and_die("getsockopt(SO_PEERCRED)"); if (crlen != sizeof(cr)) error_msg_and_die("%s: bad crlen %d", "getsockopt(SO_PEERCRED)", (int)crlen); client_uid = cr.uid; } load_abrt_conf(); int r = perform_http_xact(); if (r == 0) r = 200; free_abrt_conf_data(); printf("HTTP/1.1 %u \r\n\r\n", r); return (r >= 400); /* Error if 400+ */ } #if 0 // TODO: example of SSLed connection #include <openssl/ssl.h> #include <openssl/err.h> if (flags & OPT_SSL) { /* load key and cert files */ SSL_CTX *ctx; SSL *ssl; ctx = init_ssl_context(); if (SSL_CTX_use_certificate_file(ctx, cert_path, SSL_FILETYPE_PEM) <= 0 || SSL_CTX_use_PrivateKey_file(ctx, key_path, SSL_FILETYPE_PEM) <= 0 ) { ERR_print_errors_fp(stderr); error_msg_and_die("SSL certificates err\n"); } if (!SSL_CTX_check_private_key(ctx)) { error_msg_and_die("Private key does not match public key\n"); } (void)SSL_CTX_set_mode(ctx, SSL_MODE_AUTO_RETRY); //TODO more errors? ssl = SSL_new(ctx); SSL_set_fd(ssl, sockfd_in); //SSL_set_accept_state(ssl); if (SSL_accept(ssl) == 1) { //while whatever serve while (serve(ssl, flags)) continue; //TODO errors SSL_shutdown(ssl); } SSL_free(ssl); SSL_CTX_free(ctx); } else { while (serve(&sockfd_in, flags)) continue; } err = (flags & OPT_SSL) ? SSL_read(sock, buffer, READ_BUF-1): read(*(int*)sock, buffer, READ_BUF-1); if ( err < 0 ) { //TODO handle errno || SSL_get_error(ssl,err); break; } if ( err == 0 ) break; if (!head) { buffer[err] = '\0'; clean[i%2] = delete_cr(buffer); cut = g_strstr_len(buffer, -1, "\n\n"); if ( cut == NULL ) { g_string_append(headers, buffer); } else { g_string_append_len(headers, buffer, cut-buffer); } } /* end of header section? */ if ( !head && ( cut != NULL || (clean[(i+1)%2] && buffer[0]=='\n') ) ) { parse_head(&request, headers); head = TRUE; c_len = has_body(&request); if ( c_len ) { //if we want to read body some day - this will be the right place to begin //malloc body append rest of the (fixed) buffer at the beginning of a body //if clean buffer[1]; } else { break; } break; //because we don't support body yet } else if ( head == TRUE ) { /* body-reading stuff * read body, check content-len * save body to request */ break; } else { // count header size len += err; if ( len > READ_BUF-1 ) { //TODO header is too long break; } } i++; } g_string_free(headers, true); //because we allocated it rt = generate_response(&request, &response); /* write headers */ if ( flags & OPT_SSL ) { //TODO err err = SSL_write(sock, response.response_line, strlen(response.response_line)); err = SSL_write(sock, response.head->str , strlen(response.head->str)); err = SSL_write(sock, "\r\n", 2); } else { //TODO err err = write(*(int*)sock, response.response_line, strlen(response.response_line)); err = write(*(int*)sock, response.head->str , strlen(response.head->str)); err = write(*(int*)sock, "\r\n", 2); } #endif
./CrossVul/dataset_final_sorted/CWE-200/c/bad_1508_0
crossvul-cpp_data_good_2751_0
/****************************************************************************** * * Module Name: psobject - Support for parse objects * *****************************************************************************/ /****************************************************************************** * * 1. Copyright Notice * * Some or all of this work - Copyright (c) 1999 - 2017, Intel Corp. * All rights reserved. * * 2. License * * 2.1. This is your license from Intel Corp. under its intellectual property * rights. You may have additional license terms from the party that provided * you this software, covering your right to use that party's intellectual * property rights. * * 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a * copy of the source code appearing in this file ("Covered Code") an * irrevocable, perpetual, worldwide license under Intel's copyrights in the * base code distributed originally by Intel ("Original Intel Code") to copy, * make derivatives, distribute, use and display any portion of the Covered * Code in any form, with the right to sublicense such rights; and * * 2.3. Intel grants Licensee a non-exclusive and non-transferable patent * license (with the right to sublicense), under only those claims of Intel * patents that are infringed by the Original Intel Code, to make, use, sell, * offer to sell, and import the Covered Code and derivative works thereof * solely to the minimum extent necessary to exercise the above copyright * license, and in no event shall the patent license extend to any additions * to or modifications of the Original Intel Code. No other license or right * is granted directly or by implication, estoppel or otherwise; * * The above copyright and patent license is granted only if the following * conditions are met: * * 3. Conditions * * 3.1. Redistribution of Source with Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification with rights to further distribute source must include * the above Copyright Notice, the above License, this list of Conditions, * and the following Disclaimer and Export Compliance provision. In addition, * Licensee must cause all Covered Code to which Licensee contributes to * contain a file documenting the changes Licensee made to create that Covered * Code and the date of any change. Licensee must include in that file the * documentation of any changes made by any predecessor Licensee. Licensee * must include a prominent statement that the modification is derived, * directly or indirectly, from Original Intel Code. * * 3.2. Redistribution of Source with no Rights to Further Distribute Source. * Redistribution of source code of any substantial portion of the Covered * Code or modification without rights to further distribute source must * include the following Disclaimer and Export Compliance provision in the * documentation and/or other materials provided with distribution. In * addition, Licensee may not authorize further sublicense of source of any * portion of the Covered Code, and must include terms to the effect that the * license from Licensee to its licensee is limited to the intellectual * property embodied in the software Licensee provides to its licensee, and * not to intellectual property embodied in modifications its licensee may * make. * * 3.3. Redistribution of Executable. Redistribution in executable form of any * substantial portion of the Covered Code or modification must reproduce the * above Copyright Notice, and the following Disclaimer and Export Compliance * provision in the documentation and/or other materials provided with the * distribution. * * 3.4. Intel retains all right, title, and interest in and to the Original * Intel Code. * * 3.5. Neither the name Intel nor any other trademark owned or controlled by * Intel shall be used in advertising or otherwise to promote the sale, use or * other dealings in products derived from or relating to the Covered Code * without prior written authorization from Intel. * * 4. Disclaimer and Export Compliance * * 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED * HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE * IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE, * INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY * UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY * IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A * PARTICULAR PURPOSE. * * 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES * OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR * COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT, * SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY * CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL * HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS * SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY * LIMITED REMEDY. * * 4.3. Licensee shall not export, either directly or indirectly, any of this * software or system incorporating such software without first obtaining any * required license or other approval from the U. S. Department of Commerce or * any other agency or department of the United States Government. In the * event Licensee exports any such software from the United States or * re-exports any such software from a foreign destination, Licensee shall * ensure that the distribution and export/re-export of the software is in * compliance with all laws, regulations, orders, or other restrictions of the * U.S. Export Administration Regulations. Licensee agrees that neither it nor * any of its subsidiaries will export/re-export any technical data, process, * software, or service, directly or indirectly, to any country for which the * United States government or any agency thereof requires an export license, * other governmental approval, or letter of assurance, without first obtaining * such license, approval or letter. * ***************************************************************************** * * Alternatively, you may choose to be licensed under the terms of the * following license: * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions, and the following disclaimer, * without modification. * 2. Redistributions in binary form must reproduce at minimum a disclaimer * substantially similar to the "NO WARRANTY" disclaimer below * ("Disclaimer") and any redistribution must be conditioned upon * including a substantially similar Disclaimer requirement for further * binary redistribution. * 3. Neither the names of the above-listed copyright holders nor the names * of any contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * Alternatively, you may choose to be licensed under the terms of the * GNU General Public License ("GPL") version 2 as published by the Free * Software Foundation. * *****************************************************************************/ #include "acpi.h" #include "accommon.h" #include "acparser.h" #include "amlcode.h" #include "acconvert.h" #define _COMPONENT ACPI_PARSER ACPI_MODULE_NAME ("psobject") /* Local prototypes */ static ACPI_STATUS AcpiPsGetAmlOpcode ( ACPI_WALK_STATE *WalkState); /******************************************************************************* * * FUNCTION: AcpiPsGetAmlOpcode * * PARAMETERS: WalkState - Current state * * RETURN: Status * * DESCRIPTION: Extract the next AML opcode from the input stream. * ******************************************************************************/ static ACPI_STATUS AcpiPsGetAmlOpcode ( ACPI_WALK_STATE *WalkState) { UINT32 AmlOffset; ACPI_FUNCTION_TRACE_PTR (PsGetAmlOpcode, WalkState); WalkState->Aml = WalkState->ParserState.Aml; WalkState->Opcode = AcpiPsPeekOpcode (&(WalkState->ParserState)); /* * First cut to determine what we have found: * 1) A valid AML opcode * 2) A name string * 3) An unknown/invalid opcode */ WalkState->OpInfo = AcpiPsGetOpcodeInfo (WalkState->Opcode); switch (WalkState->OpInfo->Class) { case AML_CLASS_ASCII: case AML_CLASS_PREFIX: /* * Starts with a valid prefix or ASCII char, this is a name * string. Convert the bare name string to a namepath. */ WalkState->Opcode = AML_INT_NAMEPATH_OP; WalkState->ArgTypes = ARGP_NAMESTRING; break; case AML_CLASS_UNKNOWN: /* The opcode is unrecognized. Complain and skip unknown opcodes */ if (WalkState->PassNumber == 2) { AmlOffset = (UINT32) ACPI_PTR_DIFF (WalkState->Aml, WalkState->ParserState.AmlStart); ACPI_ERROR ((AE_INFO, "Unknown opcode 0x%.2X at table offset 0x%.4X, ignoring", WalkState->Opcode, (UINT32) (AmlOffset + sizeof (ACPI_TABLE_HEADER)))); ACPI_DUMP_BUFFER ((WalkState->ParserState.Aml - 16), 48); #ifdef ACPI_ASL_COMPILER /* * This is executed for the disassembler only. Output goes * to the disassembled ASL output file. */ AcpiOsPrintf ( "/*\nError: Unknown opcode 0x%.2X at table offset 0x%.4X, context:\n", WalkState->Opcode, (UINT32) (AmlOffset + sizeof (ACPI_TABLE_HEADER))); ACPI_ERROR ((AE_INFO, "Aborting disassembly, AML byte code is corrupt")); /* Dump the context surrounding the invalid opcode */ AcpiUtDumpBuffer (((UINT8 *) WalkState->ParserState.Aml - 16), 48, DB_BYTE_DISPLAY, (AmlOffset + sizeof (ACPI_TABLE_HEADER) - 16)); AcpiOsPrintf (" */\n"); /* * Just abort the disassembly, cannot continue because the * parser is essentially lost. The disassembler can then * randomly fail because an ill-constructed parse tree * can result. */ return_ACPI_STATUS (AE_AML_BAD_OPCODE); #endif } /* Increment past one-byte or two-byte opcode */ WalkState->ParserState.Aml++; if (WalkState->Opcode > 0xFF) /* Can only happen if first byte is 0x5B */ { WalkState->ParserState.Aml++; } return_ACPI_STATUS (AE_CTRL_PARSE_CONTINUE); default: /* Found opcode info, this is a normal opcode */ WalkState->ParserState.Aml += AcpiPsGetOpcodeSize (WalkState->Opcode); WalkState->ArgTypes = WalkState->OpInfo->ParseArgs; break; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiPsBuildNamedOp * * PARAMETERS: WalkState - Current state * AmlOpStart - Begin of named Op in AML * UnnamedOp - Early Op (not a named Op) * Op - Returned Op * * RETURN: Status * * DESCRIPTION: Parse a named Op * ******************************************************************************/ ACPI_STATUS AcpiPsBuildNamedOp ( ACPI_WALK_STATE *WalkState, UINT8 *AmlOpStart, ACPI_PARSE_OBJECT *UnnamedOp, ACPI_PARSE_OBJECT **Op) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Arg = NULL; ACPI_FUNCTION_TRACE_PTR (PsBuildNamedOp, WalkState); UnnamedOp->Common.Value.Arg = NULL; UnnamedOp->Common.ArgListLength = 0; UnnamedOp->Common.AmlOpcode = WalkState->Opcode; /* * Get and append arguments until we find the node that contains * the name (the type ARGP_NAME). */ while (GET_CURRENT_ARG_TYPE (WalkState->ArgTypes) && (GET_CURRENT_ARG_TYPE (WalkState->ArgTypes) != ARGP_NAME)) { ASL_CV_CAPTURE_COMMENTS (WalkState); Status = AcpiPsGetNextArg (WalkState, &(WalkState->ParserState), GET_CURRENT_ARG_TYPE (WalkState->ArgTypes), &Arg); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } AcpiPsAppendArg (UnnamedOp, Arg); INCREMENT_ARG_LIST (WalkState->ArgTypes); } /* are there any inline comments associated with the NameSeg?? If so, save this. */ ASL_CV_CAPTURE_COMMENTS (WalkState); #ifdef ACPI_ASL_COMPILER if (AcpiGbl_CurrentInlineComment != NULL) { UnnamedOp->Common.NameComment = AcpiGbl_CurrentInlineComment; AcpiGbl_CurrentInlineComment = NULL; } #endif /* * Make sure that we found a NAME and didn't run out of arguments */ if (!GET_CURRENT_ARG_TYPE (WalkState->ArgTypes)) { return_ACPI_STATUS (AE_AML_NO_OPERAND); } /* We know that this arg is a name, move to next arg */ INCREMENT_ARG_LIST (WalkState->ArgTypes); /* * Find the object. This will either insert the object into * the namespace or simply look it up */ WalkState->Op = NULL; Status = WalkState->DescendingCallback (WalkState, Op); if (ACPI_FAILURE (Status)) { if (Status != AE_CTRL_TERMINATE) { ACPI_EXCEPTION ((AE_INFO, Status, "During name lookup/catalog")); } return_ACPI_STATUS (Status); } if (!*Op) { return_ACPI_STATUS (AE_CTRL_PARSE_CONTINUE); } Status = AcpiPsNextParseState (WalkState, *Op, Status); if (ACPI_FAILURE (Status)) { if (Status == AE_CTRL_PENDING) { Status = AE_CTRL_PARSE_PENDING; } return_ACPI_STATUS (Status); } AcpiPsAppendArg (*Op, UnnamedOp->Common.Value.Arg); #ifdef ACPI_ASL_COMPILER /* save any comments that might be associated with UnnamedOp. */ (*Op)->Common.InlineComment = UnnamedOp->Common.InlineComment; (*Op)->Common.EndNodeComment = UnnamedOp->Common.EndNodeComment; (*Op)->Common.CloseBraceComment = UnnamedOp->Common.CloseBraceComment; (*Op)->Common.NameComment = UnnamedOp->Common.NameComment; (*Op)->Common.CommentList = UnnamedOp->Common.CommentList; (*Op)->Common.EndBlkComment = UnnamedOp->Common.EndBlkComment; (*Op)->Common.CvFilename = UnnamedOp->Common.CvFilename; (*Op)->Common.CvParentFilename = UnnamedOp->Common.CvParentFilename; (*Op)->Named.Aml = UnnamedOp->Common.Aml; UnnamedOp->Common.InlineComment = NULL; UnnamedOp->Common.EndNodeComment = NULL; UnnamedOp->Common.CloseBraceComment = NULL; UnnamedOp->Common.NameComment = NULL; UnnamedOp->Common.CommentList = NULL; UnnamedOp->Common.EndBlkComment = NULL; #endif if ((*Op)->Common.AmlOpcode == AML_REGION_OP || (*Op)->Common.AmlOpcode == AML_DATA_REGION_OP) { /* * Defer final parsing of an OperationRegion body, because we don't * have enough info in the first pass to parse it correctly (i.e., * there may be method calls within the TermArg elements of the body.) * * However, we must continue parsing because the opregion is not a * standalone package -- we don't know where the end is at this point. * * (Length is unknown until parse of the body complete) */ (*Op)->Named.Data = AmlOpStart; (*Op)->Named.Length = 0; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiPsCreateOp * * PARAMETERS: WalkState - Current state * AmlOpStart - Op start in AML * NewOp - Returned Op * * RETURN: Status * * DESCRIPTION: Get Op from AML * ******************************************************************************/ ACPI_STATUS AcpiPsCreateOp ( ACPI_WALK_STATE *WalkState, UINT8 *AmlOpStart, ACPI_PARSE_OBJECT **NewOp) { ACPI_STATUS Status = AE_OK; ACPI_PARSE_OBJECT *Op; ACPI_PARSE_OBJECT *NamedOp = NULL; ACPI_PARSE_OBJECT *ParentScope; UINT8 ArgumentCount; const ACPI_OPCODE_INFO *OpInfo; ACPI_FUNCTION_TRACE_PTR (PsCreateOp, WalkState); Status = AcpiPsGetAmlOpcode (WalkState); if (Status == AE_CTRL_PARSE_CONTINUE) { return_ACPI_STATUS (AE_CTRL_PARSE_CONTINUE); } if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } /* Create Op structure and append to parent's argument list */ WalkState->OpInfo = AcpiPsGetOpcodeInfo (WalkState->Opcode); Op = AcpiPsAllocOp (WalkState->Opcode, AmlOpStart); if (!Op) { return_ACPI_STATUS (AE_NO_MEMORY); } if (WalkState->OpInfo->Flags & AML_NAMED) { Status = AcpiPsBuildNamedOp (WalkState, AmlOpStart, Op, &NamedOp); AcpiPsFreeOp (Op); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } *NewOp = NamedOp; return_ACPI_STATUS (AE_OK); } /* Not a named opcode, just allocate Op and append to parent */ if (WalkState->OpInfo->Flags & AML_CREATE) { /* * Backup to beginning of CreateXXXfield declaration * BodyLength is unknown until we parse the body */ Op->Named.Data = AmlOpStart; Op->Named.Length = 0; } if (WalkState->Opcode == AML_BANK_FIELD_OP) { /* * Backup to beginning of BankField declaration * BodyLength is unknown until we parse the body */ Op->Named.Data = AmlOpStart; Op->Named.Length = 0; } ParentScope = AcpiPsGetParentScope (&(WalkState->ParserState)); AcpiPsAppendArg (ParentScope, Op); if (ParentScope) { OpInfo = AcpiPsGetOpcodeInfo (ParentScope->Common.AmlOpcode); if (OpInfo->Flags & AML_HAS_TARGET) { ArgumentCount = AcpiPsGetArgumentCount (OpInfo->Type); if (ParentScope->Common.ArgListLength > ArgumentCount) { Op->Common.Flags |= ACPI_PARSEOP_TARGET; } } /* * Special case for both Increment() and Decrement(), where * the lone argument is both a source and a target. */ else if ((ParentScope->Common.AmlOpcode == AML_INCREMENT_OP) || (ParentScope->Common.AmlOpcode == AML_DECREMENT_OP)) { Op->Common.Flags |= ACPI_PARSEOP_TARGET; } } if (WalkState->DescendingCallback != NULL) { /* * Find the object. This will either insert the object into * the namespace or simply look it up */ WalkState->Op = *NewOp = Op; Status = WalkState->DescendingCallback (WalkState, &Op); Status = AcpiPsNextParseState (WalkState, Op, Status); if (Status == AE_CTRL_PENDING) { Status = AE_CTRL_PARSE_PENDING; } } return_ACPI_STATUS (Status); } /******************************************************************************* * * FUNCTION: AcpiPsCompleteOp * * PARAMETERS: WalkState - Current state * Op - Returned Op * Status - Parse status before complete Op * * RETURN: Status * * DESCRIPTION: Complete Op * ******************************************************************************/ ACPI_STATUS AcpiPsCompleteOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT **Op, ACPI_STATUS Status) { ACPI_STATUS Status2; ACPI_FUNCTION_TRACE_PTR (PsCompleteOp, WalkState); /* * Finished one argument of the containing scope */ WalkState->ParserState.Scope->ParseScope.ArgCount--; /* Close this Op (will result in parse subtree deletion) */ Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } *Op = NULL; switch (Status) { case AE_OK: break; case AE_CTRL_TRANSFER: /* We are about to transfer to a called method */ WalkState->PrevOp = NULL; WalkState->PrevArgTypes = WalkState->ArgTypes; return_ACPI_STATUS (Status); case AE_CTRL_END: AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); if (*Op) { WalkState->Op = *Op; WalkState->OpInfo = AcpiPsGetOpcodeInfo ((*Op)->Common.AmlOpcode); WalkState->Opcode = (*Op)->Common.AmlOpcode; Status = WalkState->AscendingCallback (WalkState); Status = AcpiPsNextParseState (WalkState, *Op, Status); Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } } Status = AE_OK; break; case AE_CTRL_BREAK: case AE_CTRL_CONTINUE: /* Pop off scopes until we find the While */ while (!(*Op) || ((*Op)->Common.AmlOpcode != AML_WHILE_OP)) { AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); } /* Close this iteration of the While loop */ WalkState->Op = *Op; WalkState->OpInfo = AcpiPsGetOpcodeInfo ((*Op)->Common.AmlOpcode); WalkState->Opcode = (*Op)->Common.AmlOpcode; Status = WalkState->AscendingCallback (WalkState); Status = AcpiPsNextParseState (WalkState, *Op, Status); Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } Status = AE_OK; break; case AE_CTRL_TERMINATE: /* Clean up */ do { if (*Op) { Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } AcpiUtDeleteGenericState ( AcpiUtPopGenericState (&WalkState->ControlState)); } AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (*Op); return_ACPI_STATUS (AE_OK); default: /* All other non-AE_OK status */ do { if (*Op) { Status2 = AcpiPsCompleteThisOp (WalkState, *Op); if (ACPI_FAILURE (Status2)) { return_ACPI_STATUS (Status2); } } AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (*Op); #if 0 /* * TBD: Cleanup parse ops on error */ if (*Op == NULL) { AcpiPsPopScope (ParserState, Op, &WalkState->ArgTypes, &WalkState->ArgCount); } #endif WalkState->PrevOp = NULL; WalkState->PrevArgTypes = WalkState->ArgTypes; return_ACPI_STATUS (Status); } /* This scope complete? */ if (AcpiPsHasCompletedScope (&(WalkState->ParserState))) { AcpiPsPopScope (&(WalkState->ParserState), Op, &WalkState->ArgTypes, &WalkState->ArgCount); ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "Popped scope, Op=%p\n", *Op)); } else { *Op = NULL; } return_ACPI_STATUS (AE_OK); } /******************************************************************************* * * FUNCTION: AcpiPsCompleteFinalOp * * PARAMETERS: WalkState - Current state * Op - Current Op * Status - Current parse status before complete last * Op * * RETURN: Status * * DESCRIPTION: Complete last Op. * ******************************************************************************/ ACPI_STATUS AcpiPsCompleteFinalOp ( ACPI_WALK_STATE *WalkState, ACPI_PARSE_OBJECT *Op, ACPI_STATUS Status) { ACPI_STATUS ReturnStatus = AE_OK; BOOLEAN Ascending = TRUE; ACPI_FUNCTION_TRACE_PTR (PsCompleteFinalOp, WalkState); /* * Complete the last Op (if not completed), and clear the scope stack. * It is easily possible to end an AML "package" with an unbounded number * of open scopes (such as when several ASL blocks are closed with * sequential closing braces). We want to terminate each one cleanly. */ ACPI_DEBUG_PRINT ((ACPI_DB_PARSE, "AML package complete at Op %p\n", Op)); do { if (Op) { if (Ascending && WalkState->AscendingCallback != NULL) { WalkState->Op = Op; WalkState->OpInfo = AcpiPsGetOpcodeInfo (Op->Common.AmlOpcode); WalkState->Opcode = Op->Common.AmlOpcode; Status = WalkState->AscendingCallback (WalkState); Status = AcpiPsNextParseState (WalkState, Op, Status); if (Status == AE_CTRL_PENDING) { Status = AcpiPsCompleteOp (WalkState, &Op, AE_OK); if (ACPI_FAILURE (Status)) { return_ACPI_STATUS (Status); } } if (Status == AE_CTRL_TERMINATE) { Ascending = FALSE; ReturnStatus = AE_CTRL_TERMINATE; } else if (ACPI_FAILURE (Status)) { /* First error is most important */ Ascending = FALSE; ReturnStatus = Status; } } Status = AcpiPsCompleteThisOp (WalkState, Op); if (ACPI_FAILURE (Status)) { Ascending = FALSE; if (ACPI_SUCCESS (ReturnStatus) || ReturnStatus == AE_CTRL_TERMINATE) { ReturnStatus = Status; } } } AcpiPsPopScope (&(WalkState->ParserState), &Op, &WalkState->ArgTypes, &WalkState->ArgCount); } while (Op); return_ACPI_STATUS (ReturnStatus); }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2751_0
crossvul-cpp_data_good_2490_3
/* Copyright (c) 2001 Matej Pfajfar. * Copyright (c) 2001-2004, Roger Dingledine. * Copyright (c) 2004-2006, Roger Dingledine, Nick Mathewson. * Copyright (c) 2007-2016, The Tor Project, Inc. */ /* See LICENSE for licensing information */ /** * \file nodelist.c * * \brief Structures and functions for tracking what we know about the routers * on the Tor network, and correlating information from networkstatus, * routerinfo, and microdescs. * * The key structure here is node_t: that's the canonical way to refer * to a Tor relay that we might want to build a circuit through. Every * node_t has either a routerinfo_t, or a routerstatus_t from the current * networkstatus consensus. If it has a routerstatus_t, it will also * need to have a microdesc_t before you can use it for circuits. * * The nodelist_t is a global singleton that maps identities to node_t * objects. Access them with the node_get_*() functions. The nodelist_t * is maintained by calls throughout the codebase * * Generally, other code should not have to reach inside a node_t to * see what information it has. Instead, you should call one of the * many accessor functions that works on a generic node_t. If there * isn't one that does what you need, it's better to make such a function, * and then use it. * * For historical reasons, some of the functions that select a node_t * from the list of all usable node_t objects are in the routerlist.c * module, since they originally selected a routerinfo_t. (TODO: They * should move!) * * (TODO: Perhaps someday we should abstract the remaining ways of * talking about a relay to also be node_t instances. Those would be * routerstatus_t as used for directory requests, and dir_server_t as * used for authorities and fallback directories.) */ #include "or.h" #include "address.h" #include "config.h" #include "control.h" #include "dirserv.h" #include "entrynodes.h" #include "geoip.h" #include "main.h" #include "microdesc.h" #include "networkstatus.h" #include "nodelist.h" #include "policies.h" #include "protover.h" #include "rendservice.h" #include "router.h" #include "routerlist.h" #include "routerset.h" #include "torcert.h" #include <string.h> static void nodelist_drop_node(node_t *node, int remove_from_ht); static void node_free(node_t *node); /** count_usable_descriptors counts descriptors with these flag(s) */ typedef enum { /* All descriptors regardless of flags */ USABLE_DESCRIPTOR_ALL = 0, /* Only descriptors with the Exit flag */ USABLE_DESCRIPTOR_EXIT_ONLY = 1 } usable_descriptor_t; static void count_usable_descriptors(int *num_present, int *num_usable, smartlist_t *descs_out, const networkstatus_t *consensus, const or_options_t *options, time_t now, routerset_t *in_set, usable_descriptor_t exit_only); static void update_router_have_minimum_dir_info(void); static double get_frac_paths_needed_for_circs(const or_options_t *options, const networkstatus_t *ns); /** A nodelist_t holds a node_t object for every router we're "willing to use * for something". Specifically, it should hold a node_t for every node that * is currently in the routerlist, or currently in the consensus we're using. */ typedef struct nodelist_t { /* A list of all the nodes. */ smartlist_t *nodes; /* Hash table to map from node ID digest to node. */ HT_HEAD(nodelist_map, node_t) nodes_by_id; } nodelist_t; static inline unsigned int node_id_hash(const node_t *node) { return (unsigned) siphash24g(node->identity, DIGEST_LEN); } static inline unsigned int node_id_eq(const node_t *node1, const node_t *node2) { return tor_memeq(node1->identity, node2->identity, DIGEST_LEN); } HT_PROTOTYPE(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq) HT_GENERATE2(nodelist_map, node_t, ht_ent, node_id_hash, node_id_eq, 0.6, tor_reallocarray_, tor_free_) /** The global nodelist. */ static nodelist_t *the_nodelist=NULL; /** Create an empty nodelist if we haven't done so already. */ static void init_nodelist(void) { if (PREDICT_UNLIKELY(the_nodelist == NULL)) { the_nodelist = tor_malloc_zero(sizeof(nodelist_t)); HT_INIT(nodelist_map, &the_nodelist->nodes_by_id); the_nodelist->nodes = smartlist_new(); } } /** As node_get_by_id, but returns a non-const pointer */ node_t * node_get_mutable_by_id(const char *identity_digest) { node_t search, *node; if (PREDICT_UNLIKELY(the_nodelist == NULL)) return NULL; memcpy(&search.identity, identity_digest, DIGEST_LEN); node = HT_FIND(nodelist_map, &the_nodelist->nodes_by_id, &search); return node; } /** Return the node_t whose identity is <b>identity_digest</b>, or NULL * if no such node exists. */ MOCK_IMPL(const node_t *, node_get_by_id,(const char *identity_digest)) { return node_get_mutable_by_id(identity_digest); } /** Internal: return the node_t whose identity_digest is * <b>identity_digest</b>. If none exists, create a new one, add it to the * nodelist, and return it. * * Requires that the nodelist be initialized. */ static node_t * node_get_or_create(const char *identity_digest) { node_t *node; if ((node = node_get_mutable_by_id(identity_digest))) return node; node = tor_malloc_zero(sizeof(node_t)); memcpy(node->identity, identity_digest, DIGEST_LEN); HT_INSERT(nodelist_map, &the_nodelist->nodes_by_id, node); smartlist_add(the_nodelist->nodes, node); node->nodelist_idx = smartlist_len(the_nodelist->nodes) - 1; node->country = -1; return node; } /** Called when a node's address changes. */ static void node_addrs_changed(node_t *node) { node->last_reachable = node->last_reachable6 = 0; node->country = -1; } /** Add <b>ri</b> to an appropriate node in the nodelist. If we replace an * old routerinfo, and <b>ri_old_out</b> is not NULL, set *<b>ri_old_out</b> * to the previous routerinfo. */ node_t * nodelist_set_routerinfo(routerinfo_t *ri, routerinfo_t **ri_old_out) { node_t *node; const char *id_digest; int had_router = 0; tor_assert(ri); init_nodelist(); id_digest = ri->cache_info.identity_digest; node = node_get_or_create(id_digest); if (node->ri) { if (!routers_have_same_or_addrs(node->ri, ri)) { node_addrs_changed(node); } had_router = 1; if (ri_old_out) *ri_old_out = node->ri; } else { if (ri_old_out) *ri_old_out = NULL; } node->ri = ri; if (node->country == -1) node_set_country(node); if (authdir_mode(get_options()) && !had_router) { const char *discard=NULL; uint32_t status = dirserv_router_get_status(ri, &discard, LOG_INFO); dirserv_set_node_flags_from_authoritative_status(node, status); } return node; } /** Set the appropriate node_t to use <b>md</b> as its microdescriptor. * * Called when a new microdesc has arrived and the usable consensus flavor * is "microdesc". **/ node_t * nodelist_add_microdesc(microdesc_t *md) { networkstatus_t *ns = networkstatus_get_latest_consensus_by_flavor(FLAV_MICRODESC); const routerstatus_t *rs; node_t *node; if (ns == NULL) return NULL; init_nodelist(); /* Microdescriptors don't carry an identity digest, so we need to figure * it out by looking up the routerstatus. */ rs = router_get_consensus_status_by_descriptor_digest(ns, md->digest); if (rs == NULL) return NULL; node = node_get_mutable_by_id(rs->identity_digest); if (node) { if (node->md) node->md->held_by_nodes--; node->md = md; md->held_by_nodes++; } return node; } /** Tell the nodelist that the current usable consensus is <b>ns</b>. * This makes the nodelist change all of the routerstatus entries for * the nodes, drop nodes that no longer have enough info to get used, * and grab microdescriptors into nodes as appropriate. */ void nodelist_set_consensus(networkstatus_t *ns) { const or_options_t *options = get_options(); int authdir = authdir_mode_v3(options); init_nodelist(); if (ns->flavor == FLAV_MICRODESC) (void) get_microdesc_cache(); /* Make sure it exists first. */ SMARTLIST_FOREACH(the_nodelist->nodes, node_t *, node, node->rs = NULL); SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) { node_t *node = node_get_or_create(rs->identity_digest); node->rs = rs; if (ns->flavor == FLAV_MICRODESC) { if (node->md == NULL || tor_memneq(node->md->digest,rs->descriptor_digest,DIGEST256_LEN)) { if (node->md) node->md->held_by_nodes--; node->md = microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest); if (node->md) node->md->held_by_nodes++; } } node_set_country(node); /* If we're not an authdir, believe others. */ if (!authdir) { node->is_valid = rs->is_valid; node->is_running = rs->is_flagged_running; node->is_fast = rs->is_fast; node->is_stable = rs->is_stable; node->is_possible_guard = rs->is_possible_guard; node->is_exit = rs->is_exit; node->is_bad_exit = rs->is_bad_exit; node->is_hs_dir = rs->is_hs_dir; node->ipv6_preferred = 0; if (fascist_firewall_prefer_ipv6_orport(options) && (tor_addr_is_null(&rs->ipv6_addr) == 0 || (node->md && tor_addr_is_null(&node->md->ipv6_addr) == 0))) node->ipv6_preferred = 1; } } SMARTLIST_FOREACH_END(rs); nodelist_purge(); if (! authdir) { SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { /* We have no routerstatus for this router. Clear flags so we can skip * it, maybe.*/ if (!node->rs) { tor_assert(node->ri); /* if it had only an md, or nothing, purge * would have removed it. */ if (node->ri->purpose == ROUTER_PURPOSE_GENERAL) { /* Clear all flags. */ node->is_valid = node->is_running = node->is_hs_dir = node->is_fast = node->is_stable = node->is_possible_guard = node->is_exit = node->is_bad_exit = node->ipv6_preferred = 0; } } } SMARTLIST_FOREACH_END(node); } } /** Helper: return true iff a node has a usable amount of information*/ static inline int node_is_usable(const node_t *node) { return (node->rs) || (node->ri); } /** Tell the nodelist that <b>md</b> is no longer a microdescriptor for the * node with <b>identity_digest</b>. */ void nodelist_remove_microdesc(const char *identity_digest, microdesc_t *md) { node_t *node = node_get_mutable_by_id(identity_digest); if (node && node->md == md) { node->md = NULL; md->held_by_nodes--; } } /** Tell the nodelist that <b>ri</b> is no longer in the routerlist. */ void nodelist_remove_routerinfo(routerinfo_t *ri) { node_t *node = node_get_mutable_by_id(ri->cache_info.identity_digest); if (node && node->ri == ri) { node->ri = NULL; if (! node_is_usable(node)) { nodelist_drop_node(node, 1); node_free(node); } } } /** Remove <b>node</b> from the nodelist. (Asserts that it was there to begin * with.) */ static void nodelist_drop_node(node_t *node, int remove_from_ht) { node_t *tmp; int idx; if (remove_from_ht) { tmp = HT_REMOVE(nodelist_map, &the_nodelist->nodes_by_id, node); tor_assert(tmp == node); } idx = node->nodelist_idx; tor_assert(idx >= 0); tor_assert(node == smartlist_get(the_nodelist->nodes, idx)); smartlist_del(the_nodelist->nodes, idx); if (idx < smartlist_len(the_nodelist->nodes)) { tmp = smartlist_get(the_nodelist->nodes, idx); tmp->nodelist_idx = idx; } node->nodelist_idx = -1; } /** Return a newly allocated smartlist of the nodes that have <b>md</b> as * their microdescriptor. */ smartlist_t * nodelist_find_nodes_with_microdesc(const microdesc_t *md) { smartlist_t *result = smartlist_new(); if (the_nodelist == NULL) return result; SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { if (node->md == md) { smartlist_add(result, node); } } SMARTLIST_FOREACH_END(node); return result; } /** Release storage held by <b>node</b> */ static void node_free(node_t *node) { if (!node) return; if (node->md) node->md->held_by_nodes--; tor_assert(node->nodelist_idx == -1); tor_free(node); } /** Remove all entries from the nodelist that don't have enough info to be * usable for anything. */ void nodelist_purge(void) { node_t **iter; if (PREDICT_UNLIKELY(the_nodelist == NULL)) return; /* Remove the non-usable nodes. */ for (iter = HT_START(nodelist_map, &the_nodelist->nodes_by_id); iter; ) { node_t *node = *iter; if (node->md && !node->rs) { /* An md is only useful if there is an rs. */ node->md->held_by_nodes--; node->md = NULL; } if (node_is_usable(node)) { iter = HT_NEXT(nodelist_map, &the_nodelist->nodes_by_id, iter); } else { iter = HT_NEXT_RMV(nodelist_map, &the_nodelist->nodes_by_id, iter); nodelist_drop_node(node, 0); node_free(node); } } nodelist_assert_ok(); } /** Release all storage held by the nodelist. */ void nodelist_free_all(void) { if (PREDICT_UNLIKELY(the_nodelist == NULL)) return; HT_CLEAR(nodelist_map, &the_nodelist->nodes_by_id); SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { node->nodelist_idx = -1; node_free(node); } SMARTLIST_FOREACH_END(node); smartlist_free(the_nodelist->nodes); tor_free(the_nodelist); } /** Check that the nodelist is internally consistent, and consistent with * the directory info it's derived from. */ void nodelist_assert_ok(void) { routerlist_t *rl = router_get_routerlist(); networkstatus_t *ns = networkstatus_get_latest_consensus(); digestmap_t *dm; if (!the_nodelist) return; dm = digestmap_new(); /* every routerinfo in rl->routers should be in the nodelist. */ if (rl) { SMARTLIST_FOREACH_BEGIN(rl->routers, routerinfo_t *, ri) { const node_t *node = node_get_by_id(ri->cache_info.identity_digest); tor_assert(node && node->ri == ri); tor_assert(fast_memeq(ri->cache_info.identity_digest, node->identity, DIGEST_LEN)); tor_assert(! digestmap_get(dm, node->identity)); digestmap_set(dm, node->identity, (void*)node); } SMARTLIST_FOREACH_END(ri); } /* every routerstatus in ns should be in the nodelist */ if (ns) { SMARTLIST_FOREACH_BEGIN(ns->routerstatus_list, routerstatus_t *, rs) { const node_t *node = node_get_by_id(rs->identity_digest); tor_assert(node && node->rs == rs); tor_assert(fast_memeq(rs->identity_digest, node->identity, DIGEST_LEN)); digestmap_set(dm, node->identity, (void*)node); if (ns->flavor == FLAV_MICRODESC) { /* If it's a microdesc consensus, every entry that has a * microdescriptor should be in the nodelist. */ microdesc_t *md = microdesc_cache_lookup_by_digest256(NULL, rs->descriptor_digest); tor_assert(md == node->md); if (md) tor_assert(md->held_by_nodes >= 1); } } SMARTLIST_FOREACH_END(rs); } /* The nodelist should have no other entries, and its entries should be * well-formed. */ SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { tor_assert(digestmap_get(dm, node->identity) != NULL); tor_assert(node_sl_idx == node->nodelist_idx); } SMARTLIST_FOREACH_END(node); tor_assert((long)smartlist_len(the_nodelist->nodes) == (long)HT_SIZE(&the_nodelist->nodes_by_id)); digestmap_free(dm, NULL); } /** Return a list of a node_t * for every node we know about. The caller * MUST NOT modify the list. (You can set and clear flags in the nodes if * you must, but you must not add or remove nodes.) */ MOCK_IMPL(smartlist_t *, nodelist_get_list,(void)) { init_nodelist(); return the_nodelist->nodes; } /** Given a hex-encoded nickname of the format DIGEST, $DIGEST, $DIGEST=name, * or $DIGEST~name, return the node with the matching identity digest and * nickname (if any). Return NULL if no such node exists, or if <b>hex_id</b> * is not well-formed. */ const node_t * node_get_by_hex_id(const char *hex_id) { char digest_buf[DIGEST_LEN]; char nn_buf[MAX_NICKNAME_LEN+1]; char nn_char='\0'; if (hex_digest_nickname_decode(hex_id, digest_buf, &nn_char, nn_buf)==0) { const node_t *node = node_get_by_id(digest_buf); if (!node) return NULL; if (nn_char) { const char *real_name = node_get_nickname(node); if (!real_name || strcasecmp(real_name, nn_buf)) return NULL; if (nn_char == '=') { const char *named_id = networkstatus_get_router_digest_by_nickname(nn_buf); if (!named_id || tor_memneq(named_id, digest_buf, DIGEST_LEN)) return NULL; } } return node; } return NULL; } /** Given a nickname (possibly verbose, possibly a hexadecimal digest), return * the corresponding node_t, or NULL if none exists. Warn the user if * <b>warn_if_unnamed</b> is set, and they have specified a router by * nickname, but the Named flag isn't set for that router. */ MOCK_IMPL(const node_t *, node_get_by_nickname,(const char *nickname, int warn_if_unnamed)) { if (!the_nodelist) return NULL; /* Handle these cases: DIGEST, $DIGEST, $DIGEST=name, $DIGEST~name. */ { const node_t *node; if ((node = node_get_by_hex_id(nickname)) != NULL) return node; } if (!strcasecmp(nickname, UNNAMED_ROUTER_NICKNAME)) return NULL; /* Okay, so if we get here, the nickname is just a nickname. Is there * a binding for it in the consensus? */ { const char *named_id = networkstatus_get_router_digest_by_nickname(nickname); if (named_id) return node_get_by_id(named_id); } /* Is it marked as owned-by-someone-else? */ if (networkstatus_nickname_is_unnamed(nickname)) { log_info(LD_GENERAL, "The name %s is listed as Unnamed: there is some " "router that holds it, but not one listed in the current " "consensus.", escaped(nickname)); return NULL; } /* Okay, so the name is not canonical for anybody. */ { smartlist_t *matches = smartlist_new(); const node_t *choice = NULL; SMARTLIST_FOREACH_BEGIN(the_nodelist->nodes, node_t *, node) { if (!strcasecmp(node_get_nickname(node), nickname)) smartlist_add(matches, node); } SMARTLIST_FOREACH_END(node); if (smartlist_len(matches)>1 && warn_if_unnamed) { int any_unwarned = 0; SMARTLIST_FOREACH_BEGIN(matches, node_t *, node) { if (!node->name_lookup_warned) { node->name_lookup_warned = 1; any_unwarned = 1; } } SMARTLIST_FOREACH_END(node); if (any_unwarned) { log_warn(LD_CONFIG, "There are multiple matches for the name %s, " "but none is listed as Named in the directory consensus. " "Choosing one arbitrarily.", nickname); } } else if (smartlist_len(matches)==1 && warn_if_unnamed) { char fp[HEX_DIGEST_LEN+1]; node_t *node = smartlist_get(matches, 0); if (! node->name_lookup_warned) { base16_encode(fp, sizeof(fp), node->identity, DIGEST_LEN); log_warn(LD_CONFIG, "You specified a server \"%s\" by name, but the directory " "authorities do not have any key registered for this " "nickname -- so it could be used by any server, not just " "the one you meant. " "To make sure you get the same server in the future, refer " "to it by key, as \"$%s\".", nickname, fp); node->name_lookup_warned = 1; } } if (smartlist_len(matches)) choice = smartlist_get(matches, 0); smartlist_free(matches); return choice; } } /** Return the Ed25519 identity key for the provided node, or NULL if it * doesn't have one. */ const ed25519_public_key_t * node_get_ed25519_id(const node_t *node) { if (node->ri) { if (node->ri->cache_info.signing_key_cert) { const ed25519_public_key_t *pk = &node->ri->cache_info.signing_key_cert->signing_key; if (BUG(ed25519_public_key_is_zero(pk))) goto try_the_md; return pk; } } try_the_md: if (node->md) { if (node->md->ed25519_identity_pkey) { return node->md->ed25519_identity_pkey; } } return NULL; } /** Return true iff this node's Ed25519 identity matches <b>id</b>. * (An absent Ed25519 identity matches NULL or zero.) */ int node_ed25519_id_matches(const node_t *node, const ed25519_public_key_t *id) { const ed25519_public_key_t *node_id = node_get_ed25519_id(node); if (node_id == NULL || ed25519_public_key_is_zero(node_id)) { return id == NULL || ed25519_public_key_is_zero(id); } else { return id && ed25519_pubkey_eq(node_id, id); } } /** Return true iff <b>node</b> supports authenticating itself * by ed25519 ID during the link handshake in a way that we can understand * when we probe it. */ int node_supports_ed25519_link_authentication(const node_t *node) { /* XXXX Oh hm. What if some day in the future there are link handshake * versions that aren't 3 but which are ed25519 */ if (! node_get_ed25519_id(node)) return 0; if (node->ri) { const char *protos = node->ri->protocol_list; if (protos == NULL) return 0; return protocol_list_supports_protocol(protos, PRT_LINKAUTH, 3); } if (node->rs) { return node->rs->supports_ed25519_link_handshake; } tor_assert_nonfatal_unreached_once(); return 0; } /** Return the RSA ID key's SHA1 digest for the provided node. */ const uint8_t * node_get_rsa_id_digest(const node_t *node) { tor_assert(node); return (const uint8_t*)node->identity; } /** Return the nickname of <b>node</b>, or NULL if we can't find one. */ const char * node_get_nickname(const node_t *node) { tor_assert(node); if (node->rs) return node->rs->nickname; else if (node->ri) return node->ri->nickname; else return NULL; } /** Return true iff the nickname of <b>node</b> is canonical, based on the * latest consensus. */ int node_is_named(const node_t *node) { const char *named_id; const char *nickname = node_get_nickname(node); if (!nickname) return 0; named_id = networkstatus_get_router_digest_by_nickname(nickname); if (!named_id) return 0; return tor_memeq(named_id, node->identity, DIGEST_LEN); } /** Return true iff <b>node</b> appears to be a directory authority or * directory cache */ int node_is_dir(const node_t *node) { if (node->rs) { routerstatus_t * rs = node->rs; /* This is true if supports_tunnelled_dir_requests is true which * indicates that we support directory request tunnelled or through the * DirPort. */ return rs->is_v2_dir; } else if (node->ri) { routerinfo_t * ri = node->ri; /* Both tunnelled request is supported or DirPort is set. */ return ri->supports_tunnelled_dir_requests; } else { return 0; } } /** Return true iff <b>node</b> has either kind of usable descriptor -- that * is, a routerdescriptor or a microdescriptor. */ int node_has_descriptor(const node_t *node) { return (node->ri || (node->rs && node->md)); } /** Return the router_purpose of <b>node</b>. */ int node_get_purpose(const node_t *node) { if (node->ri) return node->ri->purpose; else return ROUTER_PURPOSE_GENERAL; } /** Compute the verbose ("extended") nickname of <b>node</b> and store it * into the MAX_VERBOSE_NICKNAME_LEN+1 character buffer at * <b>verbose_name_out</b> */ void node_get_verbose_nickname(const node_t *node, char *verbose_name_out) { const char *nickname = node_get_nickname(node); int is_named = node_is_named(node); verbose_name_out[0] = '$'; base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, node->identity, DIGEST_LEN); if (!nickname) return; verbose_name_out[1+HEX_DIGEST_LEN] = is_named ? '=' : '~'; strlcpy(verbose_name_out+1+HEX_DIGEST_LEN+1, nickname, MAX_NICKNAME_LEN+1); } /** Compute the verbose ("extended") nickname of node with * given <b>id_digest</b> and store it into the MAX_VERBOSE_NICKNAME_LEN+1 * character buffer at <b>verbose_name_out</b> * * If node_get_by_id() returns NULL, base 16 encoding of * <b>id_digest</b> is returned instead. */ void node_get_verbose_nickname_by_id(const char *id_digest, char *verbose_name_out) { const node_t *node = node_get_by_id(id_digest); if (!node) { verbose_name_out[0] = '$'; base16_encode(verbose_name_out+1, HEX_DIGEST_LEN+1, id_digest, DIGEST_LEN); } else { node_get_verbose_nickname(node, verbose_name_out); } } /** Return true iff it seems that <b>node</b> allows circuits to exit * through it directlry from the client. */ int node_allows_single_hop_exits(const node_t *node) { if (node && node->ri) return node->ri->allow_single_hop_exits; else return 0; } /** Return true iff it seems that <b>node</b> has an exit policy that doesn't * actually permit anything to exit, or we don't know its exit policy */ int node_exit_policy_rejects_all(const node_t *node) { if (node->rejects_all) return 1; if (node->ri) return node->ri->policy_is_reject_star; else if (node->md) return node->md->exit_policy == NULL || short_policy_is_reject_star(node->md->exit_policy); else return 1; } /** Return true iff the exit policy for <b>node</b> is such that we can treat * rejecting an address of type <b>family</b> unexpectedly as a sign of that * node's failure. */ int node_exit_policy_is_exact(const node_t *node, sa_family_t family) { if (family == AF_UNSPEC) { return 1; /* Rejecting an address but not telling us what address * is a bad sign. */ } else if (family == AF_INET) { return node->ri != NULL; } else if (family == AF_INET6) { return 0; } tor_fragile_assert(); return 1; } /* Check if the "addr" and port_field fields from r are a valid non-listening * address/port. If so, set valid to true and add a newly allocated * tor_addr_port_t containing "addr" and port_field to sl. * "addr" is an IPv4 host-order address and port_field is a uint16_t. * r is typically a routerinfo_t or routerstatus_t. */ #define SL_ADD_NEW_IPV4_AP(r, port_field, sl, valid) \ STMT_BEGIN \ if (tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \ valid = 1; \ tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \ tor_addr_from_ipv4h(&ap->addr, (r)->addr); \ ap->port = (r)->port_field; \ smartlist_add((sl), ap); \ } \ STMT_END /* Check if the "addr" and port_field fields from r are a valid non-listening * address/port. If so, set valid to true and add a newly allocated * tor_addr_port_t containing "addr" and port_field to sl. * "addr" is a tor_addr_t and port_field is a uint16_t. * r is typically a routerinfo_t or routerstatus_t. */ #define SL_ADD_NEW_IPV6_AP(r, port_field, sl, valid) \ STMT_BEGIN \ if (tor_addr_port_is_valid(&(r)->ipv6_addr, (r)->port_field, 0)) { \ valid = 1; \ tor_addr_port_t *ap = tor_malloc(sizeof(tor_addr_port_t)); \ tor_addr_copy(&ap->addr, &(r)->ipv6_addr); \ ap->port = (r)->port_field; \ smartlist_add((sl), ap); \ } \ STMT_END /** Return list of tor_addr_port_t with all OR ports (in the sense IP * addr + TCP port) for <b>node</b>. Caller must free all elements * using tor_free() and free the list using smartlist_free(). * * XXX this is potentially a memory fragmentation hog -- if on * critical path consider the option of having the caller allocate the * memory */ smartlist_t * node_get_all_orports(const node_t *node) { smartlist_t *sl = smartlist_new(); int valid = 0; /* Find a valid IPv4 address and port */ if (node->ri != NULL) { SL_ADD_NEW_IPV4_AP(node->ri, or_port, sl, valid); } /* If we didn't find a valid address/port in the ri, try the rs */ if (!valid && node->rs != NULL) { SL_ADD_NEW_IPV4_AP(node->rs, or_port, sl, valid); } /* Find a valid IPv6 address and port */ valid = 0; if (node->ri != NULL) { SL_ADD_NEW_IPV6_AP(node->ri, ipv6_orport, sl, valid); } if (!valid && node->rs != NULL) { SL_ADD_NEW_IPV6_AP(node->rs, ipv6_orport, sl, valid); } if (!valid && node->md != NULL) { SL_ADD_NEW_IPV6_AP(node->md, ipv6_orport, sl, valid); } return sl; } #undef SL_ADD_NEW_IPV4_AP #undef SL_ADD_NEW_IPV6_AP /** Wrapper around node_get_prim_orport for backward compatibility. */ void node_get_addr(const node_t *node, tor_addr_t *addr_out) { tor_addr_port_t ap; node_get_prim_orport(node, &ap); tor_addr_copy(addr_out, &ap.addr); } /** Return the host-order IPv4 address for <b>node</b>, or 0 if it doesn't * seem to have one. */ uint32_t node_get_prim_addr_ipv4h(const node_t *node) { /* Don't check the ORPort or DirPort, as this function isn't port-specific, * and the node might have a valid IPv4 address, yet have a zero * ORPort or DirPort. */ if (node->ri && tor_addr_is_valid_ipv4h(node->ri->addr, 0)) { return node->ri->addr; } else if (node->rs && tor_addr_is_valid_ipv4h(node->rs->addr, 0)) { return node->rs->addr; } return 0; } /** Copy a string representation of an IP address for <b>node</b> into * the <b>len</b>-byte buffer at <b>buf</b>. */ void node_get_address_string(const node_t *node, char *buf, size_t len) { uint32_t ipv4_addr = node_get_prim_addr_ipv4h(node); if (tor_addr_is_valid_ipv4h(ipv4_addr, 0)) { tor_addr_t addr; tor_addr_from_ipv4h(&addr, ipv4_addr); tor_addr_to_str(buf, &addr, len, 0); } else if (len > 0) { buf[0] = '\0'; } } /** Return <b>node</b>'s declared uptime, or -1 if it doesn't seem to have * one. */ long node_get_declared_uptime(const node_t *node) { if (node->ri) return node->ri->uptime; else return -1; } /** Return <b>node</b>'s platform string, or NULL if we don't know it. */ const char * node_get_platform(const node_t *node) { /* If we wanted, we could record the version in the routerstatus_t, since * the consensus lists it. We don't, though, so this function just won't * work with microdescriptors. */ if (node->ri) return node->ri->platform; else return NULL; } /** Return <b>node</b>'s time of publication, or 0 if we don't have one. */ time_t node_get_published_on(const node_t *node) { if (node->ri) return node->ri->cache_info.published_on; else return 0; } /** Return true iff <b>node</b> is one representing this router. */ int node_is_me(const node_t *node) { return router_digest_is_me(node->identity); } /** Return <b>node</b> declared family (as a list of names), or NULL if * the node didn't declare a family. */ const smartlist_t * node_get_declared_family(const node_t *node) { if (node->ri && node->ri->declared_family) return node->ri->declared_family; else if (node->md && node->md->family) return node->md->family; else return NULL; } /* Does this node have a valid IPv6 address? * Prefer node_has_ipv6_orport() or node_has_ipv6_dirport() for * checking specific ports. */ int node_has_ipv6_addr(const node_t *node) { /* Don't check the ORPort or DirPort, as this function isn't port-specific, * and the node might have a valid IPv6 address, yet have a zero * ORPort or DirPort. */ if (node->ri && tor_addr_is_valid(&node->ri->ipv6_addr, 0)) return 1; if (node->rs && tor_addr_is_valid(&node->rs->ipv6_addr, 0)) return 1; if (node->md && tor_addr_is_valid(&node->md->ipv6_addr, 0)) return 1; return 0; } /* Does this node have a valid IPv6 ORPort? */ int node_has_ipv6_orport(const node_t *node) { tor_addr_port_t ipv6_orport; node_get_pref_ipv6_orport(node, &ipv6_orport); return tor_addr_port_is_valid_ap(&ipv6_orport, 0); } /* Does this node have a valid IPv6 DirPort? */ int node_has_ipv6_dirport(const node_t *node) { tor_addr_port_t ipv6_dirport; node_get_pref_ipv6_dirport(node, &ipv6_dirport); return tor_addr_port_is_valid_ap(&ipv6_dirport, 0); } /** Return 1 if we prefer the IPv6 address and OR TCP port of * <b>node</b>, else 0. * * We prefer the IPv6 address if the router has an IPv6 address, * and we can use IPv6 addresses, and: * i) the node_t says that it prefers IPv6 * or * ii) the router has no IPv4 OR address. * * If you don't have a node, consider looking it up. * If there is no node, use fascist_firewall_prefer_ipv6_orport(). */ int node_ipv6_or_preferred(const node_t *node) { const or_options_t *options = get_options(); tor_addr_port_t ipv4_addr; node_assert_ok(node); /* XX/teor - node->ipv6_preferred is set from * fascist_firewall_prefer_ipv6_orport() each time the consensus is loaded. */ if (!fascist_firewall_use_ipv6(options)) { return 0; } else if (node->ipv6_preferred || node_get_prim_orport(node, &ipv4_addr)) { return node_has_ipv6_orport(node); } return 0; } #define RETURN_IPV4_AP(r, port_field, ap_out) \ STMT_BEGIN \ if (r && tor_addr_port_is_valid_ipv4h((r)->addr, (r)->port_field, 0)) { \ tor_addr_from_ipv4h(&(ap_out)->addr, (r)->addr); \ (ap_out)->port = (r)->port_field; \ return 0; \ } \ STMT_END /** Copy the primary (IPv4) OR port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. Return 0 if a valid address and * port was copied, else return non-zero.*/ int node_get_prim_orport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. */ RETURN_IPV4_AP(node->ri, or_port, ap_out); RETURN_IPV4_AP(node->rs, or_port, ap_out); /* Microdescriptors only have an IPv6 address */ return -1; } /** Copy the preferred OR port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_orport(const node_t *node, tor_addr_port_t *ap_out) { tor_assert(ap_out); if (node_ipv6_or_preferred(node)) { node_get_pref_ipv6_orport(node, ap_out); } else { /* the primary ORPort is always on IPv4 */ node_get_prim_orport(node, ap_out); } } /** Copy the preferred IPv6 OR port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_ipv6_orport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. * Prefer rs over md for consistency with the fascist_firewall_* functions. * Check if the address or port are valid, and try another alternative * if they are not. */ if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr, node->ri->ipv6_orport, 0)) { tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr); ap_out->port = node->ri->ipv6_orport; } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr, node->rs->ipv6_orport, 0)) { tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr); ap_out->port = node->rs->ipv6_orport; } else if (node->md && tor_addr_port_is_valid(&node->md->ipv6_addr, node->md->ipv6_orport, 0)) { tor_addr_copy(&ap_out->addr, &node->md->ipv6_addr); ap_out->port = node->md->ipv6_orport; } else { tor_addr_make_null(&ap_out->addr, AF_INET6); ap_out->port = 0; } } /** Return 1 if we prefer the IPv6 address and Dir TCP port of * <b>node</b>, else 0. * * We prefer the IPv6 address if the router has an IPv6 address, * and we can use IPv6 addresses, and: * i) the router has no IPv4 Dir address. * or * ii) our preference is for IPv6 Dir addresses. * * If there is no node, use fascist_firewall_prefer_ipv6_dirport(). */ int node_ipv6_dir_preferred(const node_t *node) { const or_options_t *options = get_options(); tor_addr_port_t ipv4_addr; node_assert_ok(node); /* node->ipv6_preferred is set from fascist_firewall_prefer_ipv6_orport(), * so we can't use it to determine DirPort IPv6 preference. * This means that bridge clients will use IPv4 DirPorts by default. */ if (!fascist_firewall_use_ipv6(options)) { return 0; } else if (node_get_prim_dirport(node, &ipv4_addr) || fascist_firewall_prefer_ipv6_dirport(get_options())) { return node_has_ipv6_dirport(node); } return 0; } /** Copy the primary (IPv4) Dir port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. Return 0 if a valid address and * port was copied, else return non-zero.*/ int node_get_prim_dirport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. */ RETURN_IPV4_AP(node->ri, dir_port, ap_out); RETURN_IPV4_AP(node->rs, dir_port, ap_out); /* Microdescriptors only have an IPv6 address */ return -1; } #undef RETURN_IPV4_AP /** Copy the preferred Dir port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_dirport(const node_t *node, tor_addr_port_t *ap_out) { tor_assert(ap_out); if (node_ipv6_dir_preferred(node)) { node_get_pref_ipv6_dirport(node, ap_out); } else { /* the primary DirPort is always on IPv4 */ node_get_prim_dirport(node, ap_out); } } /** Copy the preferred IPv6 Dir port (IP address and TCP port) for * <b>node</b> into *<b>ap_out</b>. */ void node_get_pref_ipv6_dirport(const node_t *node, tor_addr_port_t *ap_out) { node_assert_ok(node); tor_assert(ap_out); /* Check ri first, because rewrite_node_address_for_bridge() updates * node->ri with the configured bridge address. * Prefer rs over md for consistency with the fascist_firewall_* functions. * Check if the address or port are valid, and try another alternative * if they are not. */ /* Assume IPv4 and IPv6 dirports are the same */ if (node->ri && tor_addr_port_is_valid(&node->ri->ipv6_addr, node->ri->dir_port, 0)) { tor_addr_copy(&ap_out->addr, &node->ri->ipv6_addr); ap_out->port = node->ri->dir_port; } else if (node->rs && tor_addr_port_is_valid(&node->rs->ipv6_addr, node->rs->dir_port, 0)) { tor_addr_copy(&ap_out->addr, &node->rs->ipv6_addr); ap_out->port = node->rs->dir_port; } else { tor_addr_make_null(&ap_out->addr, AF_INET6); ap_out->port = 0; } } /** Return true iff <b>md</b> has a curve25519 onion key. * Use node_has_curve25519_onion_key() instead of calling this directly. */ static int microdesc_has_curve25519_onion_key(const microdesc_t *md) { if (!md) { return 0; } if (!md->onion_curve25519_pkey) { return 0; } if (tor_mem_is_zero((const char*)md->onion_curve25519_pkey->public_key, CURVE25519_PUBKEY_LEN)) { return 0; } return 1; } /** Return true iff <b>node</b> has a curve25519 onion key. */ int node_has_curve25519_onion_key(const node_t *node) { if (!node) return 0; if (node->ri) return routerinfo_has_curve25519_onion_key(node->ri); else if (node->md) return microdesc_has_curve25519_onion_key(node->md); else return 0; } /** Refresh the country code of <b>ri</b>. This function MUST be called on * each router when the GeoIP database is reloaded, and on all new routers. */ void node_set_country(node_t *node) { tor_addr_t addr = TOR_ADDR_NULL; /* XXXXipv6 */ if (node->rs) tor_addr_from_ipv4h(&addr, node->rs->addr); else if (node->ri) tor_addr_from_ipv4h(&addr, node->ri->addr); node->country = geoip_get_country_by_addr(&addr); } /** Set the country code of all routers in the routerlist. */ void nodelist_refresh_countries(void) { smartlist_t *nodes = nodelist_get_list(); SMARTLIST_FOREACH(nodes, node_t *, node, node_set_country(node)); } /** Return true iff router1 and router2 have similar enough network addresses * that we should treat them as being in the same family */ int addrs_in_same_network_family(const tor_addr_t *a1, const tor_addr_t *a2) { return 0 == tor_addr_compare_masked(a1, a2, 16, CMP_SEMANTIC); } /** Return true if <b>node</b>'s nickname matches <b>nickname</b> * (case-insensitive), or if <b>node's</b> identity key digest * matches a hexadecimal value stored in <b>nickname</b>. Return * false otherwise. */ static int node_nickname_matches(const node_t *node, const char *nickname) { const char *n = node_get_nickname(node); if (n && nickname[0]!='$' && !strcasecmp(n, nickname)) return 1; return hex_digest_nickname_matches(nickname, node->identity, n, node_is_named(node)); } /** Return true iff <b>node</b> is named by some nickname in <b>lst</b>. */ static inline int node_in_nickname_smartlist(const smartlist_t *lst, const node_t *node) { if (!lst) return 0; SMARTLIST_FOREACH(lst, const char *, name, { if (node_nickname_matches(node, name)) return 1; }); return 0; } /** Return true iff r1 and r2 are in the same family, but not the same * router. */ int nodes_in_same_family(const node_t *node1, const node_t *node2) { const or_options_t *options = get_options(); /* Are they in the same family because of their addresses? */ if (options->EnforceDistinctSubnets) { tor_addr_t a1, a2; node_get_addr(node1, &a1); node_get_addr(node2, &a2); if (addrs_in_same_network_family(&a1, &a2)) return 1; } /* Are they in the same family because the agree they are? */ { const smartlist_t *f1, *f2; f1 = node_get_declared_family(node1); f2 = node_get_declared_family(node2); if (f1 && f2 && node_in_nickname_smartlist(f1, node2) && node_in_nickname_smartlist(f2, node1)) return 1; } /* Are they in the same option because the user says they are? */ if (options->NodeFamilySets) { SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, { if (routerset_contains_node(rs, node1) && routerset_contains_node(rs, node2)) return 1; }); } return 0; } /** * Add all the family of <b>node</b>, including <b>node</b> itself, to * the smartlist <b>sl</b>. * * This is used to make sure we don't pick siblings in a single path, or * pick more than one relay from a family for our entry guard list. * Note that a node may be added to <b>sl</b> more than once if it is * part of <b>node</b>'s family for more than one reason. */ void nodelist_add_node_and_family(smartlist_t *sl, const node_t *node) { const smartlist_t *all_nodes = nodelist_get_list(); const smartlist_t *declared_family; const or_options_t *options = get_options(); tor_assert(node); declared_family = node_get_declared_family(node); /* Let's make sure that we have the node itself, if it's a real node. */ { const node_t *real_node = node_get_by_id(node->identity); if (real_node) smartlist_add(sl, (node_t*)real_node); } /* First, add any nodes with similar network addresses. */ if (options->EnforceDistinctSubnets) { tor_addr_t node_addr; node_get_addr(node, &node_addr); SMARTLIST_FOREACH_BEGIN(all_nodes, const node_t *, node2) { tor_addr_t a; node_get_addr(node2, &a); if (addrs_in_same_network_family(&a, &node_addr)) smartlist_add(sl, (void*)node2); } SMARTLIST_FOREACH_END(node2); } /* Now, add all nodes in the declared_family of this node, if they * also declare this node to be in their family. */ if (declared_family) { /* Add every r such that router declares familyness with node, and node * declares familyhood with router. */ SMARTLIST_FOREACH_BEGIN(declared_family, const char *, name) { const node_t *node2; const smartlist_t *family2; if (!(node2 = node_get_by_nickname(name, 0))) continue; if (!(family2 = node_get_declared_family(node2))) continue; SMARTLIST_FOREACH_BEGIN(family2, const char *, name2) { if (node_nickname_matches(node, name2)) { smartlist_add(sl, (void*)node2); break; } } SMARTLIST_FOREACH_END(name2); } SMARTLIST_FOREACH_END(name); } /* If the user declared any families locally, honor those too. */ if (options->NodeFamilySets) { SMARTLIST_FOREACH(options->NodeFamilySets, const routerset_t *, rs, { if (routerset_contains_node(rs, node)) { routerset_get_all_nodes(sl, rs, NULL, 0); } }); } } /** Find a router that's up, that has this IP address, and * that allows exit to this address:port, or return NULL if there * isn't a good one. * Don't exit enclave to excluded relays -- it wouldn't actually * hurt anything, but this way there are fewer confused users. */ const node_t * router_find_exact_exit_enclave(const char *address, uint16_t port) {/*XXXX MOVE*/ uint32_t addr; struct in_addr in; tor_addr_t a; const or_options_t *options = get_options(); if (!tor_inet_aton(address, &in)) return NULL; /* it's not an IP already */ addr = ntohl(in.s_addr); tor_addr_from_ipv4h(&a, addr); SMARTLIST_FOREACH(nodelist_get_list(), const node_t *, node, { if (node_get_addr_ipv4h(node) == addr && node->is_running && compare_tor_addr_to_node_policy(&a, port, node) == ADDR_POLICY_ACCEPTED && !routerset_contains_node(options->ExcludeExitNodesUnion_, node)) return node; }); return NULL; } /** Return 1 if <b>router</b> is not suitable for these parameters, else 0. * If <b>need_uptime</b> is non-zero, we require a minimum uptime. * If <b>need_capacity</b> is non-zero, we require a minimum advertised * bandwidth. * If <b>need_guard</b>, we require that the router is a possible entry guard. */ int node_is_unreliable(const node_t *node, int need_uptime, int need_capacity, int need_guard) { if (need_uptime && !node->is_stable) return 1; if (need_capacity && !node->is_fast) return 1; if (need_guard && !node->is_possible_guard) return 1; return 0; } /** Return 1 if all running sufficiently-stable routers we can use will reject * addr:port. Return 0 if any might accept it. */ int router_exit_policy_all_nodes_reject(const tor_addr_t *addr, uint16_t port, int need_uptime) { addr_policy_result_t r; SMARTLIST_FOREACH_BEGIN(nodelist_get_list(), const node_t *, node) { if (node->is_running && !node_is_unreliable(node, need_uptime, 0, 0)) { r = compare_tor_addr_to_node_policy(addr, port, node); if (r != ADDR_POLICY_REJECTED && r != ADDR_POLICY_PROBABLY_REJECTED) return 0; /* this one could be ok. good enough. */ } } SMARTLIST_FOREACH_END(node); return 1; /* all will reject. */ } /** Mark the router with ID <b>digest</b> as running or non-running * in our routerlist. */ void router_set_status(const char *digest, int up) { node_t *node; tor_assert(digest); SMARTLIST_FOREACH(router_get_fallback_dir_servers(), dir_server_t *, d, if (tor_memeq(d->digest, digest, DIGEST_LEN)) d->is_running = up); SMARTLIST_FOREACH(router_get_trusted_dir_servers(), dir_server_t *, d, if (tor_memeq(d->digest, digest, DIGEST_LEN)) d->is_running = up); node = node_get_mutable_by_id(digest); if (node) { #if 0 log_debug(LD_DIR,"Marking router %s as %s.", node_describe(node), up ? "up" : "down"); #endif if (!up && node_is_me(node) && !net_is_disabled()) log_warn(LD_NET, "We just marked ourself as down. Are your external " "addresses reachable?"); if (bool_neq(node->is_running, up)) router_dir_info_changed(); node->is_running = up; } } /** True iff, the last time we checked whether we had enough directory info * to build circuits, the answer was "yes". If there are no exits in the * consensus, we act as if we have 100% of the exit directory info. */ static int have_min_dir_info = 0; /** Does the consensus contain nodes that can exit? */ static consensus_path_type_t have_consensus_path = CONSENSUS_PATH_UNKNOWN; /** True iff enough has changed since the last time we checked whether we had * enough directory info to build circuits that our old answer can no longer * be trusted. */ static int need_to_update_have_min_dir_info = 1; /** String describing what we're missing before we have enough directory * info. */ static char dir_info_status[512] = ""; /** Return true iff we have enough consensus information to * start building circuits. Right now, this means "a consensus that's * less than a day old, and at least 60% of router descriptors (configurable), * weighted by bandwidth. Treat the exit fraction as 100% if there are * no exits in the consensus." * To obtain the final weighted bandwidth, we multiply the * weighted bandwidth fraction for each position (guard, middle, exit). */ int router_have_minimum_dir_info(void) { static int logged_delay=0; const char *delay_fetches_msg = NULL; if (should_delay_dir_fetches(get_options(), &delay_fetches_msg)) { if (!logged_delay) log_notice(LD_DIR, "Delaying directory fetches: %s", delay_fetches_msg); logged_delay=1; strlcpy(dir_info_status, delay_fetches_msg, sizeof(dir_info_status)); return 0; } logged_delay = 0; /* reset it if we get this far */ if (PREDICT_UNLIKELY(need_to_update_have_min_dir_info)) { update_router_have_minimum_dir_info(); } return have_min_dir_info; } /** Set to CONSENSUS_PATH_EXIT if there is at least one exit node * in the consensus. We update this flag in compute_frac_paths_available if * there is at least one relay that has an Exit flag in the consensus. * Used to avoid building exit circuits when they will almost certainly fail. * Set to CONSENSUS_PATH_INTERNAL if there are no exits in the consensus. * (This situation typically occurs during bootstrap of a test network.) * Set to CONSENSUS_PATH_UNKNOWN if we have never checked, or have * reason to believe our last known value was invalid or has expired. * If we're in a network with TestingDirAuthVoteExit set, * this can cause router_have_consensus_path() to be set to * CONSENSUS_PATH_EXIT, even if there are no nodes with accept exit policies. */ MOCK_IMPL(consensus_path_type_t, router_have_consensus_path, (void)) { return have_consensus_path; } /** Called when our internal view of the directory has changed. This can be * when the authorities change, networkstatuses change, the list of routerdescs * changes, or number of running routers changes. */ void router_dir_info_changed(void) { need_to_update_have_min_dir_info = 1; rend_hsdir_routers_changed(); } /** Return a string describing what we're missing before we have enough * directory info. */ const char * get_dir_info_status_string(void) { return dir_info_status; } /** Iterate over the servers listed in <b>consensus</b>, and count how many of * them seem like ones we'd use (store this in *<b>num_usable</b>), and how * many of <em>those</em> we have descriptors for (store this in * *<b>num_present</b>). * * If <b>in_set</b> is non-NULL, only consider those routers in <b>in_set</b>. * If <b>exit_only</b> is USABLE_DESCRIPTOR_EXIT_ONLY, only consider nodes * with the Exit flag. * If *<b>descs_out</b> is present, add a node_t for each usable descriptor * to it. */ static void count_usable_descriptors(int *num_present, int *num_usable, smartlist_t *descs_out, const networkstatus_t *consensus, const or_options_t *options, time_t now, routerset_t *in_set, usable_descriptor_t exit_only) { const int md = (consensus->flavor == FLAV_MICRODESC); *num_present = 0, *num_usable = 0; SMARTLIST_FOREACH_BEGIN(consensus->routerstatus_list, routerstatus_t *, rs) { const node_t *node = node_get_by_id(rs->identity_digest); if (!node) continue; /* This would be a bug: every entry in the consensus is * supposed to have a node. */ if (exit_only == USABLE_DESCRIPTOR_EXIT_ONLY && ! rs->is_exit) continue; if (in_set && ! routerset_contains_routerstatus(in_set, rs, -1)) continue; if (client_would_use_router(rs, now, options)) { const char * const digest = rs->descriptor_digest; int present; ++*num_usable; /* the consensus says we want it. */ if (md) present = NULL != microdesc_cache_lookup_by_digest256(NULL, digest); else present = NULL != router_get_by_descriptor_digest(digest); if (present) { /* we have the descriptor listed in the consensus. */ ++*num_present; } if (descs_out) smartlist_add(descs_out, (node_t*)node); } } SMARTLIST_FOREACH_END(rs); log_debug(LD_DIR, "%d usable, %d present (%s%s).", *num_usable, *num_present, md ? "microdesc" : "desc", exit_only == USABLE_DESCRIPTOR_EXIT_ONLY ? " exits" : "s"); } /** Return an estimate of which fraction of usable paths through the Tor * network we have available for use. Count how many routers seem like ones * we'd use (store this in *<b>num_usable_out</b>), and how many of * <em>those</em> we have descriptors for (store this in * *<b>num_present_out</b>.) * * If **<b>status_out</b> is present, allocate a new string and print the * available percentages of guard, middle, and exit nodes to it, noting * whether there are exits in the consensus. * If there are no exits in the consensus, we treat the exit fraction as 100%, * but set router_have_consensus_path() so that we can only build internal * paths. */ static double compute_frac_paths_available(const networkstatus_t *consensus, const or_options_t *options, time_t now, int *num_present_out, int *num_usable_out, char **status_out) { smartlist_t *guards = smartlist_new(); smartlist_t *mid = smartlist_new(); smartlist_t *exits = smartlist_new(); double f_guard, f_mid, f_exit; double f_path = 0.0; /* Used to determine whether there are any exits in the consensus */ int np = 0; /* Used to determine whether there are any exits with descriptors */ int nu = 0; const int authdir = authdir_mode_v3(options); count_usable_descriptors(num_present_out, num_usable_out, mid, consensus, options, now, NULL, USABLE_DESCRIPTOR_ALL); if (options->EntryNodes) { count_usable_descriptors(&np, &nu, guards, consensus, options, now, options->EntryNodes, USABLE_DESCRIPTOR_ALL); } else { SMARTLIST_FOREACH(mid, const node_t *, node, { if (authdir) { if (node->rs && node->rs->is_possible_guard) smartlist_add(guards, (node_t*)node); } else { if (node->is_possible_guard) smartlist_add(guards, (node_t*)node); } }); } /* All nodes with exit flag * If we're in a network with TestingDirAuthVoteExit set, * this can cause false positives on have_consensus_path, * incorrectly setting it to CONSENSUS_PATH_EXIT. This is * an unavoidable feature of forcing authorities to declare * certain nodes as exits. */ count_usable_descriptors(&np, &nu, exits, consensus, options, now, NULL, USABLE_DESCRIPTOR_EXIT_ONLY); log_debug(LD_NET, "%s: %d present, %d usable", "exits", np, nu); /* We need at least 1 exit present in the consensus to consider * building exit paths */ /* Update our understanding of whether the consensus has exits */ consensus_path_type_t old_have_consensus_path = have_consensus_path; have_consensus_path = ((nu > 0) ? CONSENSUS_PATH_EXIT : CONSENSUS_PATH_INTERNAL); if (have_consensus_path == CONSENSUS_PATH_INTERNAL && old_have_consensus_path != have_consensus_path) { log_notice(LD_NET, "The current consensus has no exit nodes. " "Tor can only build internal paths, " "such as paths to hidden services."); /* However, exit nodes can reachability self-test using this consensus, * join the network, and appear in a later consensus. This will allow * the network to build exit paths, such as paths for world wide web * browsing (as distinct from hidden service web browsing). */ } f_guard = frac_nodes_with_descriptors(guards, WEIGHT_FOR_GUARD); f_mid = frac_nodes_with_descriptors(mid, WEIGHT_FOR_MID); f_exit = frac_nodes_with_descriptors(exits, WEIGHT_FOR_EXIT); log_debug(LD_NET, "f_guard: %.2f, f_mid: %.2f, f_exit: %.2f", f_guard, f_mid, f_exit); smartlist_free(guards); smartlist_free(mid); smartlist_free(exits); if (options->ExitNodes) { double f_myexit, f_myexit_unflagged; smartlist_t *myexits= smartlist_new(); smartlist_t *myexits_unflagged = smartlist_new(); /* All nodes with exit flag in ExitNodes option */ count_usable_descriptors(&np, &nu, myexits, consensus, options, now, options->ExitNodes, USABLE_DESCRIPTOR_EXIT_ONLY); log_debug(LD_NET, "%s: %d present, %d usable", "myexits", np, nu); /* Now compute the nodes in the ExitNodes option where which we don't know * what their exit policy is, or we know it permits something. */ count_usable_descriptors(&np, &nu, myexits_unflagged, consensus, options, now, options->ExitNodes, USABLE_DESCRIPTOR_ALL); log_debug(LD_NET, "%s: %d present, %d usable", "myexits_unflagged (initial)", np, nu); SMARTLIST_FOREACH_BEGIN(myexits_unflagged, const node_t *, node) { if (node_has_descriptor(node) && node_exit_policy_rejects_all(node)) { SMARTLIST_DEL_CURRENT(myexits_unflagged, node); /* this node is not actually an exit */ np--; /* this node is unusable as an exit */ nu--; } } SMARTLIST_FOREACH_END(node); log_debug(LD_NET, "%s: %d present, %d usable", "myexits_unflagged (final)", np, nu); f_myexit= frac_nodes_with_descriptors(myexits,WEIGHT_FOR_EXIT); f_myexit_unflagged= frac_nodes_with_descriptors(myexits_unflagged,WEIGHT_FOR_EXIT); log_debug(LD_NET, "f_exit: %.2f, f_myexit: %.2f, f_myexit_unflagged: %.2f", f_exit, f_myexit, f_myexit_unflagged); /* If our ExitNodes list has eliminated every possible Exit node, and there * were some possible Exit nodes, then instead consider nodes that permit * exiting to some ports. */ if (smartlist_len(myexits) == 0 && smartlist_len(myexits_unflagged)) { f_myexit = f_myexit_unflagged; } smartlist_free(myexits); smartlist_free(myexits_unflagged); /* This is a tricky point here: we don't want to make it easy for a * directory to trickle exits to us until it learns which exits we have * configured, so require that we have a threshold both of total exits * and usable exits. */ if (f_myexit < f_exit) f_exit = f_myexit; } /* if the consensus has no exits, treat the exit fraction as 100% */ if (router_have_consensus_path() != CONSENSUS_PATH_EXIT) { f_exit = 1.0; } f_path = f_guard * f_mid * f_exit; if (status_out) tor_asprintf(status_out, "%d%% of guards bw, " "%d%% of midpoint bw, and " "%d%% of exit bw%s = " "%d%% of path bw", (int)(f_guard*100), (int)(f_mid*100), (int)(f_exit*100), (router_have_consensus_path() == CONSENSUS_PATH_EXIT ? "" : " (no exits in consensus)"), (int)(f_path*100)); return f_path; } /** We just fetched a new set of descriptors. Compute how far through * the "loading descriptors" bootstrapping phase we are, so we can inform * the controller of our progress. */ int count_loading_descriptors_progress(void) { int num_present = 0, num_usable=0; time_t now = time(NULL); const or_options_t *options = get_options(); const networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor()); double paths, fraction; if (!consensus) return 0; /* can't count descriptors if we have no list of them */ paths = compute_frac_paths_available(consensus, options, now, &num_present, &num_usable, NULL); fraction = paths / get_frac_paths_needed_for_circs(options,consensus); if (fraction > 1.0) return 0; /* it's not the number of descriptors holding us back */ return BOOTSTRAP_STATUS_LOADING_DESCRIPTORS + (int) (fraction*(BOOTSTRAP_STATUS_CONN_OR-1 - BOOTSTRAP_STATUS_LOADING_DESCRIPTORS)); } /** Return the fraction of paths needed before we're willing to build * circuits, as configured in <b>options</b>, or in the consensus <b>ns</b>. */ static double get_frac_paths_needed_for_circs(const or_options_t *options, const networkstatus_t *ns) { #define DFLT_PCT_USABLE_NEEDED 60 if (options->PathsNeededToBuildCircuits >= 0.0) { return options->PathsNeededToBuildCircuits; } else { return networkstatus_get_param(ns, "min_paths_for_circs_pct", DFLT_PCT_USABLE_NEEDED, 25, 95)/100.0; } } /** Change the value of have_min_dir_info, setting it true iff we have enough * network and router information to build circuits. Clear the value of * need_to_update_have_min_dir_info. */ static void update_router_have_minimum_dir_info(void) { time_t now = time(NULL); int res; const or_options_t *options = get_options(); const networkstatus_t *consensus = networkstatus_get_reasonably_live_consensus(now,usable_consensus_flavor()); int using_md; if (!consensus) { if (!networkstatus_get_latest_consensus()) strlcpy(dir_info_status, "We have no usable consensus.", sizeof(dir_info_status)); else strlcpy(dir_info_status, "We have no recent usable consensus.", sizeof(dir_info_status)); res = 0; goto done; } using_md = consensus->flavor == FLAV_MICRODESC; if (! entry_guards_have_enough_dir_info_to_build_circuits()) { strlcpy(dir_info_status, "We're missing descriptors for some of our " "primary entry guards", sizeof(dir_info_status)); res = 0; goto done; } /* Check fraction of available paths */ { char *status = NULL; int num_present=0, num_usable=0; double paths = compute_frac_paths_available(consensus, options, now, &num_present, &num_usable, &status); if (paths < get_frac_paths_needed_for_circs(options,consensus)) { tor_snprintf(dir_info_status, sizeof(dir_info_status), "We need more %sdescriptors: we have %d/%d, and " "can only build %d%% of likely paths. (We have %s.)", using_md?"micro":"", num_present, num_usable, (int)(paths*100), status); tor_free(status); res = 0; control_event_bootstrap(BOOTSTRAP_STATUS_REQUESTING_DESCRIPTORS, 0); goto done; } tor_free(status); res = 1; } done: /* If paths have just become available in this update. */ if (res && !have_min_dir_info) { control_event_client_status(LOG_NOTICE, "ENOUGH_DIR_INFO"); if (control_event_bootstrap(BOOTSTRAP_STATUS_CONN_OR, 0) == 0) { log_notice(LD_DIR, "We now have enough directory information to build circuits."); } } /* If paths have just become unavailable in this update. */ if (!res && have_min_dir_info) { int quiet = directory_too_idle_to_fetch_descriptors(options, now); tor_log(quiet ? LOG_INFO : LOG_NOTICE, LD_DIR, "Our directory information is no longer up-to-date " "enough to build circuits: %s", dir_info_status); /* a) make us log when we next complete a circuit, so we know when Tor * is back up and usable, and b) disable some activities that Tor * should only do while circuits are working, like reachability tests * and fetching bridge descriptors only over circuits. */ note_that_we_maybe_cant_complete_circuits(); have_consensus_path = CONSENSUS_PATH_UNKNOWN; control_event_client_status(LOG_NOTICE, "NOT_ENOUGH_DIR_INFO"); } have_min_dir_info = res; need_to_update_have_min_dir_info = 0; }
./CrossVul/dataset_final_sorted/CWE-200/c/good_2490_3
crossvul-cpp_data_good_506_0
/* * ipddp.c: IP to Appletalk-IP Encapsulation driver for Linux * Appletalk-IP to IP Decapsulation driver for Linux * * Authors: * - DDP-IP Encap by: Bradford W. Johnson <johns393@maroon.tc.umn.edu> * - DDP-IP Decap by: Jay Schulist <jschlst@samba.org> * * Derived from: * - Almost all code already existed in net/appletalk/ddp.c I just * moved/reorginized it into a driver file. Original IP-over-DDP code * was done by Bradford W. Johnson <johns393@maroon.tc.umn.edu> * - skeleton.c: A network driver outline for linux. * Written 1993-94 by Donald Becker. * - dummy.c: A dummy net driver. By Nick Holloway. * - MacGate: A user space Daemon for Appletalk-IP Decap for * Linux by Jay Schulist <jschlst@samba.org> * * Copyright 1993 United States Government as represented by the * Director, National Security Agency. * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/netdevice.h> #include <linux/etherdevice.h> #include <linux/ip.h> #include <linux/atalk.h> #include <linux/if_arp.h> #include <linux/slab.h> #include <net/route.h> #include <linux/uaccess.h> #include "ipddp.h" /* Our stuff */ static const char version[] = KERN_INFO "ipddp.c:v0.01 8/28/97 Bradford W. Johnson <johns393@maroon.tc.umn.edu>\n"; static struct ipddp_route *ipddp_route_list; static DEFINE_SPINLOCK(ipddp_route_lock); #ifdef CONFIG_IPDDP_ENCAP static int ipddp_mode = IPDDP_ENCAP; #else static int ipddp_mode = IPDDP_DECAP; #endif /* Index to functions, as function prototypes. */ static netdev_tx_t ipddp_xmit(struct sk_buff *skb, struct net_device *dev); static int ipddp_create(struct ipddp_route *new_rt); static int ipddp_delete(struct ipddp_route *rt); static struct ipddp_route* __ipddp_find_route(struct ipddp_route *rt); static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd); static const struct net_device_ops ipddp_netdev_ops = { .ndo_start_xmit = ipddp_xmit, .ndo_do_ioctl = ipddp_ioctl, .ndo_set_mac_address = eth_mac_addr, .ndo_validate_addr = eth_validate_addr, }; static struct net_device * __init ipddp_init(void) { static unsigned version_printed; struct net_device *dev; int err; dev = alloc_etherdev(0); if (!dev) return ERR_PTR(-ENOMEM); netif_keep_dst(dev); strcpy(dev->name, "ipddp%d"); if (version_printed++ == 0) printk(version); /* Initialize the device structure. */ dev->netdev_ops = &ipddp_netdev_ops; dev->type = ARPHRD_IPDDP; /* IP over DDP tunnel */ dev->mtu = 585; dev->flags |= IFF_NOARP; /* * The worst case header we will need is currently a * ethernet header (14 bytes) and a ddp header (sizeof ddpehdr+1) * We send over SNAP so that takes another 8 bytes. */ dev->hard_header_len = 14+8+sizeof(struct ddpehdr)+1; err = register_netdev(dev); if (err) { free_netdev(dev); return ERR_PTR(err); } /* Let the user now what mode we are in */ if(ipddp_mode == IPDDP_ENCAP) printk("%s: Appletalk-IP Encap. mode by Bradford W. Johnson <johns393@maroon.tc.umn.edu>\n", dev->name); if(ipddp_mode == IPDDP_DECAP) printk("%s: Appletalk-IP Decap. mode by Jay Schulist <jschlst@samba.org>\n", dev->name); return dev; } /* * Transmit LLAP/ELAP frame using aarp_send_ddp. */ static netdev_tx_t ipddp_xmit(struct sk_buff *skb, struct net_device *dev) { __be32 paddr = skb_rtable(skb)->rt_gateway; struct ddpehdr *ddp; struct ipddp_route *rt; struct atalk_addr *our_addr; spin_lock(&ipddp_route_lock); /* * Find appropriate route to use, based only on IP number. */ for(rt = ipddp_route_list; rt != NULL; rt = rt->next) { if(rt->ip == paddr) break; } if(rt == NULL) { spin_unlock(&ipddp_route_lock); return NETDEV_TX_OK; } our_addr = atalk_find_dev_addr(rt->dev); if(ipddp_mode == IPDDP_DECAP) /* * Pull off the excess room that should not be there. * This is due to a hard-header problem. This is the * quick fix for now though, till it breaks. */ skb_pull(skb, 35-(sizeof(struct ddpehdr)+1)); /* Create the Extended DDP header */ ddp = (struct ddpehdr *)skb->data; ddp->deh_len_hops = htons(skb->len + (1<<10)); ddp->deh_sum = 0; /* * For Localtalk we need aarp_send_ddp to strip the * long DDP header and place a shot DDP header on it. */ if(rt->dev->type == ARPHRD_LOCALTLK) { ddp->deh_dnet = 0; /* FIXME more hops?? */ ddp->deh_snet = 0; } else { ddp->deh_dnet = rt->at.s_net; /* FIXME more hops?? */ ddp->deh_snet = our_addr->s_net; } ddp->deh_dnode = rt->at.s_node; ddp->deh_snode = our_addr->s_node; ddp->deh_dport = 72; ddp->deh_sport = 72; *((__u8 *)(ddp+1)) = 22; /* ddp type = IP */ skb->protocol = htons(ETH_P_ATALK); /* Protocol has changed */ dev->stats.tx_packets++; dev->stats.tx_bytes += skb->len; aarp_send_ddp(rt->dev, skb, &rt->at, NULL); spin_unlock(&ipddp_route_lock); return NETDEV_TX_OK; } /* * Create a routing entry. We first verify that the * record does not already exist. If it does we return -EEXIST */ static int ipddp_create(struct ipddp_route *new_rt) { struct ipddp_route *rt = kzalloc(sizeof(*rt), GFP_KERNEL); if (rt == NULL) return -ENOMEM; rt->ip = new_rt->ip; rt->at = new_rt->at; rt->next = NULL; if ((rt->dev = atrtr_get_dev(&rt->at)) == NULL) { kfree(rt); return -ENETUNREACH; } spin_lock_bh(&ipddp_route_lock); if (__ipddp_find_route(rt)) { spin_unlock_bh(&ipddp_route_lock); kfree(rt); return -EEXIST; } rt->next = ipddp_route_list; ipddp_route_list = rt; spin_unlock_bh(&ipddp_route_lock); return 0; } /* * Delete a route, we only delete a FULL match. * If route does not exist we return -ENOENT. */ static int ipddp_delete(struct ipddp_route *rt) { struct ipddp_route **r = &ipddp_route_list; struct ipddp_route *tmp; spin_lock_bh(&ipddp_route_lock); while((tmp = *r) != NULL) { if(tmp->ip == rt->ip && tmp->at.s_net == rt->at.s_net && tmp->at.s_node == rt->at.s_node) { *r = tmp->next; spin_unlock_bh(&ipddp_route_lock); kfree(tmp); return 0; } r = &tmp->next; } spin_unlock_bh(&ipddp_route_lock); return -ENOENT; } /* * Find a routing entry, we only return a FULL match */ static struct ipddp_route* __ipddp_find_route(struct ipddp_route *rt) { struct ipddp_route *f; for(f = ipddp_route_list; f != NULL; f = f->next) { if(f->ip == rt->ip && f->at.s_net == rt->at.s_net && f->at.s_node == rt->at.s_node) return f; } return NULL; } static int ipddp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd) { struct ipddp_route __user *rt = ifr->ifr_data; struct ipddp_route rcp, rcp2, *rp; if(!capable(CAP_NET_ADMIN)) return -EPERM; if(copy_from_user(&rcp, rt, sizeof(rcp))) return -EFAULT; switch(cmd) { case SIOCADDIPDDPRT: return ipddp_create(&rcp); case SIOCFINDIPDDPRT: spin_lock_bh(&ipddp_route_lock); rp = __ipddp_find_route(&rcp); if (rp) { memset(&rcp2, 0, sizeof(rcp2)); rcp2.ip = rp->ip; rcp2.at = rp->at; rcp2.flags = rp->flags; } spin_unlock_bh(&ipddp_route_lock); if (rp) { if (copy_to_user(rt, &rcp2, sizeof(struct ipddp_route))) return -EFAULT; return 0; } else return -ENOENT; case SIOCDELIPDDPRT: return ipddp_delete(&rcp); default: return -EINVAL; } } static struct net_device *dev_ipddp; MODULE_LICENSE("GPL"); module_param(ipddp_mode, int, 0); static int __init ipddp_init_module(void) { dev_ipddp = ipddp_init(); return PTR_ERR_OR_ZERO(dev_ipddp); } static void __exit ipddp_cleanup_module(void) { struct ipddp_route *p; unregister_netdev(dev_ipddp); free_netdev(dev_ipddp); while (ipddp_route_list) { p = ipddp_route_list->next; kfree(ipddp_route_list); ipddp_route_list = p; } } module_init(ipddp_init_module); module_exit(ipddp_cleanup_module);
./CrossVul/dataset_final_sorted/CWE-200/c/good_506_0
crossvul-cpp_data_bad_2864_1
/* * FPU signal frame handling routines. */ #include <linux/compat.h> #include <linux/cpu.h> #include <asm/fpu/internal.h> #include <asm/fpu/signal.h> #include <asm/fpu/regset.h> #include <asm/fpu/xstate.h> #include <asm/sigframe.h> #include <asm/trace/fpu.h> static struct _fpx_sw_bytes fx_sw_reserved, fx_sw_reserved_ia32; /* * Check for the presence of extended state information in the * user fpstate pointer in the sigcontext. */ static inline int check_for_xstate(struct fxregs_state __user *buf, void __user *fpstate, struct _fpx_sw_bytes *fx_sw) { int min_xstate_size = sizeof(struct fxregs_state) + sizeof(struct xstate_header); unsigned int magic2; if (__copy_from_user(fx_sw, &buf->sw_reserved[0], sizeof(*fx_sw))) return -1; /* Check for the first magic field and other error scenarios. */ if (fx_sw->magic1 != FP_XSTATE_MAGIC1 || fx_sw->xstate_size < min_xstate_size || fx_sw->xstate_size > fpu_user_xstate_size || fx_sw->xstate_size > fx_sw->extended_size) return -1; /* * Check for the presence of second magic word at the end of memory * layout. This detects the case where the user just copied the legacy * fpstate layout with out copying the extended state information * in the memory layout. */ if (__get_user(magic2, (__u32 __user *)(fpstate + fx_sw->xstate_size)) || magic2 != FP_XSTATE_MAGIC2) return -1; return 0; } /* * Signal frame handlers. */ static inline int save_fsave_header(struct task_struct *tsk, void __user *buf) { if (use_fxsr()) { struct xregs_state *xsave = &tsk->thread.fpu.state.xsave; struct user_i387_ia32_struct env; struct _fpstate_32 __user *fp = buf; convert_from_fxsr(&env, tsk); if (__copy_to_user(buf, &env, sizeof(env)) || __put_user(xsave->i387.swd, &fp->status) || __put_user(X86_FXSR_MAGIC, &fp->magic)) return -1; } else { struct fregs_state __user *fp = buf; u32 swd; if (__get_user(swd, &fp->swd) || __put_user(swd, &fp->status)) return -1; } return 0; } static inline int save_xstate_epilog(void __user *buf, int ia32_frame) { struct xregs_state __user *x = buf; struct _fpx_sw_bytes *sw_bytes; u32 xfeatures; int err; /* Setup the bytes not touched by the [f]xsave and reserved for SW. */ sw_bytes = ia32_frame ? &fx_sw_reserved_ia32 : &fx_sw_reserved; err = __copy_to_user(&x->i387.sw_reserved, sw_bytes, sizeof(*sw_bytes)); if (!use_xsave()) return err; err |= __put_user(FP_XSTATE_MAGIC2, (__u32 *)(buf + fpu_user_xstate_size)); /* * Read the xfeatures which we copied (directly from the cpu or * from the state in task struct) to the user buffers. */ err |= __get_user(xfeatures, (__u32 *)&x->header.xfeatures); /* * For legacy compatible, we always set FP/SSE bits in the bit * vector while saving the state to the user context. This will * enable us capturing any changes(during sigreturn) to * the FP/SSE bits by the legacy applications which don't touch * xfeatures in the xsave header. * * xsave aware apps can change the xfeatures in the xsave * header as well as change any contents in the memory layout. * xrestore as part of sigreturn will capture all the changes. */ xfeatures |= XFEATURE_MASK_FPSSE; err |= __put_user(xfeatures, (__u32 *)&x->header.xfeatures); return err; } static inline int copy_fpregs_to_sigframe(struct xregs_state __user *buf) { int err; if (use_xsave()) err = copy_xregs_to_user(buf); else if (use_fxsr()) err = copy_fxregs_to_user((struct fxregs_state __user *) buf); else err = copy_fregs_to_user((struct fregs_state __user *) buf); if (unlikely(err) && __clear_user(buf, fpu_user_xstate_size)) err = -EFAULT; return err; } /* * Save the fpu, extended register state to the user signal frame. * * 'buf_fx' is the 64-byte aligned pointer at which the [f|fx|x]save * state is copied. * 'buf' points to the 'buf_fx' or to the fsave header followed by 'buf_fx'. * * buf == buf_fx for 64-bit frames and 32-bit fsave frame. * buf != buf_fx for 32-bit frames with fxstate. * * If the fpu, extended register state is live, save the state directly * to the user frame pointed by the aligned pointer 'buf_fx'. Otherwise, * copy the thread's fpu state to the user frame starting at 'buf_fx'. * * If this is a 32-bit frame with fxstate, put a fsave header before * the aligned state at 'buf_fx'. * * For [f]xsave state, update the SW reserved fields in the [f]xsave frame * indicating the absence/presence of the extended state to the user. */ int copy_fpstate_to_sigframe(void __user *buf, void __user *buf_fx, int size) { struct fpu *fpu = &current->thread.fpu; struct xregs_state *xsave = &fpu->state.xsave; struct task_struct *tsk = current; int ia32_fxstate = (buf != buf_fx); ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) || IS_ENABLED(CONFIG_IA32_EMULATION)); if (!access_ok(VERIFY_WRITE, buf, size)) return -EACCES; if (!static_cpu_has(X86_FEATURE_FPU)) return fpregs_soft_get(current, NULL, 0, sizeof(struct user_i387_ia32_struct), NULL, (struct _fpstate_32 __user *) buf) ? -1 : 1; if (fpu->fpstate_active || using_compacted_format()) { /* Save the live register state to the user directly. */ if (copy_fpregs_to_sigframe(buf_fx)) return -1; /* Update the thread's fxstate to save the fsave header. */ if (ia32_fxstate) copy_fxregs_to_kernel(fpu); } else { /* * It is a *bug* if kernel uses compacted-format for xsave * area and we copy it out directly to a signal frame. It * should have been handled above by saving the registers * directly. */ if (boot_cpu_has(X86_FEATURE_XSAVES)) { WARN_ONCE(1, "x86/fpu: saving compacted-format xsave area to a signal frame!\n"); return -1; } fpstate_sanitize_xstate(fpu); if (__copy_to_user(buf_fx, xsave, fpu_user_xstate_size)) return -1; } /* Save the fsave header for the 32-bit frames. */ if ((ia32_fxstate || !use_fxsr()) && save_fsave_header(tsk, buf)) return -1; if (use_fxsr() && save_xstate_epilog(buf_fx, ia32_fxstate)) return -1; return 0; } static inline void sanitize_restored_xstate(struct task_struct *tsk, struct user_i387_ia32_struct *ia32_env, u64 xfeatures, int fx_only) { struct xregs_state *xsave = &tsk->thread.fpu.state.xsave; struct xstate_header *header = &xsave->header; if (use_xsave()) { /* These bits must be zero. */ memset(header->reserved, 0, 48); /* * Init the state that is not present in the memory * layout and not enabled by the OS. */ if (fx_only) header->xfeatures = XFEATURE_MASK_FPSSE; else header->xfeatures &= (xfeatures_mask & xfeatures); } if (use_fxsr()) { /* * mscsr reserved bits must be masked to zero for security * reasons. */ xsave->i387.mxcsr &= mxcsr_feature_mask; convert_to_fxsr(tsk, ia32_env); } } /* * Restore the extended state if present. Otherwise, restore the FP/SSE state. */ static inline int copy_user_to_fpregs_zeroing(void __user *buf, u64 xbv, int fx_only) { if (use_xsave()) { if ((unsigned long)buf % 64 || fx_only) { u64 init_bv = xfeatures_mask & ~XFEATURE_MASK_FPSSE; copy_kernel_to_xregs(&init_fpstate.xsave, init_bv); return copy_user_to_fxregs(buf); } else { u64 init_bv = xfeatures_mask & ~xbv; if (unlikely(init_bv)) copy_kernel_to_xregs(&init_fpstate.xsave, init_bv); return copy_user_to_xregs(buf, xbv); } } else if (use_fxsr()) { return copy_user_to_fxregs(buf); } else return copy_user_to_fregs(buf); } static int __fpu__restore_sig(void __user *buf, void __user *buf_fx, int size) { int ia32_fxstate = (buf != buf_fx); struct task_struct *tsk = current; struct fpu *fpu = &tsk->thread.fpu; int state_size = fpu_kernel_xstate_size; u64 xfeatures = 0; int fx_only = 0; ia32_fxstate &= (IS_ENABLED(CONFIG_X86_32) || IS_ENABLED(CONFIG_IA32_EMULATION)); if (!buf) { fpu__clear(fpu); return 0; } if (!access_ok(VERIFY_READ, buf, size)) return -EACCES; fpu__activate_curr(fpu); if (!static_cpu_has(X86_FEATURE_FPU)) return fpregs_soft_set(current, NULL, 0, sizeof(struct user_i387_ia32_struct), NULL, buf) != 0; if (use_xsave()) { struct _fpx_sw_bytes fx_sw_user; if (unlikely(check_for_xstate(buf_fx, buf_fx, &fx_sw_user))) { /* * Couldn't find the extended state information in the * memory layout. Restore just the FP/SSE and init all * the other extended state. */ state_size = sizeof(struct fxregs_state); fx_only = 1; trace_x86_fpu_xstate_check_failed(fpu); } else { state_size = fx_sw_user.xstate_size; xfeatures = fx_sw_user.xfeatures; } } if (ia32_fxstate) { /* * For 32-bit frames with fxstate, copy the user state to the * thread's fpu state, reconstruct fxstate from the fsave * header. Sanitize the copied state etc. */ struct fpu *fpu = &tsk->thread.fpu; struct user_i387_ia32_struct env; int err = 0; /* * Drop the current fpu which clears fpu->fpstate_active. This ensures * that any context-switch during the copy of the new state, * avoids the intermediate state from getting restored/saved. * Thus avoiding the new restored state from getting corrupted. * We will be ready to restore/save the state only after * fpu->fpstate_active is again set. */ fpu__drop(fpu); if (using_compacted_format()) err = copy_user_to_xstate(&fpu->state.xsave, buf_fx); else err = __copy_from_user(&fpu->state.xsave, buf_fx, state_size); if (err || __copy_from_user(&env, buf, sizeof(env))) { fpstate_init(&fpu->state); trace_x86_fpu_init_state(fpu); err = -1; } else { sanitize_restored_xstate(tsk, &env, xfeatures, fx_only); } fpu->fpstate_active = 1; preempt_disable(); fpu__restore(fpu); preempt_enable(); return err; } else { /* * For 64-bit frames and 32-bit fsave frames, restore the user * state to the registers directly (with exceptions handled). */ user_fpu_begin(); if (copy_user_to_fpregs_zeroing(buf_fx, xfeatures, fx_only)) { fpu__clear(fpu); return -1; } } return 0; } static inline int xstate_sigframe_size(void) { return use_xsave() ? fpu_user_xstate_size + FP_XSTATE_MAGIC2_SIZE : fpu_user_xstate_size; } /* * Restore FPU state from a sigframe: */ int fpu__restore_sig(void __user *buf, int ia32_frame) { void __user *buf_fx = buf; int size = xstate_sigframe_size(); if (ia32_frame && use_fxsr()) { buf_fx = buf + sizeof(struct fregs_state); size += sizeof(struct fregs_state); } return __fpu__restore_sig(buf, buf_fx, size); } unsigned long fpu__alloc_mathframe(unsigned long sp, int ia32_frame, unsigned long *buf_fx, unsigned long *size) { unsigned long frame_size = xstate_sigframe_size(); *buf_fx = sp = round_down(sp - frame_size, 64); if (ia32_frame && use_fxsr()) { frame_size += sizeof(struct fregs_state); sp -= sizeof(struct fregs_state); } *size = frame_size; return sp; } /* * Prepare the SW reserved portion of the fxsave memory layout, indicating * the presence of the extended state information in the memory layout * pointed by the fpstate pointer in the sigcontext. * This will be saved when ever the FP and extended state context is * saved on the user stack during the signal handler delivery to the user. */ void fpu__init_prepare_fx_sw_frame(void) { int size = fpu_user_xstate_size + FP_XSTATE_MAGIC2_SIZE; fx_sw_reserved.magic1 = FP_XSTATE_MAGIC1; fx_sw_reserved.extended_size = size; fx_sw_reserved.xfeatures = xfeatures_mask; fx_sw_reserved.xstate_size = fpu_user_xstate_size; if (IS_ENABLED(CONFIG_IA32_EMULATION) || IS_ENABLED(CONFIG_X86_32)) { int fsave_header_size = sizeof(struct fregs_state); fx_sw_reserved_ia32 = fx_sw_reserved; fx_sw_reserved_ia32.extended_size = size + fsave_header_size; } }
./CrossVul/dataset_final_sorted/CWE-200/c/bad_2864_1